17-07-2004
Copyright © 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004 Gruppo di Documentazione PHP
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/).
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.
PHP (acronimo ricorsivo per "PHP: Hypertext Preprocessor") è un linguaggio di scripting general-purpose Open Source molto utilizzato, è specialmente indicato per lo sviluppo Web e può essere integrato nell'HTML.
Risposta banale, ma che cosa significa? Un esempio:
Notate come questo esempio è differente da uno script scritto in altri linguaggi tipo Perl o C -- invece di scrivere un programma con parecchi comandi per produrre HTML, si scrive in HTML con qualche comando immerso per ottenere dei risultati (in questo semplice esempio, la visualizzazione di una frase). Il codice PHP è delimitato da speciali start ed end tag che ne indicano l'inizio e la fine e che consentono di passare dal modo HTML al modo PHP.
Ciò che distingue PHP da altri linguaggi di scripting del tipo client-side JavaScript è che il codice viene eseguito nel server. Per avere uno script simile a quello sopra nel vostro server, il client dovrebbe ricevere il risultato ottenuto con lo script, senza sapere mai quali sono le funzioni eseguite. Potete persino configurare il vostro web server per processare tutte i vostri file HTML con PHP ed allora non ci sarebbe realmente alcun modo per gli utenti di sapere cosa avete sul vostro server.
La cosa più interessante nell'uso di PHP è che si tratta di un linguaggio estremamente semplice per il neofita, ma che, tuttavia, offre molte prestazioni avanzate al programmatore di professione. Non lasciatevi impressionare dalla lunga lista delle potenzialità di PHP. In poco tempo potrete iniziare a creare velocemente semplici scripts.
Sebbene lo sviluppo di PHP abbia come obiettivo lo scripting server-side, si può fare molto di più con esso. Leggete, e consultate la sezione Che cosa può fare PHP?.
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:
Esiste anche un'estensione DBX database abstraction extension, che vi permette di usare in modo trasparente qualsiasi database da essa supportato. Inoltre PHP supporta ODBC, lo standard di collegamento con i database, pertanto è possibile collegarsi con qualsiasi database che supporti questo standard mondiale.
Adabas D Ingres Oracle (OCI7 and OCI8) dBase InterBase Ovrimos Empress FrontBase PostgreSQL FilePro (read-only) mSQL Solid Hyperwave Direct MS-SQL Sybase IBM DB2 MySQL Velocis Informix ODBC Unix dbm
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
Di seguito, in una breve e semplice introduzione, vorremmo mostrare alcuni esempi per l'utilizzo di PHP. Essi sono relativi soltanto alla creazione dinamica di pagine web, anche se PHP non ha funzionalità limitate esclusivamente alla creazione delle sole pagine web. Fare riferimento alla sezione intitolata Cosa può fare PHP per avere ulteriori informazioni.
Le pagine web create con PHP vengono trattate come normali pagine HTML e possono essere create e modificate nello stesso modo in cui si sviluppano normali pagine HTML.
In questo tutorial assumiamo che il vostro server abbia il suporto PHP attivato e che tutti i file con estensione .php vengano gestiti da questo. Quasi in tutti i server questa è l'estensione di default per i file PHP., ma consultatevi col vostro system administrator per sicurezza. Se il vostro server supporta PHP, allora, non è necessario fare nulla. Semplicemente create i vostri file .php e scaricateli nella vostra directory web, il server le analizzerà e le eseguirà magicamente. Non è necessario compilare nulla nè installare strumenti aggiuntivi. Si pensi ai file PHP come a dei semplici file HTML con una intera famiglia aggiuntiva di magici tags che consentono di fare ogni sorta di cose.
Creare un file con nome ciao.php nella directory del web server che abbia il seguente contenuto:
Si noti che questo file non è come uno script CGI. Il file non necessita in alcun modo di essere eseguibile o speciale in alcuna maniera. Si pensi ad esso come ad un normale file HTML nel quale sono contenuti uno speciale set di tags che permettono di eseguire una moltitudine di cose interessanti.
Questo programma è molto semplice e sicuramente non era necessario fare ricorso a PHP per creare una pagina come quella. Tutto ciò che essa fa è di visualizzare: Hello World! usando la funzione echo() di PHP.
Se si è provato questo esempio e non ha dato alcun output, o è apparso un pop-up che chiedeva se scaricare la pagina, o se è apparso il file come testo, probabilmente che il server su cui si stanno effettuando le prove non ha abilitato PHP. Provare a chiedere al proprio amministratore di sistema di abilitarlo per voi usando il capitolo del manuale dedicato all'Installazione. Se si vogliono sviluppare in locale script PHP, fare riferimento alla sezione download. Si può sviluppare senza problemi sul proprio Sistema Operativo in locale, è bene installare anche un web server.
L'obiettivo dell'esempio è quello di mostrare il formato speciale dei tag PHP. In questo esempio abbiamo usato <?php per indicare l'inizio di un tag PHP. Quindi abbiamo scritto la funzione PHP e abbiamo lasciato la modalità PHP usando il tag di chiusura, ?>. All'interno di un file HTML si può entrare ed uscire dalla modalità PHP quante volte si desidera.
Nota riguardo gli editor di testo: Esistomo molti editor di testo e Integrated Development Environment (IDE) che possono essere usati per creare, modificare e gestire file PHP. Una lista parziale di questi strumenti è disponibile qui: PHP Editor's List. Se si desidera suggerire un nuovo programma, visitare la pagina sopra e chiedere al curatore di aggiungerlo alla lista.
Nota riguardo i Word Processor: Word processor quali StarOffice Writer, Microsoft Word e Abiword non sono una buona scelta per modificare i file PHP.
Se si vogliono provare comunque per scrivere questo script di test, ci si deve assicurare di salvare il file come SOLO TESTO, altrimenti PHP non sarà in grado di leggerlo e quindi non riuscirà ad eseguire lo script.
Nota riguardo Blocco Note di Windows: Se si scrive codice usando l'applicazione di Windows Blocco Note, occorre assicurarsi che i file vengano salvati con estensione .php. (Blocco Note aggiunge automaticamente l'estensione .txt ai file, a meno che non si intraprenda uno dei passi descritti di seguito.)
Quando si salva il file e viene chiesto il nome da assegnargli, scrivere il nome fra virgolette (ad esempio: "ciao.php").
In alternativa, si può cliccare sul menu a tendina 'Documenti di Testo' nella finestra di salvataggio e cambiare l'impostazione in "Tutti i File". A quel punto si può inserire il nome del file, senza usare le virgolette.
Andiamo a fare qualcosa di leggermente più utile. Andremo a controllare che tipo di browser sta utilizzando la persona che visita le nostre pagine. Per fare questo si andrà a controllare la stringa dell'user agent che il browser invia come parte della richiesta HTTP. Quest'informazione viene inviata in una variabile. Le Variabili iniziano sempre con il simbolo di dollaro $ in PHP. La variabile alla quale ci riferiamo adesso è $_SERVER["HTTP_USER_AGENT"].
Note sulle variabili Autoglobali di PHP: $_SERVER è una variabile speciale riservata a PHP la quale contiene tutte le informazioni relative al Web Server. È conosciuta come Variabile autoglobale (o Superglobale). Per maggiori informazioni è possibile vedere la pagina del manuale relativa alle Variabili Autoglobali. Questo tipo di variabili sono state introdotte nella versione 4.1.0 di PHP. Nelle versioni precedenti abbiamo utilizzato le ormai vecchie $HTTP_SERVER_VARS, oggi in disuso, anche se queste continuano ad esistere. (Potete guardare nelle note del vecchio codice.)
Per visualizzare questa variabile, dobbiamo semplicemente:
Ci sono molti types (tipi) di variabili disponibili in PHP. Nell'esempio di sopra abbiamo stampato un elemento di un Array. Gli Array possono essere molto utili.
$_SERVER è soltanto una variabile che automaticamente viene resa diponibile da PHP. È possibile visualizzare una lunga lista nella sezione Variabili riservate del manuale oppure ottenere la lista completa creando un file php nella seguente forma:
Se caricate questo documento da un browser riceverete una pagina piena d'informazioni circa PHP, così come la lista di tutte le variabili disponibili.
Potete mettere dichiarazioni multipli di PHP all'interno di un tag di PHP e generare piccoli blocchi di codice che fanno di più di un singolo echo. Per esempio, se desiderassimo controllare per vedere se l'utente usa Internet Explorer potremmo fare qualcosa come questo:
Esempio 2-4. Esempi usando le strutture di controllo e le funzioni
L'output di esempio di questo script potrebbe essere:
|
Qui introduciamo una coppia di nuovi concetti. Abbiamo la dichiarazione if (se). Se avete una conoscenza con la sintassi di base usata dal linguaggio C questo dovrebbe sembrare logico per voi. Se non conoscete abbastanza C od un altro linguaggio che utilizza la sintassi qui sopra descritta, dovreste probabilmente prendere qualsiasi libro introduttivo di PHP e leggere i primi capitoli, o leggere la parte del manuale relativa ai Riferimenti del Linguaggio. Potete trovare una lista dei libri di PHP su http://www.php.net/books.php.
Il secondo concetto che abbiamo introdotto era la chiamata alla funzione strstr(). Questa è una funzione sviluppata in PHP che cerca una stringa all'interno di un'altra stringa. In questo caso abbiamo cercato "MSIE" all'interno della stringa $_SERVER["HTTP_USER_AGENT"]. Se la stringa viene trovata, la funzione restituisce TRUE altrimenti, FALSE. Se restituisce TRUE, la dichiarazione if viene valuta come TRUE ed il codice all'interno dei relativi {braces} (sostegni) sarà eseguito. Altrimenti, non esegue altro. Sentitevi liberi di generare esempi simili, con if, else (altrimenti) ed altre funzioni quali strtoupper() e strlen(). Ogni pagina del manuale, relativa a queste funzioni contiene anche degli esempi pratici.
Possiamo fare un passo avanti e mostrarvi come potete entrare ed uscite dal modo PHP anche dall' interno di un blocco PHP:
Invece di usare la dichiarazione echo per fare l'output di qualcosa, saltiamo fuori dal modo PHP inviando soltanto HTML puro. Il punto importante da notare qui è che il flusso logico dello script rimane intatto. Solo uno dei blocchi di di HTML finirà per essere inviato come risposta, dipendendo se strstr() ritorna TRUE o FALSE in altre parole, se la stringa MSIE viene trovata o meno.
Una delle caratteritiche più forti di PHP è il modo in cui gestisce i form. Il concetto da comprendere principalmente è che qualsiasi elemento di un form sarà automaticamente disponibile per i vostri script PHP. Per maggiori informazioni ed esempi relativi all'utilizzo dei form consultate la sezione del manuale che si riferisce a le Variabili al di fuori di PHP. A seguire un esempio di un form HTML:
Questo form non ha niente di speciale. È un semplice form in HTML che non presenta nessun tipo di tags particolari. Quando l'utente riempie questo form e preme il pulsante submit, viene richiamata la pagina action.php. In questo file il risultato sarà qualcosa di simile:
Ciò che avviene dovrebbe risultare ovvio. Non c' è altro da aggiungere. Le variabili $_POST["name"] e $_POST["age"] vengono impostate automaticamente dal PHP. Prima avevamo usato la variabile autoglobal $_SERVER, ora invece abbiamo introdotto la variabile autoglobal $_POST che contiene tutti i dati di tipo POST. Notate che il metodo del nostro form è il POST. Se usassimo il metodo GET le informazioni ricavate dal nostro form si troverebbero invece in $_GET. Si può anche usare la variabile $_REQUEST se la provenienza dei dati richiesti non ci interessa. Questa variabile contiene un misto di dati GET, POST, COOKIE e FILE. Vedere anche la funzione import_request_variables().
Da quando il PHP è divenuto un linguaggio di scripting popolare, esistono più fonti che producono listati di codice che si possono adoperare nei propri scripts. La maggioranza degli sviluppatori del PHP ha cercato di renderlo compatibile con le versioni precedenti, perciò uno script creato per una vecchia versione del PHP dovrebbe girare senza modifiche (in teoria) in una più recente, ma in pratica spesso possono servire delle correzioni.
Ecco due delle più importanti modifiche apportate al vecchio codice:
Il disuso dei vecchi arrays $HTTP_*_VARS (che devono essere dichiarati global quando vengano adoperati all' interno di una funzione o di un metodo). L' introduzione in PHP 4.1.0 dei seguenti autoglobal arrays: $_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, $_REQUEST, and $_SESSION. I vecchi arrays $HTTP_*_VARS quali $HTTP_POST_VARS, invece, continuano ad essere adoperati fin da PHP3.
Le variabili esterne non vengono più registrate nel global scope per default. In altre parole, da PHP 4.2.0 la direttiva PHP register_globals è off per default in php.ini. Il metodo consigliato per accedere a questi valori è quello che fa uso degli arrays autoglobali suddetti. Scripts, libri e tutorials più vecchi devono attenersi a queste direttive. Se, per esempio, qualcuno potesse usare $id dall'URL http://www.example.com/foo.php?id=42. La variabile, $_GET['id'] sarebbe disponibile indifferentemente del fatto che sia on od off.
Con quello che sapete ora dovreste essere in grado di comprendere la maggior parte del manuale ed anche i vari scripts di esempio reperibili nelle raccolte di esempi. Inoltre potete trovarne altri sui siti web di php.net nella sezione links: http://www.php.net/links.php.
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.
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.
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.
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.
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.
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
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.
Scaricare i sorgenti di PHP e Apache.
Eseguire gunzip e tar -xvf. Ora dobbiamo modificare un paio di file in modo da poterli compilare.
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.
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
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.
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.
Questa sezione contiene note e suggerimenti specifici dell'installazione di PHP su distribuzioni Unix.
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.
This section contains notes and hints specific to installing PHP on Mac OS X Server.
There are a few pre-packaged and pre-compiled versions of PHP for Mac OS X. This can help in setting up a standard configuration, but if you need to have a different set of features (such as a secure server, or a different database driver), you may need to build PHP and/or your web server yourself. If you are unfamiliar with building and compiling your own software, it's worth checking whether somebody has already built a packaged version of PHP with the features you need.
There are two slightly different versions of Mac OS X, client and server. The following is for OS X Server.
Get the latest distributions of Apache and PHP.
Untar them, and run the configure program on Apache like so.
./configure --exec-prefix=/usr \ --localstatedir=/var \ --mandir=/usr/share/man \ --libexecdir=/System/Library/Apache/Modules \ --iconsdir=/System/Library/Apache/Icons \ --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \ --enable-shared=max \ --enable-module=most \ --target=apache |
If you want the compiler to do some optimization., you may also want to add this line:
setenv OPTIM=-O2 |
Next, go to the PHP 4 source directory and configure it.
./configure --prefix=/usr \ --sysconfdir=/etc \ --localstatedir=/var \ --mandir=/usr/share/man \ --with-xml \ --with-apache=/src/apache_1.3.12 |
Type make and make install. This will add a directory to your Apache source directory under src/modules/php4.
Now, reconfigure Apache to build in PHP 4.
./configure --exec-prefix=/usr \ --localstatedir=/var \ --mandir=/usr/share/man \ --libexecdir=/System/Library/Apache/Modules \ --iconsdir=/System/Library/Apache/Icons \ --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \ --enable-shared=max \ --enable-module=most \ --target=apache \ --activate-module=src/modules/php4/libphp4.a |
Copy and rename the php.ini-dist file to your bin directory from your PHP 4 source directory: cp php.ini-dist /usr/local/bin/php.ini or (if your don't have a local directory) cp php.ini-dist /usr/bin/php.ini.
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:
Open a terminal window.
Type wget http://www.diax.ch/users/liyanage/software/macosx/libphp4.so.gz, wait for the download to finish.
Type gunzip libphp4.so.gz.
Type sudo apxs -i -a -n php4 libphp4.so
Now type sudo open -a TextEdit /etc/httpd/httpd.conf. TextEdit will open with the web server configuration file. Locate these two lines towards the end of the file: (Use the Find command)
#AddType application/x-httpd-php .php #AddType application/x-httpd-php-source .phps |
Finally, type sudo apachectl graceful to restart the web server.
PHP should now be up and running. You can test it by dropping a file into your Sites folder which is called test.php. Into that file, write this line: <?php phpinfo() ?>.
Now open up 127.0.0.1/~your_username/test.php in your web browser. You should see a status table with information about the PHP module.
This section contains notes and hints specific to installing PHP on OpenBSD 3.4.
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
|
Read the packages(7) manual page for more information about binary packages on OpenBSD.
You can also compile up PHP from source using the ports tree. However, this is only recommended for users familiar with OpenBSD. The PHP 4 port is split into two sub-directories: core and extensions. The extensions directory generates sub-packages for all of the supported PHP modules. If you find you do not want to create some of these modules, use the no_* FLAVOR. For example, to skip building the imap module, set the FLAVOR to no_imap.
The default install of Apache runs inside a chroot(2) jail, which will restrict PHP scripts to accessing files under /var/www. You will therefore need to create a /var/www/tmp directory for PHP session files to be stored, or use an alternative session backend. In addition, database sockets need to be placed inside the jail or listen on the localhost interface. If you use network functions, some files from /etc such as /etc/resolv.conf and /etc/services will need to be moved into /var/www/etc. The OpenBSD PEAR package automatically installs into the correct chroot directories, so no special modification is needed there. More information on the OpenBSD Apache is available in the OpenBSD FAQ.
The OpenBSD 3.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 of OpenBSD used the FLAVORS system to compile up a statically linked PHP. Since it is hard to generate binary packages using this method, it is now deprecated. You can still use the old stable ports trees if you wish, but they are unsupported by the OpenBSD team. If you have any comments about this, the current maintainer for the port is Anil Madhavapeddy (avsm at openbsd dot org).
This section contains notes and hints specific to installing PHP on Solaris systems.
Solaris installs often lack C compilers and their related tools. Read this FAQ for information on why using GNU versions for some of these tools is necessary. The required software is as follows:
gcc (recommended, other C compilers may work)
make
flex
bison
m4
autoconf
automake
perl
gzip
tar
GNU sed
You can simplify the Solaris install process by using pkgadd to install most of your needed components.
This section will guide you through the general configuration and installation of PHP on Unix systems. Be sure to investigate any sections specific to your platform or web server before you begin the process.
Prerequisite knowledge and software:
Basic Unix skills (being able to operate "make" and a C compiler, if compiling)
An ANSI C compiler (if compiling)
flex (for compiling)
bison (for compiling)
A web server
Any module specific components (such as gd, pdf libs, etc.)
There are several ways to install PHP for the Unix platform, either with a compile and configure process, or through various pre-packaged methods. This documentation is mainly focused around the process of compiling and configuring PHP.
The initial PHP setup and configuration process is controlled by the use of the commandline options of the configure script. This page outlines the usage of the most common options, but there are many others to play with. Check out the Complete list of configure options for an exhaustive rundown. There are several ways to install PHP:
As an Apache 1.x module or an Apache 2.x module.
As an Pike module for Caudium
For use with AOLServer, NSAPI, phttpd, Pi3Web, Roxen, thttpd, or Zeus.
As a CGI executable
PHP can be compiled in a number of different ways, but one of the most popular is as an Apache module. The following is a quick installation overview.
Esempio 3-2. Quick Installation Instructions for PHP 4 (Apache Module Version)
|
When PHP is configured, you are ready to build the CGI executable. The command make should take care of this. If it fails and you can't figure out why, see the Problems section.
This section applies to Windows 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.
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. |
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 |
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 |
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:
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:
.. the Windows server family, Personal Web server (PWS) 3 and 4 or newer; Internet Information Server (IIS) 3 and 4 or newer.
.. the Apache servers Apache 1.3.x, and Apache 2.x.
.. the Netscape/iPlanet servers.
.. the OmniHTTPd server.
.. the Oreilly Website Pro server.
.. the Sambar server.
.. the Xitami server.
Before getting started, it is worthwhile answering the question: "Why is building on Windows so hard?" Two reasons come to mind:
Windows does not (yet) enjoy a large community of developers who are willing to freely share their source. As a direct result, the necessary investment in infrastructure required to support such development hasn't been made. By and large, what is available has been made possible by the porting of necessary utilities from Unix. Don't be surprised if some of this heritage shows through from time to time.
Pretty much all of the instructions that follow are of the "set and forget" variety. So sit back and try follow the instructions below as faithfully as you can.
To compile and build PHP you need a Microsoft Development Environment. Microsoft 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...
..the win32 buildtools from the PHP site at http://www.php.net/extra/win32build.zip.
..the source code for the DNS name resolver used by PHP from http://www.php.net/extra/bindlib_w32.zip. This is a replacement for the resolv.lib library included in win32build.zip.
If you plan to compile PHP as a Apache module you will also need the Apache sources.
Finally, you are going to need the source to PHP 4 itself. You can get the latest development version using anonymous CVS, a snapshot or the most recent released source tarball.
After downloading the required packages you have to extract them in a proper place.
Create a working directory where all files end up after extracting, e.g: C:\work.
Create the directory win32build under your working directory (C:\work) and unzip win32build.zip into it.
Create the directory bindlib_w32 under your working directory (C:\work) and unzip bindlib_w32.zip into it.
Extract the downloaded PHP source code into your working directory (C:\work).
+--c:\work | | | +--bindlib_w32 | | | | | +--arpa | | | | | +--conf | | | | | +--... | | | +--php-4.x.x | | | | | +--build | | | | | +--... | | | | | +--win32 | | | | | +--... | | | +--win32build | | | | | +--bin | | | | | +--include | | | | | +--lib |
Nota: Cygwin users may omit the last step. A properly installed Cygwin environment provides the mandatory files bison.simple and bison.exe.
The next step is to configure MVC ++ to prepare for compiling. Launch Microsoft Visual C++, and from the menu select Tools => Options. In the dialog, select the directories tab. Sequentially change the dropdown to Executables, Includes, and Library files. Your entries should look like this:
Executable files: c:\work\win32build\bin, Cygwin users: cygwin\bin
Include files: c:\work\win32build\include
Library files: c:\work\win32build\lib
You must build the resolv.lib library. Decide whether you want to have debug symbols available (bindlib - Win32 Debug) or not (bindlib - Win32 Release). Build the appropriate configuration:
For GUI users, launch VC++, and then select File => Open Workspace, navigate to c:\work\bindlib_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"
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.
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:
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
|
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 |
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
Extension | Description | Notes |
---|---|---|
php_bz2.dll | bzip2 compression functions | None |
php_calendar.dll | Calendar conversion functions | Built in since PHP 4.0.3 |
php_cpdf.dll | ClibPDF functions | None |
php_crack.dll | Crack functions | None |
php3_crypt.dll | Crypt functions | unknown |
php_ctype.dll | ctype family functions | Built in since PHP 4.3.0 |
php_curl.dll | CURL, Client URL library functions | Requires: libeay32.dll, ssleay32.dll (bundled) |
php_cybercash.dll | Cybercash payment functions | PHP <= 4.2.0 |
php_db.dll | DBM functions | Deprecated. Use DBA instead (php_dba.dll) |
php_dba.dll | DBA: DataBase (dbm-style) Abstraction layer functions | None |
php_dbase.dll | dBase functions | None |
php3_dbm.dll | Berkeley DB2 library | unknown |
php_dbx.dll | dbx functions | |
php_domxml.dll | DOM XML functions | PHP <= 4.2.0 requires: libxml2.dll (bundled) PHP >= 4.3.0 requires: iconv.dll (bundled) |
php_dotnet.dll | .NET functions | PHP <= 4.1.1 |
php_exif.dll | Read EXIF headers from JPEG | None |
php_fbsql.dll | FrontBase functions | PHP <= 4.2.0 |
php_fdf.dll | FDF: Forms Data Format functions. | Requires: fdftk.dll (bundled) |
php_filepro.dll | filePro functions | Read-only access |
php_ftp.dll | FTP functions | Built-in since PHP 4.0.3 |
php_gd.dll | GD library image functions | Removed in PHP 4.3.2. Also note that truecolor functions are not available in GD1, instead, use php_gd2.dll. |
php_gd2.dll | GD library image functions | GD2 |
php_gettext.dll | Gettext functions | PHP <= 4.2.0 requires gnu_gettext.dll (bundled), PHP >= 4.2.3 requires libintl-1.dll, iconv.dll (bundled). |
php_hyperwave.dll | HyperWave functions | None |
php_iconv.dll | ICONV characterset conversion | Requires: iconv-1.3.dll (bundled), PHP >=4.2.1 iconv.dll |
php_ifx.dll | Informix functions | Requires: Informix libraries |
php_iisfunc.dll | IIS management functions | None |
php_imap.dll | IMAP POP3 and NNTP functions | PHP 3: php3_imap4r1.dll |
php_ingres.dll | Ingres II functions | Requires: Ingres II libraries |
php_interbase.dll | InterBase functions | Requires: gds32.dll (bundled) |
php_java.dll | Java functions | PHP <= 4.0.6 requires: jvm.dll (bundled) |
php_ldap.dll | LDAP functions | PHP <= 4.2.0 requires libsasl.dll (bundled), PHP >= 4.3.0 requires libeay32.dll, ssleay32.dll (bundled) |
php_mbstring.dll | Multi-Byte String functions | None |
php_mcrypt.dll | Mcrypt Encryption functions | Requires: libmcrypt.dll |
php_mhash.dll | Mhash functions | PHP >= 4.3.0 requires: libmhash.dll (bundled) |
php_mime_magic.dll | Mimetype functions | Requires: magic.mime (bundled) |
php_ming.dll | Ming functions for Flash | None |
php_msql.dll | mSQL functions | Requires: msql.dll (bundled) |
php3_msql1.dll | mSQL 1 client | unknown |
php3_msql2.dll | mSQL 2 client | unknown |
php_mssql.dll | MSSQL functions | Requires: ntwdblib.dll (bundled) |
php3_mysql.dll | MySQL functions | Built-in in PHP 4 |
php3_nsmail.dll | Netscape mail functions | unknown |
php3_oci73.dll | Oracle functions | unknown |
php_oci8.dll | Oracle 8 functions | Requires: Oracle 8.1+ client libraries |
php_openssl.dll | OpenSSL functions | Requires: libeay32.dll (bundled) |
php_oracle.dll | Oracle functions | Requires: Oracle 7 client libraries |
php_overload.dll | Object overloading functions | Built in since PHP 4.3.0 |
php_pdf.dll | PDF functions | None |
php_pgsql.dll | PostgreSQL functions | None |
php_printer.dll | Printer functions | None |
php_shmop.dll | Shared Memory functions | None |
php_snmp.dll | SNMP get and walk functions | NT only! |
php_sockets.dll | Socket functions | None |
php_sybase_ct.dll | Sybase functions | Requires: Sybase client libraries |
php_tokenizer.dll | Tokenizer functions | Built in since PHP 4.3.0 |
php_w32api.dll | W32api functions | None |
php_xmlrpc.dll | XML-RPC functions | PHP >= 4.2.1 requires: iconv.dll (bundled) |
php_xslt.dll | XSLT functions | PHP <= 4.2.0 requires sablot.dll, expat.dll (bundled). PHP >= 4.2.1 requires sablot.dll, expat.dll, iconv.dll (bundled). |
php_yaz.dll | YAZ functions | Requires: yaz.dll (bundled) |
php_zip.dll | Zip File functions | Read only access |
php_zlib.dll | ZLib compression functions | Built in since PHP 4.3.0 |
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.
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.
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.
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
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.
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.
|
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
|
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:
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.
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().
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.
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:
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.
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"
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".
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.
Se seguente versioni di PHP funzionano correttamente con le ultime versioni di Apache 2.0:
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.
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)
|
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.
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:
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
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. |
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
|
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.
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.
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.
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.
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.
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)
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
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.
Install the following packages from http://www.sunfreeware.com/ or another download site:
autoconf-2.13 |
automake-1.4 |
bison-1_25-sol26-sparc-local |
flex-2_5_4a-sol26-sparc-local |
gcc-2_95_2-sol26-sparc-local |
gzip-1.2.4-sol26-sparc-local |
m4-1_4-sol26-sparc-local |
make-3_76_1-sol26-sparc-local |
mysql-3.23.24-beta (if you want mysql support) |
perl-5_005_03-sol26-sparc-local |
tar-1.13 (GNU tar) |
Make sure your path includes the proper directories PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/bin and make it available to your system export PATH.
gunzip php-x.x.x.tar.gz (if you have a .gz dist, otherwise go to 4).
tar xvf php-x.x.x.tar
Change to your extracted PHP directory: cd ../php-x.x.x
For the following step, make sure /opt/netscape/suitespot/ is where your netscape server is installed. Otherwise, change to the correct path and run:
./configure --with-mysql=/usr/local/mysql \ --with-nsapi=/opt/netscape/suitespot/ \ --enable-libgcc |
Run make followed by make install.
After performing the base install and reading the appropriate readme file, you may need to perform some additional configuration steps.
Configuration Instructions for 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/.
Add the following line to mime.types (you can do that by the administration server):
type=magnus-internal/x-httpd-php exts=php |
Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following, shlib will vary depending on your 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"] |
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> |
This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):
<Object name="x-httpd-php"> ObjectType fn="force-type" type="magnus-internal/x-httpd-php" Service fn=php4_execute [inikey=value inikey=value ...] </Object> |
Setup of authentication: PHP authentication cannot be used with any other authentication. ALL AUTHENTICATION IS PASSED TO YOUR PHP SCRIPT. To configure PHP Authentication for the entire server, add the following line to your default object:
<Object name="default"> AuthTrans fn=php4_auth_trans . . . </Object> |
To use PHP Authentication on a single directory, add the following:
<Object ppath="d:\path\to\authenticated\dir\*"> AuthTrans fn=php4_auth_trans </Object> |
Nota: The stacksize that PHP uses depends on the configuration of the webserver. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").
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"] |
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 ...] |
This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):
<Object name="x-httpd-php"> ObjectType fn="force-type" type="magnus-internal/x-httpd-php" Service fn=php4_execute [inikey=value inikey=value ...] </Object> |
Restart your web service and apply changes
Do it for each web server instance you want PHP to run
Nota: More details about setting up PHP as an NSAPI filter can be found here: http://benoit.noss.free.fr/php/install-php4.html
Nota: The stacksize that PHP uses depends on the configuration of the webserver. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").
Important when writing PHP scripts is the fact that 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 |
You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:
Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...] |
Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:
Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...] |
The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the webserver and insert the result in the webpage. The problem is, that this function uses some undocumented features from the NSAPI library.
Under Unix this is not a problem, because the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.
Under Windows limitations in the DLL handling need the use of a automatic detection of the most recent ns-httpdXX.dll file. This is tested for servers till version 6.1. If a newer version of the 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" |
You can check the status by using the phpinfo() function.
Nota: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!
This section contains notes and hints specific to OmniHTTPd.
You need to complete the following steps to make PHP work with OmniHTTPd. This is a CGI executable setup. SAPI is supported by OmniHTTPd, but some tests have shown that it is not so stable to use PHP as an ISAPI module.
Important for CGI users: Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0.
Install OmniHTTPd server.
Right click on the blue OmniHTTPd icon in the system tray and select Properties
Click on Web Server Global Settings
On the 'External' tab, enter: virtual = .php | actual = c:\path-to-php-dir\php.exe, and use the Add button.
On the Mime tab, enter: virtual = wwwserver/stdcgi | actual = .php, and use the Add button.
Click OK
Repeat steps 2 - 6 for each extension you want to associate with PHP.
Nota: Some OmniHTTPd packages come with built in PHP support. You can choose at setup time to do a custom setup, and uncheck the PHP component. We recommend you to use the latest PHP binaries. Some OmniHTTPd servers come with PHP 4 beta distributions, so you should choose not to set up the built in support, but install your own. If the server is already on your machine, use the Replace button in Step 4 and 5 to set the new, correct information.
This section contains notes and hints specific to the Sambar server for Windows.
This list describes how to set up the ISAPI module to work with the Sambar server on Windows.
Find the file called mappings.ini (in the config directory) in the Sambar install directory.
Open mappings.ini and add the following line under [ISAPI]:
Now restart the Sambar server for the changes to take effect.
This section contains notes and hints specific to Xitami.
This list describes how to set up the PHP CGI binary to work with Xitami on Windows.
Important for CGI users: Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0.
Make sure the webserver is running, and point your browser to xitamis admin console (usually http://127.0.0.1/admin), and click on Configuration.
Navigate to the Filters, and put the extension which PHP should parse (i.e. .php) into the field File extensions (.xxx).
In Filter command or script put the path and name of your PHP executable i.e. c:\php\php.exe.
Press the 'Save' icon.
Restart the server to reflect changes.
PHP can be built to support a large number of web servers. Please see Server-related options for a full list of server-related configure options. The PHP CGI binaries are compatible with almost all webservers supporting the CGI standard.
Some problems are more common than others. The most common ones are listed in the PHP FAQ, part of this manual.
If you are still stuck, someone on the PHP installation mailing list may be able to help you. You should check out the archive first, in case someone already answered someone else who had the same problem as you. The archives are available from the support page on http://www.php.net/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.
If you think you have found a bug in PHP, please report it. The PHP developers probably don't know about it, and unless you report it, chances are it won't be fixed. You can report bugs using the bug-tracking system at http://bugs.php.net/. Please do not send bug reports in mailing list or personal letters. The bug system is also suitable to submit feature requests.
Read the How to report a bug document before submitting any bug reports!
The configuration file (called php3.ini in PHP 3, and simply php.ini as of PHP 4) is read when PHP starts up. For the server module versions of PHP, this happens only once when the web server is started. For the CGI and CLI version, it happens on every invocation.
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
|
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_".
Sets the value of the specified directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives. To clear a previously set value use none as the value.
Nota: Don't use php_value to set boolean values. php_flag (see below) should be used instead.
Used to set a boolean configuration directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives.
Sets the value of the specified directive. This can not be used in .htaccess files. Any directive type set with php_admin_value can not be overridden by .htaccess or virtualhost directives. To clear a previously set value use none as the value.
Used to set a boolean configuration directive. This can not be used in .htaccess files. Any directive type set with php_admin_flag can not be overridden by .htaccess or virtualhost directives.
Esempio 4-2. Apache configuration example
|
Attenzione |
PHP constants do not exist outside of PHP. For example, in httpd.conf you can not use PHP constants such as E_ALL or E_NOTICE to set the error_reporting directive as they will have no meaning and will evaluate to 0. Use the associated bitmask values instead. These constants can be used in php.ini |
When running PHP on Windows, the configuration values can be modified on a per-directory basis using the Windows registry. The configuration values are stored in the registry key HKLM\SOFTWARE\PHP\Per Directory Values, in the sub-keys corresponding to the path names. For example, configuration values for the directory c:\inetpub\wwwroot would be stored in the key HKLM\SOFTWARE\PHP\Per Directory Values\c\inetpub\wwwroot. The settings for the directory would be active for any script running from this directory or any subdirectory of it. The values under the key should have the name of the PHP configuration directive and the string value. PHP constants in the values are not parsed.
Regardless of how you run PHP, you can change certain values at runtime of your scripts through ini_set(). See the documentation on the ini_set() page for more information.
If you are interested in a complete list of configuration settings on your system with their current values, you can execute the phpinfo() function, and review the resulting page. You can also access the values of individual configuration directives at runtime using ini_get() or get_cfg_var().
Quando il PHP inizia a esaminare un file, 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
|
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:
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:
Il PHP supporta i commenti dei linguaggi 'C', 'C++' e della shell Unix. Per esempio:
<?php echo "Questo ` un test"; // Questo è un commento su una linea nella stile c++ /* Questo è un commento su più linee ancora un'altra linea di commento */ echo "Questo è un altro test"; echo "Un ultimo test"; # Questo è un commento stile shell Unix ?> |
Lo stile di commento su "una linea", attualmente commenta solo fino alla fine della linea o del blocco corrente di codice PHP.
<h1>Questo è un <?# echo "semplice";?> esempio.</h1> <p>L'intestazione qui sopra dirà 'Questo è un esempio'. |
Occorre fare attenzione nel non annidare i commenti di stile C, situazione che si presenta quando si commentano larghi blocchi di codice.
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.
PHP supports eight primitive types.
Four scalar types:
Two compound types: And finally two special types: This manual also introduces some pseudo-types for readability reasons: You may also find some references to the type "double". Consider double the same as float, the two names exist only for historic reasons.The type of a variable is usually not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used.
Nota: If you want to check out the type and value of a certain expression, use var_dump().
Nota: If you simply want a human-readable representation of the type for debugging, use gettype(). To check for a certain type, do not use gettype(), but use the is_type functions. Some examples:
<?php $bool = TRUE; // a boolean $str = "foo"; // a string $int = 12; // an integer echo gettype($bool); // prints out "boolean" echo gettype($str); // prints out "string" // If this is an integer, increment it by four if (is_int($int)) { $int += 4; } // If $bool is a string, print it out // (does not print out anything) if (is_string($bool)) { echo "String: $bool"; } ?>
If you would like to force a variable to be converted to a certain type, you may either cast the variable or use the settype() function on it.
Note that a variable may be evaluated with different values in certain situations, depending on what type it is at the time. For more information, see the section on Type Juggling. Also, you may be interested in viewing the type comparison tables, as they show examples of various type related comparisons.
This is the easiest type. A boolean expresses a truth value. It can be either TRUE or FALSE.
Nota: The boolean type was introduced in PHP 4.
To specify a boolean literal, use either the keyword TRUE or FALSE. Both are case-insensitive.
Usually you use some kind of operator which returns a boolean value, and then pass it on to a control structure.
To explicitly convert a value to boolean, use either the (bool) or the (boolean) cast. However, in most cases you do not need to use the cast, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
See also Type Juggling.
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
an array with zero elements
an object with zero member variables
the special type NULL (including unset variables)
Avvertimento |
-1 is considered TRUE, like any other non-zero (whether negative or positive) number! |
<?php var_dump((bool) ""); // bool(false) var_dump((bool) 1); // bool(true) var_dump((bool) -2); // bool(true) var_dump((bool) "foo"); // bool(true) var_dump((bool) 2.3e5); // bool(true) var_dump((bool) array(12)); // bool(true) var_dump((bool) array()); // bool(false) var_dump((bool) "false"); // bool(true) ?> |
An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.
See also: Arbitrary length integer / GMP, Floating point numbers, and Arbitrary precision / BCMath
Integers can be specified in decimal (10-based), hexadecimal (16-based) or octal (8-based) notation, optionally preceded by a sign (- or +).
If you use the octal notation, you must precede the number with a 0 (zero), to use hexadecimal notation precede the number with 0x.
If you specify a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, if you perform an operation that results in a number beyond the bounds of the integer type, a float will be returned instead.
<?php $large_number = 2147483647; var_dump($large_number); // output: int(2147483647) $large_number = 2147483648; var_dump($large_number); // output: float(2147483648) // this 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.
To explicitly convert a value to integer, use either the (int) or the (integer) cast. However, in most cases you do not need to use the cast, since a value will be automatically converted if an operator, function or control structure requires an integer argument. You can also convert a value to integer with the function intval().
See also type-juggling.
When converting from float to integer, the number will be rounded towards zero.
If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31), the result is undefined, since the float hasn't got enough precision to give an exact integer result. No warning, not even a notice will be issued in this case!
Avvertimento |
Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results. See for more information the warning about float-precision. |
Attenzione |
Behaviour of converting to integer is undefined for other types. Currently, the behaviour is the same as if the value was first converted to boolean. However, do not rely on this behaviour, as it can change without notice. |
Floating point numbers (AKA "floats", "doubles" or "real numbers") can be specified using any of the following syntaxes:
Formally:LNUM [0-9]+ DNUM ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*) EXPONENT_DNUM ( ({LNUM} | {DNUM}) [eE][+-]? {LNUM}) |
Floating point precision |
It is quite usual that simple decimal fractions like 0.1 or 0.7 cannot be converted into their internal binary counterparts without a little loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8 as the result of the internal representation really being something like 7.9999999999.... This is related to the fact that it is impossible to exactly express some fractions in decimal notation with a finite number of digits. For instance, 1/3 in decimal form becomes 0.3333333. . .. So never trust floating number results to the last digit and never compare floating point numbers for equality. If you really need higher precision, you should use the arbitrary precision math functions or gmp functions instead. |
For information on when and how strings are converted to floats, see the section titled String conversion to numbers. For values of other types, the conversion is the same as if the value would have been converted to integer and then to float. See the Converting to integer section for more information.
A string is series of characters. In PHP, a character is the same as a byte, that is, there are exactly 256 different characters possible. This also implies that PHP has no native support of Unicode. See utf8_encode() and utf8_decode() for some Unicode support.
Nota: It is no problem for a string to become very large. There is no practical bound to the size of strings imposed by PHP, so there is no reason at all to worry about long strings.
A string literal can be specified in three different ways.
The easiest way to specify a simple string is to enclose it in single quotes (the character ').
To specify a literal single quote, you will need to escape it with a backslash (\), like in many other languages. If a backslash needs to occur before a single quote or at the end of the string, you need to double it. Note that if you try to escape any other character, the backslash will also be printed! So usually there is no need to escape the backslash itself.
Nota: In PHP 3, a warning will be issued at the E_NOTICE level when this happens.
Nota: Unlike the two other syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
<?php echo 'this is a simple string'; echo 'You can also have embedded newlines in strings this way as it is okay to do'; // Outputs: Arnold once said: "I'll be back" echo 'Arnold once said: "I\'ll be back"'; // Outputs: You deleted C:\*.*? echo 'You deleted C:\\*.*?'; // Outputs: You deleted C:\*.*? echo 'You deleted C:\*.*?'; // Outputs: This will not expand: \n a newline echo 'This will not expand: \n a newline'; // Outputs: Variables do not $expand $either echo 'Variables do not $expand $either'; ?> |
If the string is enclosed in double-quotes ("), PHP understands more escape sequences for special characters:
Tabella 6-1. Escaped characters
sequence | meaning |
---|---|
\n | linefeed (LF or 0x0A (10) in ASCII) |
\r | carriage return (CR or 0x0D (13) in ASCII) |
\t | horizontal tab (HT or 0x09 (9) in ASCII) |
\\ | backslash |
\$ | dollar sign |
\" | double-quote |
\[0-7]{1,3} | the sequence of characters matching the regular expression is a character in octal notation |
\x[0-9A-Fa-f]{1,2} | the sequence of characters matching the regular expression is a character in hexadecimal notation |
Again, if you try to escape any other character, the backslash will be printed too!
But the most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.
Another way to delimit strings is by using heredoc syntax ("<<<"). One should provide an identifier after <<<, then the string, and then the same identifier to close the quotation.
The closing identifier must begin in the first column of the line. Also, the identifier used must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.
Avvertimento |
It is very important to note that the line with the closing identifier contains no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs after or before the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by your operating system. This is \r on Macintosh for example. If this rule is broken and the closing identifier is not "clean" then it's not considered to be a closing identifier and PHP will continue looking for one. If in this case a proper closing identifier is not found then a parse error will result with the line number being at the end of the script. |
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
|
Nota: Heredoc support was added in PHP 4.
When a string is specified in double quotes or with heredoc, variables are parsed within it.
There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to parse a variable, an array value, or an object property.
The complex syntax was introduced in PHP 4, and can be recognised by the curly braces surrounding the expression.
If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces if you want to explicitly specify the end of the name.
<?php $beer = 'Heineken'; echo "$beer's taste is great"; // works, "'" is an invalid character for varnames echo "He drank some $beers"; // won't work, 's' is a valid character for varnames echo "He drank some ${beer}s"; // works echo "He drank some {$beer}s"; // works ?> |
Similarly, you can also have an array index or an object property parsed. With array indices, the closing square bracket (]) marks the end of the index. For object properties the same rules apply as to simple variables, though with object properties there doesn't exist a trick like the one with variables.
<?php // These examples are specific to using arrays inside of strings. // When outside of a string, always quote your array string keys // and do not use {braces} when outside of strings either. // Let's show all errors error_reporting(E_ALL); $fruits = array('strawberry' => 'red', 'banana' => 'yellow'); // Works but note that this works differently outside string-quotes echo "A banana is $fruits[banana]."; // Works echo "A banana is {$fruits['banana']}."; // Works but PHP looks for a constant named banana first // as described below. echo "A banana is {$fruits[banana]}."; // Won't work, use braces. This results in a parse error. echo "A banana is $fruits['banana']."; // Works echo "A banana is " . $fruits['banana'] . "."; // Works echo "This square is $square->width meters broad."; // Won't work. For a solution, see the complex syntax. echo "This square is $square->width00 centimeters broad."; ?> |
For anything more complex, you should use the complex syntax.
This isn't called complex because the syntax is complex, but because you can include complex expressions this way.
In fact, you can include any value that is in the namespace in strings with this syntax. You simply write the expression the same way as you would outside the string, and then include it in { and }. Since you can't escape '{', this syntax will only be recognised when the $ is immediately following the {. (Use "{\$" or "\{$" to get a literal "{$"). Some examples to make it clear:
<?php // Let's show all errors error_reporting(E_ALL); $great = 'fantastic'; // Won't work, outputs: This is { fantastic} echo "This is { $great}"; // Works, outputs: This is fantastic echo "This is {$great}"; echo "This is ${great}"; // Works echo "This square is {$square->width}00 centimeters broad."; // Works echo "This works: {$arr[4][3]}"; // This is wrong for the same reason as $foo[bar] is wrong // outside a string. In other words, it will still work but // because PHP first looks for a constant named foo, it will // throw an error of level E_NOTICE (undefined constant). echo "This is wrong: {$arr[foo][3]}"; // Works. When using multi-dimensional arrays, always use // braces around arrays when inside of strings echo "This works: {$arr['foo'][3]}"; // Works. echo "This works: " . $arr['foo'][3]; echo "You can even write {$obj->values[3]->name}"; echo "This is the value of the var named $name: {${$name}}"; ?> |
Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string in curly braces.
Nota: For backwards compatibility, you can still use array-brackets for the same purpose. However, this syntax is deprecated as of PHP 4.
Esempio 6-3. Some string examples
|
Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. Please see String operators for more information.
There are a lot of useful functions for string modification.
See the string functions section for general functions, the regular expression functions for advanced find&replacing (in two tastes: Perl and POSIX extended).
There are also functions for URL-strings, and functions to encrypt/decrypt strings (mcrypt and mhash).
Finally, if you still didn't find what you're looking for, see also the character type functions.
You can convert a value to a string using the (string) cast, or the strval() function. String conversion is automatically done in the scope of an expression for you where a string is needed. This happens when you use the echo() or print() functions, or when you compare a variable value to a string. Reading the manual sections on Types and Type Juggling will make the following clearer. See also settype().
A boolean TRUE value is converted to the string "1", the FALSE value is represented as "" (empty string). This way you can convert back and forth between boolean and string values.
An integer or a floating point number (float) is converted to a string representing the number with its digits (including the exponent part for floating point numbers).
Arrays are always converted to the string "Array", so you cannot dump out the contents of an array with echo() or print() to see what is inside them. To view one element, you'd do something like echo $arr['foo']. See below for tips on dumping/viewing the entire contents.
Objects are always converted to the string "Object". If you would like to print out the member variable values of an object for debugging reasons, read the paragraphs below. If you would like to find out the class name of which an object is an instance of, use get_class().
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.
When a string is evaluated as a numeric value, the resulting value and type are determined as follows.
The string will evaluate as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will evaluate as an integer.
The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.
<?php $foo = 1 + "10.5"; // $foo is float (11.5) $foo = 1 + "-1.3e3"; // $foo is float (-1299) $foo = 1 + "bob-1.3e3"; // $foo is integer (1) $foo = 1 + "bob3"; // $foo is integer (1) $foo = 1 + "10 Small Pigs"; // $foo is integer (11) $foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2) $foo = "10.0 pigs " + 1; // $foo is float (11) $foo = "10.0 pigs " + 1.0; // $foo is float (11) ?> |
For more information on this conversion, see the Unix manual page for strtod(3).
If you would like to test any of the examples in this section, you can cut and paste the examples and insert the following line to see for yourself what's going on:
Do not expect to get the code of one character by converting it to integer (as you would do in C for example). Use the functions ord() and chr() to convert between charcodes and characters.
An array in PHP is actually an ordered map. A map is a type that maps values to keys. This type is optimized in several ways, so you can use it as a real array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. Because you can have another PHP array as a value, you can also quite easily simulate trees.
Explanation of those data structures is beyond the scope of this manual, but you'll find at least one example for each of them. For more information we refer you to external literature about this broad topic.
An array can be created by the array() language-construct. It takes a certain number of comma-separated key => value pairs.
array( [key =>] value , ... ) // key may be an integer or string // value may be any value |
A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). There are no different indexed and associative array types in PHP; there is only one array type, which can both contain integer and string indices.
A value can be of any PHP type.
<?php $arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42)); echo $arr["somearray"][6]; // 5 echo $arr["somearray"][13]; // 9 echo $arr["somearray"]["a"]; // 42 ?> |
If you do not specify a key for a given value, then the maximum of the integer indices is taken, and the new key will be that maximum value + 1. If you specify a key that already has a value assigned to it, that value will be overwritten.
<?php // This array is the same as ... array(5 => 43, 32, 56, "b" => 12); // ...this array array(5 => 43, 6 => 32, 7 => 56, "b" => 12); ?> |
Avvertimento |
As of PHP 4.3.0, the index generation behaviour described above has changed. Now, if you append to an array in which the current maximum key is negative, then the next key created will be zero (0). Before, the new index would have been set to the largest existing key + 1, the same as positive indices are. |
Using TRUE as a key will evaluate to integer 1 as key. Using FALSE as a key will evaluate to integer 0 as key. Using NULL as a key will evaluate to the empty string. Using the empty string as key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets.
You cannot use arrays or objects as keys. Doing so will result in a warning: Illegal offset type.
You can also modify an existing array by explicitly setting values in it.
This is done by assigning values to the array while specifying the key in brackets. You can also omit the key, add an empty pair of brackets ("[]") to the variable name in that case.
$arr[key] = value; $arr[] = value; // key may be an integer or string // value may be any value |
<?php $arr = array(5 => 1, 12 => 2); $arr[] = 56; // This is the same as $arr[13] = 56; // at this point of the script $arr["x"] = 42; // This adds a new element to // the array with key "x" unset($arr[5]); // This removes the element from the array unset($arr); // This deletes the whole array ?> |
Nota: As mentioned above, if you provide the brackets with no key specified, then the maximum of the existing integer indices is taken, and the new key will be that maximum value + 1 . If no integer indices exist yet, the key will be 0 (zero). If you specify a key that already has a value assigned to it, that value will be overwritten.
Avvertimento As of PHP 4.3.0, the index generation behaviour described above has changed. Now, if you append to an array in which the current maximum key is negative, then the next key created will be zero (0). Before, the new index would have been set to the largest existing key + 1, the same as positive indices are.
Note that the maximum integer key used for this need not currently exist in the array. It simply must have existed in the array at some time since the last time the array was re-indexed. The following example illustrates:
<?php // Create a simple array. $array = array(1, 2, 3, 4, 5); print_r($array); // Now delete every item, but leave the array itself intact: foreach ($array as $i => $value) { unset($array[$i]); } print_r($array); // Append an item (note that the new key is 5, instead of 0 as you // might expect). $array[] = 6; print_r($array); // Re-index: $array = array_values($array); $array[] = 7; print_r($array); ?>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 )
There are quite a few useful functions for working with arrays. See the array functions section.
Nota: The unset() function allows unsetting keys of an array. Be aware that the array will NOT be reindexed. If you only use "usual integer indices" (starting from zero, increasing by one), you can achieve the reindex effect by using array_values().
The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array.
You should always use quotes around a string literal array index. For example, use $foo['bar'] and not $foo[bar]. But why is $foo[bar] wrong? You might have seen the following syntax in old scripts:
This is wrong, but it works. Then, why is it wrong? The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes), and PHP may in future define constants which, unfortunately for your code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.Nota: This does not mean to always quote the key. You do not want to quote keys which are constants or variables, as this will prevent PHP from interpreting them.
<?php error_reporting(E_ALL); ini_set('display_errors', true); ini_set('html_errors', false); // Simple array: $array = array(1, 2); $count = count($array); for ($i = 0; $i < $count; $i++) { echo "\nChecking $i: \n"; echo "Bad: " . $array['$i'] . "\n"; echo "Good: " . $array[$i] . "\n"; echo "Bad: {$array['$i']}\n"; echo "Good: {$array[$i]}\n"; } ?>Nota: 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:
This is an example of using a function return value as the array index. PHP also knows about constants, as you may have seen the E_* ones before.<?php $error_descriptions[E_ERROR] = "A fatal error has occured"; $error_descriptions[E_WARNING] = "PHP issued a warning"; $error_descriptions[E_NOTICE] = "This is just an informal notice"; ?> |
<?php $error_descriptions[1] = "A fatal error has occured"; $error_descriptions[2] = "PHP issued a warning"; $error_descriptions[8] = "This is just an informal notice"; ?> |
As we already explained in the above examples, $foo[bar] still works but is wrong. It works, because bar is due to its syntax expected to be a constant expression. However, in this case no constant with the name bar exists. PHP now assumes that you meant bar literally, as the string "bar", but that you forgot to write the quotes.
At some point in the future, the PHP team might want to add another constant or keyword, or you may introduce another constant into your application, and then you get in trouble. For example, you already cannot use the words empty and default this way, since they are special reserved keywords.
Nota: To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings.
For any of the types: integer, float, string, boolean and resource, if you convert a value to an array, you get an array with one element (with index 0), which is the scalar value you started with.
If you convert an object to an array, you get the properties (member variables) of that object as the array's elements. The keys are the member variable names.
If you convert a NULL value to an array, you get an empty array.
The array type in PHP is very versatile, so here will be some examples to show you the full power of arrays.
<?php // this $a = array( 'color' => 'red', 'taste' => 'sweet', 'shape' => 'round', 'name' => 'apple', 4 // key will be 0 ); // is completely equivalent with $a['color'] = 'red'; $a['taste'] = 'sweet'; $a['shape'] = 'round'; $a['name'] = 'apple'; $a[] = 4; // key will be 0 $b[] = 'a'; $b[] = 'b'; $b[] = 'c'; // will result in the array array(0 => 'a' , 1 => 'b' , 2 => 'c'), // or simply array('a', 'b', 'c') ?> |
Esempio 6-4. Using array()
|
Note that it is currently not possible to change the values of the array directly in such a loop. A workaround is the following:
This example creates a one-based array.
Arrays are ordered. You can also change the order using various sorting functions. See the array functions section for more information. You can count the number of items in an array using the count() function.
Because the value of an array can be anything, it can also be another array. This way you can make recursive and multi-dimensional arrays.
Esempio 6-10. Recursive and multi-dimensional arrays
|
You should be aware that array assignment always involves value copying. You need to use the reference operator to copy an array by reference.
To initialize an object, you use the new statement to instantiate the object to a variable.
For a full discussion, please read the section Classes and Objects.
If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built in class is created. If the value was null, the new instance will be empty. For any other value, a member variable named scalar will contain the value.
A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. See the appendix for a listing of all these functions and the corresponding resource types.
Nota: The resource type was introduced in PHP 4
As resource types hold special handlers to opened files, database connections, image canvas areas and the like, you cannot convert any value to a resource.
Due to the reference-counting system introduced with PHP 4's Zend Engine, it is automatically detected when a resource is no longer referred to (just like Java). When this is the case, all resources that were in use for this resource are made free by the garbage collector. For this reason, it is rarely ever necessary to free the memory manually by using some free_result function.
Nota: Persistent database links are special, they are not destroyed by the garbage collector. See also the section about persistent connections.
The special NULL value represents that a variable has no value. NULL is the only possible value of type NULL.
Nota: The null type was introduced in PHP 4
A variable is considered to be NULL if
it has been assigned the constant NULL.
it has not been set to any value yet.
it has been unset().
mixed indicates that a parameter may accept multiple (but not necessarily all) types.
gettype() for example will accept all PHP types, while str_replace() will accept strings and arrays.
Some functions like call_user_func() or usort() accept user defined callback functions as a parameter. Callback functions can not only be simple functions but also object methods including static class methods.
A PHP function is simply passed by its name as a string. You can pass any builtin or user defined function with the exception of array(), echo(), empty(), eval(), exit(), isset(), list(), print() and unset().
A method of an instantiated object is passed as an array containing an object as the element with index 0 and a method name as the element with index 1.
Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object as the element with index 0.
Esempio 6-11. Callback function examples
|
PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var, $var becomes a string. If you then assign an integer value to $var, it becomes an integer.
An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.
<?php $foo = "0"; // $foo is string (ASCII 48) $foo += 2; // $foo is now an integer (2) $foo = $foo + 1.3; // $foo is now a float (3.3) $foo = 5 + "10 Little Piggies"; // $foo is integer (15) $foo = 5 + "10 Small Pigs"; // $foo is integer (15) ?> |
If the last two examples above seem odd, see String conversion to numbers.
If you wish to force a variable to be evaluated as a certain type, see the section on Type casting. If you wish to change the type of a variable, see settype().
If you would like to test any of the examples in this section, you can use the var_dump() function.
Nota: The behaviour of an automatic conversion to array is currently undefined.
Since PHP (for historical reasons) supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem: should $a become an array with its first element being "f", or should "f" become the first character of the string $a?
The current versions of PHP interpret the second assignment as a string offset identification, so $a becomes "f", the result of this automatic conversion however should be considered undefined. PHP 4 introduced the new curly bracket syntax to access characters in string, use this syntax instead of the one presented above:
See the section titled String access by character for more information.
Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.
The casts allowed are:
(int), (integer) - cast to integer
(bool), (boolean) - cast to boolean
(float), (double), (real) - cast to float
(string) - cast to string
(array) - cast to array
(object) - cast to object
Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:
Nota: Instead of casting a variable to string, you can also enclose the variable in double quotes.
It may not be obvious exactly what will happen when casting between certain types. For more info, see these sections:
Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.
Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
Nota: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255 (0x7f-0xff).
<?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 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
Contains a reference to every variable which is currently available within the global scope of the script. The keys of this array are the names of the global variables. $GLOBALS has existed since PHP 3.
Variables set by the web server or otherwise directly related to the execution environment of the current script. Analogous to the old $HTTP_SERVER_VARS array (which is still available, but deprecated).
Variables provided to the script via HTTP GET. Analogous to the old $HTTP_GET_VARS array (which is still available, but deprecated).
Variables provided to the script via HTTP POST. Analogous to the old $HTTP_POST_VARS array (which is still available, but deprecated).
Variables provided to the script via HTTP cookies. Analogous to the old $HTTP_COOKIE_VARS array (which is still available, but deprecated).
Variables provided to the script via HTTP post file uploads. Analogous to the old $HTTP_POST_FILES array (which is still available, but deprecated). See POST method uploads for more information.
Variables provided to the script via the environment. Analogous to the old $HTTP_ENV_VARS array (which is still available, but deprecated).
Variables provided to the script via the GET, POST, and COOKIE input mechanisms, and which therefore cannot be trusted. The presence and order of variable inclusion in this array is defined according to the PHP variables_order configuration directive. This array has no direct analogue in versions of PHP prior to 4.1.0. See also import_request_variables().
Attenzione |
Since PHP 4.3.0, FILE information from $_FILES does not exist in $_REQUEST. |
Nota: When running on the command line , this will not include the argv and argc entries; these are present in the $_SERVER array.
Variables which are currently registered to a script's session. Analogous to the old $HTTP_SESSION_VARS array (which is still available, but deprecated). See the Session handling functions section for more information.
The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:
Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:
<?php $a = 1; /* global scope */ function Test() { echo $a; /* reference to local scope variable */ } Test(); ?> |
This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.
First, an example use of global:
The above script will output "3". By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.
A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:
The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal. Here's an example demonstrating the power of superglobals:
Esempio 7-3. Example demonstrating superglobals and scope
|
Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example:
This function is quite useless since every time it is called it sets $a to 0 and prints "0". The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:
Now, every time the Test() function is called it will print the value of $a and increment it.
Static variables also provide one way to deal with recursive functions. A recursive function is one which calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10, using the static variable $count to know when to stop:
Nota: Static variables 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.
The Zend Engine 1, driving PHP 4, implements the static and global modifier for variables in terms of references. For example, a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. This can lead to unexpected behaviour which the following example addresses:
<?php function test_global_ref() { global $obj; $obj = &new stdclass; } function test_global_noref() { global $obj; $obj = new stdclass; } test_global_ref(); var_dump($obj); test_global_noref(); var_dump($obj); ?> |
Executing this example will result in the following output:
NULL object(stdClass)(0) { } |
A similar behaviour applies to the static statement. References are not stored statically:
<?php function &get_instance_ref() { static $obj; echo "Static object: "; var_dump($obj); if (!isset($obj)) { // Assign a reference to the static variable $obj = &new stdclass; } $obj->property++; return $obj; } function &get_instance_noref() { static $obj; echo "Static object: "; var_dump($obj); if (!isset($obj)) { // Assign the object to the static variable $obj = new stdclass; } $obj->property++; return $obj; } $obj1 = get_instance_ref(); $still_obj1 = get_instance_ref(); echo "\n"; $obj2 = get_instance_noref(); $still_obj2 = get_instance_noref(); ?> |
Executing this example will result in the following output:
Static object: NULL Static object: NULL Static object: NULL Static object: object(stdClass)(1) { ["property"]=> int(1) } |
This example demonstrates that when assigning a reference to a static variable, it's not remembered when you call the &get_instance_ref() function a second time.
Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:
A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.
At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement:
produces the exact same output as:
i.e. they both produce: hello world.
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
Avvertimento |
Please note that variable variables cannot be used with PHP's Superglobal arrays. 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. |
When a form is submitted to a PHP script, the information from that form is automatically made available to the script. There are many ways to access this information, for example:
Depending on your particular setup and personal preferences, there are many ways to access data from your HTML forms. Some examples are:
Esempio 7-9. Accessing data from a simple POST HTML form
|
Using a GET form is similar except you'll use the appropriate GET predefined variable instead. GET also applies to the QUERY_STRING (the information after the '?' in a URL). So, for example, http://www.example.com/test.php?id=3 contains GET data which is accessible with $_GET['id']. See also $_REQUEST and import_request_variables().
Nota: Superglobal arrays, like $_POST and $_GET, became available in PHP 4.1.0
As shown, before PHP 4.2.0 the default value for register_globals was on. And, in PHP 3 it was always on. The PHP community is encouraging all to not rely on this directive as it's preferred to assume it's off and code accordingly.
Nota: The magic_quotes_gpc configuration directive affects Get, Post and Cookie values. If turned on, value (It's "PHP!") will automagically become (It\'s \"PHP!\"). Escaping is needed for DB insertion. See also addslashes(), stripslashes() and magic_quotes_sybase.
PHP also understands arrays in the context of form variables (see the related faq). You may, for example, group related variables together, or use this feature to retrieve values from a multiple select input. For example, let's post a form to itself and upon submission display the data:
Esempio 7-10. More complex form variables
|
In PHP 3, the array form variable usage is limited to single-dimensional arrays. In PHP 4, no such restriction applies.
When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:
When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image. The experienced may note that the actual variable names sent by the browser contains a period rather than an underscore, but PHP converts the period to an underscore automatically.
PHP transparently supports HTTP cookies as defined by Netscape's Spec. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() function. Cookies are part of the HTTP header, so the SetCookie function must be called before any output is sent to the browser. This is the same restriction as for the header() function. Cookie data is then available in the appropriate cookie data arrays, such as $_COOKIE, $HTTP_COOKIE_VARS as well as in $_REQUEST. See the setcookie() manual page for more details and examples.
If you wish to assign multiple values to a single cookie variable, you may assign it as an array. For example:
<?php setcookie("MyCookie[foo]", "Testing 1", time()+3600); setcookie("MyCookie[bar]", "Testing 2", time()+3600); ?> |
That will create two separate cookies although MyCookie will now be a single array in your script. If you want to set just one cookie with multiple values, consider using serialize() or explode() on the value first.
Note that a cookie will replace a previous cookie by the same name in your browser unless the path or domain is different. So, for a shopping cart application you may want to keep a counter and pass this along. i.e.
Esempio 7-11. A setcookie() example
|
Typically, PHP does not alter the names of variables when they are passed into a script. However, it should be noted that the dot (period, full stop) is not a valid character in a PHP variable name. For the reason, look at it:
<?php $varname.ext; /* invalid variable name */ ?> |
For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores.
Because PHP determines the types of variables and converts them (generally) as needed, it is not always obvious what type a given variable is at any one time. PHP includes several functions which find out what type a variable is, such as: gettype(), is_array(), is_float(), is_int(), is_object(), and is_string(). See also the chapter on Types.
Una costante è un identificatore (nome) per un valore. Come si può intuire, tale valore non può cambiare durante l'esecuzione dello script (fanno eccezione le costanti magiche, che, in realtà, non sono costanti). Una costante è "case-sensitive" per default. È convenzione comune che i nomi di costante siano sempre maiuscoli.
In PHP il nome di una costante segue le regole di qualsiasi "etichetta". Un nome di costante valido inizia con una lettera o underscore, seguita da un numero qualsiasi di caratteri alfanumerici o underscore. L'espressione regolare che esprime questa convenzione è: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
Nota: In questo contesto una lettera è a-z, A-Z e i caratteri ASCII dal 127 al 255 (0x7f-0xff).
Come le superglobals, costante è sempre globale. Si può accedere alle costanti da qualsiasi punto dello script senza tenere conto della visibilità. Per maggiori dettagli sulla visibilità, leggere la sezione variable scope.
È possibile definire una variabile utilizzando la funzione define(). Una volta definita, a una costante non è possibile cambiare il valore o eliminarla.
Le costanti possono contenere solo dati di tipo scalare (boolean, integer, float e string).
Per ottenere il valore di una costante è sufficiente specificarne il nome. A differenza delle variabili, non è necessario anteporre il simbolo $ al nome di una variabile. Si può anche utilizzare la funzione constant(), per leggere il valore di una costante, nel caso in cui se ne ottenga dinamicamente il nome. Si utilizzi get_defined_constants() per ottenere una lista delle variabili definite.
Nota: Costanti e variabili (globali) si trovano in un "namespace" differente. Questo implica che generalmente TRUE e $TRUE sono differenti.
Se si utilizza il nome di una costante che non è definita, PHP assume che detto valore sia il nome della costante stessa, come se si fosse inserito il testo nel nome . Quando ciò accade PHP segnala il problema con un E_NOTICE. Vedere anche il capitolo del manuale sul perchè $foo[bar] è errata (a meno che prima non definisca bar come costante con define()). Per sapere se una costante è definita, si può utilizzare la funzione defined().
Di seguito sono riportate le principali differenze rispetto le variabili:
Le costanti non iniziano con il segno del dollaro ($);
Le costanti possono essere definite solo con la funzione define() e non tramite assegnazione;
Le costanti possono essere definite e utilizzate ovunque senza seguire le regole di visibilità;
Una volta impostate, le costanti non posso essere redefinite e ne annullate;
Le costanti possono essere solo valori scalari;
Il PHP mette a disposizione ad ogni script diverse costanti predefinite. 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
Nome | Descrizione |
---|---|
__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.
Expressions are the most important building stones of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value".
The most basic forms of expressions are constants and variables. When you type "$a = 5", you're assigning '5' into $a. '5', obviously, has the value 5, or in other words '5' is an expression with the value of 5 (in this case, '5' is an integer constant).
After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value of 5 as well. If everything works right, this is exactly what will happen.
Slightly more complex examples for expressions are functions. For instance, consider the following function:
Assuming you're familiar with the concept of functions (if you're not, take a look at the chapter about functions), you'd assume that typing $c = foo() is essentially just like writing $c = 5, and you're right. Functions are expressions with the value of their return value. Since foo() returns 5, the value of the expression 'foo()' is 5. Usually functions don't just return a static value but compute something.
Of course, values in PHP don't have to be integers, and very often they aren't. PHP supports four scalar value types: integer values, floating point values (float), string values and boolean values (scalar values are values that you can't 'break' into smaller pieces, unlike arrays, for instance). PHP also supports two composite (non-scalar) types: arrays and objects. Each of these value types can be assigned into variables or returned from functions.
PHP takes expressions much further, in the same way many other languages do. PHP is an expression-oriented language, in the sense that almost everything is an expression. Consider the example we've already dealt with, '$a = 5'. It's easy to see that there are two values involved here, the value of the integer constant '5', and the value of $a which is being updated to 5 as well. But the truth is that there's one additional value involved here, and that's the value of the assignment itself. The assignment itself evaluates to the assigned value, in this case 5. In practice, it means that '$a = 5', regardless of what it does, is an expression with the value 5. Thus, writing something like '$b = ($a = 5)' is like writing '$a = 5; $b = 5;' (a semicolon marks the end of a statement). Since assignments are parsed in a right to left order, you can also write '$b = $a = 5'.
Another good example of expression orientation is pre- and post-increment and decrement. Users of PHP and many other languages may be familiar with the notation of variable++ and variable--. These are increment and decrement operators. In PHP, the statement '$a++' has no value (is not an expression), and thus you can't assign it or use it in any way. PHP enhances the increment/decrement capabilities by making these expressions as well, like in C. In PHP, like in C, there are two types of increment - pre-increment and post-increment. Both pre-increment and post-increment essentially increment the variable, and the effect on the variable is identical. The difference is with the value of the increment expression. Pre-increment, which is written '++$variable', evaluates to the incremented value (PHP increments the variable before reading its value, thus the name 'pre-increment'). Post-increment, which is written '$variable++' evaluates to the original value of $variable, before it was incremented (PHP increments the variable after reading its value, thus the name 'post-increment').
A very common type of expressions are comparison expressions. These expressions evaluate to either FALSE or TRUE. PHP supports > (bigger than), >= (bigger than or equal to), == (equal), != (not equal), < (smaller than) and <= (smaller than or equal to). The language also supports a set of strict equivalence operators: === (equal to and same type) and !== (not equal to or not same type). These expressions are most commonly used inside conditional execution, such as if statements.
The last example of expressions we'll deal with here is combined operator-assignment expressions. You already know that if you want to increment $a by 1, you can simply write '$a++' or '++$a'. But what if you want to add more than one to it, for instance 3? You could write '$a++' multiple times, but this is obviously not a very efficient or comfortable way. A much more common practice is to write '$a = $a + 3'. '$a + 3' evaluates to the value of $a plus 3, and is assigned back into $a, which results in incrementing $a by 3. In PHP, as in several other languages like C, you can write this in a shorter way, which with time would become clearer and quicker to understand as well. Adding 3 to the current value of $a can be written '$a += 3'. This means exactly "take the value of $a, add 3 to it, and assign it back into $a". In addition to being shorter and clearer, this also results in faster execution. The value of '$a += 3', like the value of a regular assignment, is the assigned value. Notice that it is NOT 3, but the combined value of $a plus 3 (this is the value that's assigned into $a). Any two-place operator can be used in this operator-assignment mode, for example '$a -= 5' (subtract 5 from the value of $a), '$b *= 7' (multiply the value of $b by 7), etc.
There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:
If the value of the first subexpression is TRUE (non-zero), then the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.
The following example should help you understand pre- and post-increment and expressions in general a bit better:
<?php function double($i) { return $i*2; } $b = $a = 5; /* assign the value five into the variable $a and $b */ $c = $a++; /* post-increment, assign original value of $a (5) to $c */ $e = $d = ++$b; /* pre-increment, assign the incremented value of $b (6) to $d and $e */ /* at this point, both $d and $e are equal to 6 */ $f = double($d++); /* assign twice the value of $d before the increment, 2*6 = 12 to $f */ $g = double(++$e); /* assign twice the value of $e after the increment, 2*7 = 14 to $g */ $h = $g += 10; /* first, $g is incremented by 10 and ends with the value of 24. the value of the assignment (24) is then assigned into $h, and $h ends with the value of 24 as well. */ ?> |
Some expressions can be considered as statements. In this case, a statement has the form of 'expr' ';' that is, an expression followed by a semicolon. In '$b=$a=5;', $a=5 is a valid expression, but it's not a statement by itself. '$b=$a=5;' however is a valid statement.
One last thing worth mentioning is the truth value of expressions. In many events, mainly in conditional execution and loops, you're not interested in the specific value of the expression, but only care about whether it means TRUE or FALSE. The constants TRUE and FALSE (case-insensitive) are the two possible boolean values. When necessary, an expression is automatically converted to boolean. See the section about type-casting for details about how.
PHP provides a full and powerful implementation of expressions, and documenting it entirely goes beyond the scope of this manual. The above examples should give you a good idea about what expressions are and how you can construct useful expressions. Throughout the rest of this manual we'll write expr to indicate any valid PHP expression.
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 | , |
sinistra | or |
sinistra | xor |
sinistra | and |
destra | |
sinistra | = += -= *= /= .= %= &= |= ^= ~= <<= >>= |
sinistra | ? : |
sinistra | || |
sinistra | && |
sinistra | | |
sinistra | ^ |
sinistra | & |
non associativi | == != === !== |
non associativi | < <= > >= |
sinistra | << >> |
sinistra | + - . |
sinistra | * / % |
destra | ! ~ ++ -- (int) (float) (string) (array) (object) @ |
destra | [ |
non associativi | new |
Ricordate l'aritmetica di base dalla scuola? Questi funzionano proprio come quelli.
Tabella 10-2. Operatori aritmetici
Esempio | Nome | Risultato |
---|---|---|
$a + $b | Addizione | La somma di $a e $b. |
$a - $b | Sottrazione | La differenza di $a e $b. |
$a * $b | Moltiplicazione | il prodotto di $a e $b. |
$a / $b | Divisione | Quoziente di $a e $b. |
$a % $b | Modulo | Il resto di $a diviso da $b. |
L'operatore di divisione ("/") restituisce un valore float in ogni caso, anche se i due operandi sono interi (oppure stringhe che vengono convertite in interi).
L'operatore di base dell'assegnazione è "=". La vostra prima inclinazione potrebbe essere di pensare che ciò sia come "uguale a". No. Esso significa realmente che l'operando a sinistra assume il valore dell'espressione a destra (ciò significa, "assegna il valore a").
Il valore di un'espressione di assegnazione è il valore assegnato. Cioè il valore di "$a = 3" è 3. Questo vi permette di fare qualche trucchetto:
In aggiunta all'operatore di base dell'assegnazione, ci sono gli "operatori combinati" per tutta l'aritmetica binaria e gli operatori di stringa che vi consentono di usare un valore in un'espressione e poi impostare il suo valore al risultato di quell'espressione. Per esempio:
$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.
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
Esempio | Nome | Risultato |
---|---|---|
$a & $b | And | Sono impostati ad ON i bit che sono ON sia in $a che in $b. |
$a | $b | Or | Sono impostati ad ON i bit che sono ON in $a oppure in $b. |
$a ^ $b | Xor | Sono impostati ad ON i bit che sono ON in $a oppure in $b na non quelli che sono entrambi ON. |
~ $a | Not | Sono impostati ad ON i bit che sono OFF in $a, e viceversa. |
$a << $b | Shift left | Sposta i bit di $a a sinistra di $b passi (ogni passo significa "moltiplica per due") |
$a >> $b | Shift right | Sposta i bit di $a a destra di $b passi (ogni passo significa "dividi per due") |
Gli operatori di confronto, come suggerisce il loro nome, permettono di confrontare due valori.
Tabella 10-4. Operatori di confronto
Esempio | Nome | Risultato |
---|---|---|
$a == $b | Uguale | TRUE se $a è uguale a $b. |
$a === $b | Identico | TRUE se $a è uguale a $b, ed essi sono dello stesso tipo. (Solo PHP 4) |
$a != $b | Diversi | TRUE se $a è diverso da $b. |
$a <> $b | Diversi | TRUE se $a è diverso da $b. |
$a !== $b | Non identici | TRUE se $a è diverso da $b, o se essi non sono dello stesso tipo. (Solo PHP 4) |
$a < $b | Minore | TRUE se $a è strettamente minore di $b. |
$a > $b | Maggiore | TRUE se $a è strettamente maggiore di $b. |
$a <= $b | Minore o uguale | TRUE se $a è minore o uguale a $b. |
$a >= $b | Maggiore o uguale | TRUE se $a è maggiore o uguale a $b. |
Un altro operatore condizionale è l'operatore "?:" (o ternario), che opera come in C e molti altri linguaggi.
Questa espressione vale espressione2 se espressione1 è TRUE, e espressione3 se espressione1 è FALSE.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é. |
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).
Nota: L'operatore backtick è disabilitato quando è abilitata safe mode oppure quando è disabilitata shell_exec().
Vedere anche escapeshellcmd(), exec(), passthru(), popen(), shell_exec() e system().
PHP supporta lo stile C degli operatori di pre- e post-incremento e decremento.
Tabella 10-5. Operatori di incremento/decremento
Esempio | Nome | Effetto |
---|---|---|
++$a | Pre-incremento | Incrementa $a di una unità, inoltre restituisce $a. |
$a++ | Post-incremento | Restituisce $a, inoltre incrementa $a di una unità. |
--$a | Pre-decremento | Decrementa $a di una unità, inoltre restituisce $a. |
$a-- | Post-decremento | Restituisce $a, inoltre decrementa $a di una unità. |
Qui c'è un semplice script di esempio:
<?php echo "<h3>Post-incremento</h3>"; $a = 5; echo "Dovrebbe essere 5: " . $a++ . "<br>\n"; echo "Dovrebbe essere 6: " . $a . "<br>\n"; echo "<h3>Pre-incremento</h3>"; $a = 5; echo "Dovrebbe essere 6: " . ++$a . "<br>\n"; echo "Dovrebbe essere 6: " . $a . "<br>\n"; echo "<h3>Post-decremento</h3>"; $a = 5; echo "Dovrebbe essere 5: " . $a-- . "<br>\n"; echo "Dovrebbe essere 4: " . $a . "<br>\n"; echo "<h3>Pre-decremento</h3>"; $a = 5; echo "Dovrebbe essere 4: " . --$a . "<br>\n"; echo "Dovrebbe essere 4: " . $a . "<br>\n"; ?> |
Tabella 10-6. Operatori logici
Esempio | Nome | Risultato |
---|---|---|
$a and $b | And | TRUE se entrambi $a e $b sono TRUE. |
$a or $b | Or | TRUE se uno tra $a o $b è TRUE. |
$a xor $b | Xor | TRUE se uno tra $a o $b è TRUE, ma non entrambi. |
! $a | Not | TRUE se $a non è TRUE. |
$a && $b | And | TRUE se entrambi $a e $b sono TRUE. |
$a || $b | Or | TRUE se uno tra $a o $b è TRUE. |
La ragione per le due differenti variazioni degli operatori "and" e "or" è che essi operano con differenti precedenze. (Vedere Precedenza degli operatori.)
Ci sono due operatori di stringa. Il primo è l'operatore di concatenazione ('.'), che restituisce la concatenazione dei suoi argomenti 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.
Qualsiasi script PHP è costituito da una serie di istruzioni. Una istruzione può essere un'assegnazione, una chiamata di funzione, un loop, una istruzione condizionale che non fa nulla (istruzione vuota). Le istruzioni terminano con un punto e virgola. Inoltre, le istruzioni si possono raggruppare in blocchi di istruzioni racchiudendole tra parentesi graffa. Un gruppo di istruzioni è, a sua volta, un'istruzione. Il presente capitolo descrive i differenti tipi di istruzioni.
Il costrutto if è una delle più importanti caratteristiche di qualsiasi linguaggio, incluso PHP. Permette l'esecuzione condizionata di frammenti di codice. La struttura di controllo if di PHP è simile a quella del linguaggio C:
Come descritto nella sezione sulle espressioni, espressione restiruirà il suo valore booleano. Se espressione vale TRUE, PHP eseguirà istruzione, e se essa vale FALSE - la ignorerà. Più informazioni riguardo i valori valutati FALSE possono essere trovati nella sezione 'Conversione in booleano' .
L'esempio che segue visualizzerà a è maggiore di b se $a sarà maggiore di $b:
Spesso sarà necessario eseguire più di una istruzione condizionale. Naturalmente non è necessario, utilizzare una singola clausola if per ciascuna istruzione. Si possono raggruppare diverse istruzioni in un singolo gruppo di istruzioni. Per esempio, il codice che segue visualizzerà a è maggiore di b se $a è maggiore di $b, e successivamente assegnerà il valore della variabile $a alla variabile $b:
Si possono annidare indefinitamente istruzioni if, la qual cosa fornisce piena flessibilità per l'esecuzione di istruzioni condizionali in diversi punti del programma.
Spesso è necessario eseguire un'istruzione se una proposizione è vera e un'altra istruzione se la proposizione è falsa. Per questo si usa la clausola else. else estende il costrutto if aggiungendo la possibilità di eseguire un'istruzione se l'espressione nel ramo if è FALSE. L'esempio che segue visualizzerà a è maggiore di b se $a è maggiore di $b e a NON è maggiore di b altrimenti:
Il ramo else viene eseguito solo se l'espressione nel ramo if è FALSE, e, nel caso ci fossero delle clausole elseif, solamente se le espressioni in esse contenute fossero anch'esse FALSE (vedere elseif).elseif, come è facile intuire, è una combinazione di if ed else. Analogamente ad else, estende if aggiungendo la possibilità di eseguire un'altra istruzione nel caso in cui l'espressione contenuta nel ramo if sia FALSE. Però, a differenza di else, si eseguirà l'istruzione alternativa solamente se l'espressione contenuta nel ramo elseif sarà TRUE. L'esempio che segue, visualizzerà a è maggiore di b, a è uguale a b oppure a è minore di b:
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.
PHP offre una sintassi alternativa per alcune delle sue strutture di controllo; vale a dire, if, while, for, foreach e switch. Fondamentalmente la sintassi alternativa consiste nel sostituire la prima parentesi graffa con il carattere "duepunti" (:) e la seconda parentesi graffa con endif;, endwhile;, endfor;, endforeach;, oppure endswitch;, rispettivamente.
Nell'esempio precedente, il blocco HTML "a è uguale a 5" è incluso nel ramo if scritto utilizzando la sintassi alternativa. Il blocco HTML verrà visualizzato solamente se $a è uguale a 5.
La sintassi alternativa si applica anche ad else ed elseif. Nell'esempio che segue si mostra come utilizzare la sintassi alternativa nel caso di un if con elseif ed else:
Il ciclo while è la forma di ciclo più semplice tra quelle possibili in PHP. Si comporta come la sua controparte nel linguaggio C. La forma di base di un ciclo while è la seguente:
Il significato di un ciclo while è semplice. Istruisce l'interprete PHP perchè esegua l'istruzione (o le istruzioni) in esso racchiuse, ripetutamente, fintanto che l'espressione contenuta nella clausola while ha valore TRUE. Il valore dell'espressione viene verificato ogni volta che il ciclo si ripete (iterazione), così che anche se il valore dell'espressione cambia durante l'esecuzione dell'istruzione, il ciclo non termina fino all'iterazione successiva. Ovviamente, se l'espressione nella clausola while ha valore FALSE dall'inizio, l'istruzione racchiusa nel blocco non verrà eseguita nemmeno una volta.
Come nel caso della struttura di controllo if, si possono raggruppare più istruzioni nello medesimo ciclo while racchiudendo le istruzioni in parentesi graffa, oppure utilizzando la sintassi alternativa:
Gli esempi seguenti sono identici e entrambi visualizzano i numeri da 1 a 10:
Il ciclo do..while è simile al ciclo while, con l'unica differenza che il valore dell'espressione viene controllato alla fine di ogni iterazione anzichè all'inizio. La differenza più importante rispetto a while è che la prima iterazione di un blocco do..while verrà sempre eseguita (il valore dell'espressione viene controllato alla fine del ciclo), mentre non sarà necessariamente eseguito in un ciclo while (il valore dell'espressione viene controllato all'inizio del ciclo, e se tale valore è FALSE dall'inizio, l'esecuzione del ciclo termina immediatamente).
È ammessa una sola sintassi per il ciclo do..while:
Il ciclo precedente verrà eseguito un'unica volta, dal momento che alla prima iterazione, quando si controlla l'espressione, il suo valore sarà FALSE ($i non è maggiore di 0) e il ciclo di esecuzioni, termina.
Chi ha utilizzato il linguaggio C conosce probabilmente un'altro modo di utilizzare il ciclo do..while, che permette di terminare l'esecuzione delle istruzioni durante l'esecuzione stessa, utilizzando do..while(0), e usando l'istruzione break. Il codice che segue esemplifica questa possibilità:
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à'.
Il ciclo for è il ciclo più complesso tra quelli disponibili in PHP. Si comporta come la sua controparte nel linguaggio C. La sintassi di un clico for è:
Il valore della prima espressione (espressione1) viene verificato (eseguito) una sola volta incondizionatamente all'inizio del ciclo.
Ad ogni iterazione, si controlla il valore di espressione2. Se è TRUE, il ciclo prosegue e viene eseguita l'istruzione (o le istruzioni) contenuta nel blocco; se è FALSE, l'esecuzione del ciclo termina.
Al termine di ogni iterazione, si verifica (si esegue) il valore di espressione3.
Le due espressioni possono anche non essere presenti. Se non esiste espressione2 significa che il ciclo deve essere eseguito indefinitamente (PHP considera implicitamente che il suo valore è TRUE, come in C). Questa possibilità in fondo non è utile come può sembrare perchè obbliga a terminare il ciclo utilizzando l'istruzione break invece di utilizzare le espressioni booleane del ciclo for .
Si considerino gli esempi seguenti. In ciascun caso si visualizzeranno i numeri da 1 a 10:
/* 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.
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.
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"; } |
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 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 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 " Centrale<br>\n"; while (1) { echo " Interno<br>\n"; continue 3; } echo "Questo non sarà mai stampato.<br>\n"; } echo "Nemmeno questo.<br>\n"; } |
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.
Il costrutto declare si usa per definire direttive di esecuzione per blocchi di istruzioni. La sintassi è simile alla sintassi di altre strutture di controllo:
La sezione direttiva permette di impostare il comportamento del blocco declare . Attualmente è riconosciuta una sola direttiva: la direttiva ticks. (Fare riferimento più in basso per ulteriori informazioni relative alla direttiva ticks)
Verrà eseguita la parte istruzione del blocco declare - come verrà eseguita e quali effetti collaterali emergeranno durante l'esecuzione potrà dipendere dalla direttiva impostata nel blocco direttiva.
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
|
I tick sono ben adeguati per il debugging, l'implementazione di semplici multitasking, backgrounded I/O e molti altri compiti.
Vedere anche register_tick_function() e unregister_tick_function().
Se viene chiamato all'interno di una funzione, l'istruzione return() termina immediatamente l'esecuzione della funzione corrente, e restituisce il suo argomento come valore della funzione chiamata. return() terminerà anche l'esecuzione di un'istruzione eval() o di un file di script.
Se viene chiamato in uno scope globale, allora verrà terrminata l'esecuzione del file di script corrente. Nel caso in cui il file di script corrente sia un file chiamato da include() o require(), il controllo viene passato al file chiamante. Ciononostante, se il file di script corrente è un file chiamato da include(), allora il valore dato da return() verrà restituito come valore della chiamata include(). Se viene chiamato return() all'interno del file di script principale, allora l'esecuzione dello script terminerà. Se il file di script corrente è stato nominato da auto_prepend_file o auto_append_file con le opzioni di configurazione 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.
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()
|
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.
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()
|
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
|
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
|
Poichè include() e require() sono speciali costrutti di linguaggio, dovete includerli all'interno di blocchi di istruzioni se si trovano in un blocco condizionale.
Trattamento dei valori restituiti: È possibile eseguire un'istruzione return() in un file incluso per terminare l'esecuzione di quel file e restituirlo allo script che l'ha chiamato. È anche possibile restituire valori dai file inclusi. Potete prendere il valore di una chiamata di inclusione come fareste con una normale funzione.
Nota: In PHP 3, return potrebbe non apparire in un blocco a meno che esso sia un blocco di funzione, nel qual caso return() si applica a quella funzione e non all'intero file.
$bar ha valore 1 perchè l'inclusione è stata eseguita con successo. Notare la differenza tra gli esempi sopra. Il primo usa return() all'interno di un file incluso mentre l'altro no. 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.
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().
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().
Una funzione può essere definita usando la seguente sintassi:
All'interno di una funzione può apparire qualunque codice PHP valido, persino altre funzioni e definizioni di classe.
In PHP 3, le funzioni devono essere definite prima di essere referenziate. Non esiste nessun requisito in PHP 4.
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.
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.
Di default, gli argomenti della funzione sono passati per valore (così se cambiate il valore dell'argomento all'interno della funzione , esso non cambierà fuori della funzione). Se volete permettere ad una funzione di modificare i suoi argomenti, dovete passarli per riferimento.
Se volete che una argomento sia passato sempre per riferimento ad una funzione, dovete anteporre un ampersand (&) al nome dell'argomento nella definizione della funzione:
Una funzione può definire valori predefiniti in stile C++ per argomenti scalari come segue:
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. |
PHP 4 ha il supporto per le liste di argomenti a lunghezza variabile nelle funzioni definite dall'utente. Ciò è realmente abbastanza semplice, usando le funzioni func_num_args(), func_get_arg(), e func_get_args().
Non è richiesta una speciale sintassi, e le liste di argomenti possono ancora essere provviste esplicitamente con le definizioni di funzioni e si comporteranno normalmente.
I valori vengono restituiti usando l'istruzione opzionale return. Può essere restituito qualsiasi tipo, incluse liste ed oggetti. Ciò provoca l'interruzione dell'esecuzione della funzione immediatamente e la restituzione del controllo alla linea da cui è stata chiamata. Vedere return() per maggiori informazioni.
Non possono essere restituiti valori multipli da una funzione, ma risultati simili possono essere ottenuti restituendo una lista.
Per restituire un riferimento da una funzione, è necessario usare l'operatore di passaggio per riferimento & in entrambe le dichiarazioni di funzioni e quando viene assegnato il valore restituito ad una variabile:
function &restituisce_riferimento() { return $un_riferimento; } $nuovo_riferimento =& restituisce_riferimento(); |
Per maggiori informazioni sui riferimenti, consultare References Explained.
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. |
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.
Vedere anche variabili variabili e function_exists().
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:
|
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
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.
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.
E possibile ritrovarsi a scrivere classi con codice che si riferisce a variabili e funzioni di classi base. Ciò è particolarmente VERO se una classe derivata è un perfezionamento o una specializzazione di una classe base.
Invece di usare il nome letterale della classe, bisognerebbe usare il nome speciale parent, che si riferisce al nome della classe base definita nella dichiarazione di extends. Usando questo metodo, si evita di usare il nome della classe base nel codice scritto. Se l'albero di eredità cambiasse durante lo sviluppo della classe, il cambiamento si ridurrebbe semplicemente alla modifica della dichiarazione extends della classe.
<?php class A { function example() { echo "Sono A::example() e fornisco una funzionalità di base.<br>\n"; } } class B extends A { function example() { echo "Sono B::example() e fornisco una funzionalità aggiuntiva.<br>\n"; parent::example(); } } $b = new B; // Il codice chiama B::example(), che a sua volta chiama A::example(). $b->example(); ?> |
Nota: In PHP 3, gli oggetti perdono la loro associazione di classe durante il processo di serializzazione e di deserializzazione. La variabile risultante è di tipo oggetto, ma non ha classe e metodi, e diventa inutile (come un buffo array).
Attenzione |
Le seguenti informazioni sono valide soltanto per PHP 4. |
serialize() restituisce una stringa che contiene una rappresentazione byte-stream di tutti i valori che possono essere memorizzati in PHP. unserialize() può usare questa stringa per ricreare i valori variabili utilizzabili. Usando serialize() per salvare un oggetto si salveranno tutte le variabili dell'oggetto. Le funzioni dell'oggetto non sono salvate, viene salvato solo il nome della classe.
Per potere usare unserialize() su un oggetto, la classe dell'oggetto deve essere definita. Cioè se avete un oggetto $a della classe A su una pagina di nome page1.php e usate serialize(), otterrete una stringa che si riferisce alla classe A e contiene tutti i valori delle variabili contenute in $a. Se desiderate potere deserializzare l'oggetto in un'altra pagina chiamata page2.php, dovete ricreare $a dalla classe A, la definizione della classe A perciò deve essere presente nella pagina page2.php. Questo può essere fatto per esempio memorizzando la definizione della classe A in un file che viene incluso sia in page1.php che in page2.php.
<?php // classa.inc: class A { var $one = 1; function show_one() { echo $this->one; } } // page1.php: include("classa.inc"); $a = new A; $s = serialize($a); // memorizzare $s in qualche posto della page2. $fp = fopen("store", "w"); 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.
serialize() controlla se la vostra classe ha una funzione dal nome magico __sleep. In caso affermativo, quella funzione viene eseguita prima di qualsiasi serializzazione. La funzione può pulire l'oggetto e restituire un array con i nomi di tutte le variabili di quell' oggetto che dovrebbero essere serializzate.
Si intende usare __sleep quando chiudendo un collegamento ad un database l'oggetto può avere dati pendenti e l'oggetto ha bisogno di essere ripulito. Inoltre, la funzione è utile se avete oggetti molto grandi che non devono essere salvati completamente.
Per contro, unserialize() controlla per vedere se c'è nella classe una funzione dal nome magico __wakeup. Se è presente questa funzione può ricostruire qualunque risorsa che l'oggetto aveva.
L'intento di __wakeup è quello di ristabilire le connessioni ai database che possono esser state persi durante la serializzazione ed effettuare altre mansioni reinizializzazione.
La creazione di riferimenti con costruttori può condurre a risultati confusi. Questa sezione in stile Tutorial vi aiuterà ad evitare problemi.
<?php class Foo { function Foo($name) { // crea un riferimento all'interno della variabile $globalref global $globalref; $globalref[] = &$this; // setta Name con il valore passato $this->setName($name); // e lo manda all'output $this->echoName(); } function echoName() { echo "<br>",$this->name; } function setName($name) { $this->name = $name; } } ?> |
Verifichiamo se c'è una differenza fra $bar1 che è stato creato usando l'operatore = e $bar2 che è stato creato usando l'operatore di riferimento =& ...
<?php $bar1 = new Foo('set in constructor'); $bar1->echoName(); $globalref[0]->echoName(); /* output: imposta nel costruttore imposta nel costruttore imposta nel costruttore */ $bar2 =& new Foo('set in constructor'); $bar2->echoName(); $globalref[1]->echoName(); /* output: imposta nel costruttore imposta nel costruttore imposta nel costruttore */ ?> |
Apparentemente non c'è differenza, ed in effetti questo è molto significativo: $bar1 e $globalref[0] _ NON _ sono riferimenti, ma sono due variabili diverse. Questo succede perché "new" non restituisce per default un riferimento, ma restituisce una copia.
Nota: Non c'è perdita di prestazioni (da php 4 in su si usa il riferimento) ad istanziare copie per riferimento. Al contrario spesso è meglio lavorare con copie istanziate per riferimento, perché creare copie reali richiede un certo tempo, mentre creare riferimenti virtuali è immediato, (a meno che non si parli di un grande array o un oggetto che viene modificato in modo successivo, allora sarebbe saggio usare i riferimenti per cambiargli tutti i valori simultaneamente).
<?php // ora cambieremo il nome che cosa vi aspettate? // potreste prevedere che $bar e $globalref[0] cambino i loro nomi ... $bar1->setName('set from outside'); // come accennato prima ecco il risultato. $bar1->echoName(); $globalref[0]->echoName(); /* output: set from outside set in constructor */ // vediamo le differenze tra $bar2 e $globalref[1] $bar2->setName('set from outside'); // fortunatamen sono solo uguali, ma sono la stessa variabile // $bar2->name e $globalref[1]->name sono la stessa cosa $bar2->echoName(); $globalref[1]->echoName(); /* output: set from outside set from outside */ ?> |
Un esempio finale, prova a farvi capire.
<?php class A { function A($i) { $this->value = $i; // provare a capire perchè qui non abbiamo bisogno d'un riferimento $this->b = new B($this); } function createRef() { $this->c = new B($this); } function echoValue() { echo "<br>","class ",get_class($this),': ',$this->value; } } class B { function B(&$a) { $this->a = &$a; } function echoValue() { echo "<br>","class ",get_class($this),': ',$this->a->value; } } // prova a capire perchè usando una semplice copia si avrebbe // in un risultato indesiderato nella riga segnata con * $a =& new A(10); $a->createRef(); $a->echoValue(); $a->b->echoValue(); $a->c->echoValue(); $a->value = 11; $a->echoValue(); $a->b->echoValue(); // * $a->c->echoValue(); /* output: class A: 10 class B: 10 class B: 10 class A: 11 class B: 11 class B: 11 */ ?> |
In PHP 4, gli oggetti sono confrontati semplicemente, cioè: due istanze di oggetto sono uguali se hanno gli stessi attributi e valori, e sono istanze della stessa classe. Questa regola regola è applicata anche nel confronto di due oggetti utilizzando l'operatore di identità (===).
Eseguendo il codice seguente:
Esempio 13-1. Esempio di confronto di oggetti in PHP 4
|
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 |
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
|
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 |
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
|
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 |
Intro to oop5 for php
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
|
For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.
PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as 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.
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.
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.
Class members must be defined with public, private, or private.
Esempio 14-3. Member declaration
|
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.
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.
Abstract classes cannot be instantiated. Old code that has no user-defined classes or functions named 'abstract' should run without modifications.
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 14-5. Cloning an object
|
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
|
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 |
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:
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 ] { } } } |
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
|
Nota: The method invoke() accepts a variable number of arguments which are passed to the function just as in call_user_func().
The ReflectionParameter class retrieves information about a function's or method's parameters.
<?php class ReflectionParameter implements Reflector { 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
|
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
|
Nota: The method newInstance() accepts a variable number of arguments which are passed to the function just as in call_user_func().
Nota: $class = new ReflectionClass('Foo'); $class->isInstance($arg) is equivalent to $arg instanceof Foo or is_a($arg, 'Foo').
The ReflectionMethod class lets you reverse-engineer class methods.
<?php class ReflectionMethod extends ReflectionFunction { public __construct(mixed class, string name) public 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
|
Nota: Trying to invoke private, protected or abstract methods will result in an exception being thrown from the invoke() method.
Nota: For static methods as seen above, you should pass NULL as the first argument to invoke(). For non-static methods, pass an instance of the class.
The ReflectionProperty class lets you reverse-engineer class properties.
<?php class ReflectionProperty implements Reflector { 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
|
Nota: Trying to get or set private or protected class property's values will result in an exception being thrown.
The ReflectionExtension class lets you reverse-engineer extensions. You can retrieve all loaded extensions at runtime using the get_loaded_extensions().
<?php class ReflectionExtension implements Reflector { 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
|
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
|
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
I riferimenti in PHP sono il mezzo per accedere ad uno stesso contenuto di variabile utilizzando diversi nomi. Non si sta parlando di puntatori come in C, ma di alias nella tabella dei simboli. Si noti che in PHP, il nome delle variabili e il loro contenuto sono cose diverse, uno stesso contenuto infatti può avere nomi diversi. L'analogia più prossima è quella con i nomi dei file e i file stessi in Unix - i nomi delle variabili sono come directory, mentre il contenuto delle variabili è il file stesso. I riferimenti possono essere pensati come hardlink del filesystem Unix.
I riferimenti permettono di creare due o più variabili che si riferiscono allo stesso contenuto. Questo significa, che scrivendo:
$a e $b puntano 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):
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:
$a assume il valore 6. Questo accade perchè nella funzione foo, la variabile $var si riferisce allo stesso contenuto di $a. Si vedano le spiegazioni più dettagliate per passaggio per riferimento.Il terzo utilizzo del riferimento è il ritorno per riferimento.
Come detto prima, i riferimenti non sono puntatori. Questo significa, che il seguente costrutto non fà quello che ci si aspetterebbe:
Nell'esempio $var in foo viene scambiato con $bar nella chiamata, e poi riscambiato con $GLOBALS["baz"]. Questo non è il modo per collegare $bar nell'ambito della chiamata con qualcos'altro usando il meccanismo di riferimento, poichè $bar non è disponibile nella funzione foo (è rappresentato da $var, ma $var possiede soltanto il contenuto della variabile e non il nome del valore collegato nella tabella dei simboli).
Si può passare una variabile ad una funzione per riferimento, modificandone gli argomenti. La sintassi è la seguente:
Nota che non si usa il segno di riferimento nella chiamata della funzione, ma solo nella definizione. La definizione della funzione basta da sola per passare correttamente un argomento per riferimento.Le seguenti cose possono essere passate per riferimento:
Variabili, es. foo($a)
Operatore New, es. foo(new foobar())
Riferimento restituito da una funazione, es.
Vedi anche le spiegazioni sulla restituzione per riferimento.Qualunque altra cosa non dovrebbe essere passata per riferimento, poichè il risultato sarebbe indefinito. Per esempio, il seguente passaggio per riferimento non è valido:
Questi requisiti sono validi per PHP 4.0.4 e seguenti.La restituzione per riferimento è utile quando si vuole usare una funzione per trovare quale variabile un riferimento dovrebbe limitare. Per restituire per riferimento, si usa questa sintassi:
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.
Quando si cancella un riferimento, si rompe il collegamento tra il nome della variabile e il contenuto della variabile. Questo non significa che il contenuto della variabile venga distrutto. Per esempio:
non cancella $b, ma solo $a.Di nuovo, può essere utile pensare a questo con un'analogia col comendo Unix unlink.
Diversi costrutti in PHP sono implementati attraverso il meccanismo dei riferimenti, dove ogni cosa detta precedentemente, si applica anche a questi costrutti. Alcuni, come il passaggio e la restituzione per riferimento, sono stati menzionati sopra, gli altri sono:
Quando si dichiara una variabile come global $var di fatto si crea un riferimento ad una variabile globale. Questo ha lo stesso significato, dell'espressione:
Questo significa, per esempio, che cancellando $var non si cancella la variabile globale.
PHP is a powerful language and the interpreter, whether included in a web server as a module or executed as a separate CGI binary, is able to access files, execute commands and open network connections on the server. These properties make anything run on a web server insecure by default. PHP is designed specifically to be a more secure language for writing CGI programs than Perl or C, and with correct selection of compile-time and runtime configuration options, and proper coding practices, it can give you exactly the combination of freedom and security you need.
As there are many different ways of utilizing PHP, there are many configuration options controlling its behaviour. A large selection of options guarantees you can use PHP for a lot of purposes, but it also means there are combinations of these options and server configurations that result in an insecure setup.
The configuration flexibility of PHP is equally rivalled by the code flexibility. PHP can be used to build complete server applications, with all the power of a shell user, or it can be used for simple server-side includes with little risk in a tightly controlled environment. How you build that environment, and how secure it is, is largely up to the PHP developer.
This chapter starts with some general security advice, explains the different configuration option combinations and the situations they can be safely used, and describes different considerations in coding for different levels of security.
A completely secure system is a virtual impossibility, so an approach often used in the security profession is one of balancing risk and usability. If every variable submitted by a user required two forms of biometric validation (such as a retinal scan and a fingerprint), you would have an extremely high level of accountability. It would also take half an hour to fill out a fairly complex form, which would tend to encourage users to find ways of bypassing the security.
The best security is often unobtrusive enough to suit the requirements without the user being prevented from accomplishing their work, or over-burdening the code author with excessive complexity. Indeed, some security attacks are merely exploits of this kind of overly built security, which tends to erode over time.
A phrase worth remembering: A system is only as good as the weakest link in a chain. If all transactions are heavily logged based on time, location, transaction type, etc. but the user is only verified based on a single cookie, the validity of tying the users to the transaction log is severely weakened.
When testing, keep in mind that you will not be able to test all possibilities for even the simplest of pages. The input you may expect will be completely unrelated to the input given by a disgruntled employee, a cracker with months of time on their hands, or a housecat walking across the keyboard. This is why it's best to look at the code from a logical perspective, to discern where unexpected data can be introduced, and then follow how it is modified, reduced, or amplified.
The Internet is filled with people trying to make a name for themselves by breaking your code, crashing your site, posting inappropriate content, and otherwise making your day interesting. It doesn't matter if you have a small or large site, you are a target by simply being online, by having a server that can be connected to. Many cracking programs do not discern by size, they simply trawl massive IP blocks looking for victims. Try not to become one.
Using PHP as a CGI binary is an option for setups that for some reason do not wish to integrate PHP as a module into server software (like Apache), or will use PHP with different kinds of CGI wrappers to create safe chroot and setuid environments for scripts. This setup usually involves installing executable PHP binary to the web server cgi-bin directory. CERT advisory CA-96.11 recommends against placing any interpreters into cgi-bin. Even if the PHP binary can be used as a standalone interpreter, PHP is designed to prevent the attacks this setup makes possible:
Accessing system files: http://my.host/cgi-bin/php?/etc/passwd
The query information in a URL after the question mark (?) is passed as command line arguments to the interpreter by the CGI interface. Usually interpreters open and execute the file specified as the first argument on the command line.
When invoked as a CGI binary, PHP refuses to interpret the command line arguments.
Accessing any web document on server: http://my.host/cgi-bin/php/secret/doc.html
The path information part of the URL after the PHP binary name, /secret/doc.html is conventionally used to specify the name of the file to be opened and interpreted by the CGI program. Usually some web server configuration directives (Apache: Action) are used to redirect requests to documents like http://my.host/secret/script.php to the PHP interpreter. With this setup, the web server first checks the access permissions to the directory /secret, and after that creates the redirected request http://my.host/cgi-bin/php/secret/script.php. Unfortunately, if the request is originally given in this form, no access checks are made by web server for file /secret/script.php, but only for the /cgi-bin/php file. This way any user able to access /cgi-bin/php is able to access any protected document on the web server.
In PHP, compile-time configuration option --enable-force-cgi-redirect and runtime configuration directives doc_root and user_dir can be used to prevent this attack, if the server document tree has any directories with access restrictions. See below for full the explanation of the different combinations.
If your server does not have any content that is not restricted by password or ip based access control, there is no need for these configuration options. If your web server does not allow you to do redirects, or the server does not have a way to communicate to the PHP binary that the request is a safely redirected request, you can specify the option --enable-force-cgi-redirect to the configure script. You still have to make sure your PHP scripts do not rely on one or another way of calling the script, neither by directly http://my.host/cgi-bin/php/dir/script.php nor by redirection http://my.host/dir/script.php.
Redirection can be configured in Apache by using AddHandler and Action directives (see below).
This compile-time option prevents anyone from calling PHP directly with a URL like http://my.host/cgi-bin/php/secretdir/script.php. Instead, PHP will only parse in this mode if it has gone through a web server redirect rule.
Usually the redirection in the Apache configuration is done with the following directives:
Action php-script /cgi-bin/php AddHandler php-script .php |
This option has only been tested with the Apache web server, and relies on Apache to set the non-standard CGI environment variable REDIRECT_STATUS on redirected requests. If your web server does not support any way of telling if the request is direct or redirected, you cannot use this option and you must use one of the other ways of running the CGI version documented here.
To include active content, like scripts and executables, in the web server document directories is sometimes considered an insecure practice. If, because of some configuration mistake, the scripts are not executed but displayed as regular HTML documents, this may result in leakage of intellectual property or security information like passwords. Therefore many sysadmins will prefer setting up another directory structure for scripts that are accessible only through the PHP CGI, and therefore always interpreted and not displayed as such.
Also if the method for making sure the requests are not redirected, as described in the previous section, is not available, it is necessary to set up a script doc_root that is different from web document root.
You can set the PHP script document root by the configuration directive doc_root in the configuration file, or you can set the environment variable PHP_DOCUMENT_ROOT. If it is set, the CGI version of PHP will always construct the file name to open with this doc_root and the path information in the request, so you can be sure no script is executed outside this directory (except for user_dir below).
Another option usable here is user_dir. When user_dir is unset, only thing controlling the opened file name is doc_root. Opening a URL like http://my.host/~user/doc.php does not result in opening a file under users home directory, but a file called ~user/doc.php under doc_root (yes, a directory name starting with a tilde [~]).
If user_dir is set to for example public_php, a request like http://my.host/~user/doc.php will open a file called doc.php under the directory named public_php under the home directory of the user. If the home of the user is /home/user, the file executed is /home/user/public_php/doc.php.
user_dir expansion happens regardless of the doc_root setting, so you can control the document root and user directory access separately.
A very secure option is to put the PHP parser binary somewhere outside of the web tree of files. In /usr/local/bin, for example. The only real downside to this option is that you will now have to put a line similar to:
as the first line of any file containing PHP tags. You will also need to make the file executable. That is, treat it exactly as you would treat any other CGI script written in Perl or sh or any other common scripting language which uses the #! shell-escape mechanism for launching itself.To get PHP to handle PATH_INFO and PATH_TRANSLATED information correctly with this setup, the PHP parser should be compiled with the --enable-discard-path configure option.
When PHP is used as an Apache module it inherits Apache's user permissions (typically those of the "nobody" user). This has several impacts on security and authorization. For example, if you are using PHP to access a database, unless that database has built-in access control, you will have to make the database accessible to the "nobody" user. This means a malicious script could access and modify the database, even without a username and password. It's entirely possible that a web spider could stumble across a database administrator's web page, and drop all of your databases. You can protect against this with Apache authorization, or you can design your own access model using LDAP, .htaccess files, etc. and include that code as part of your PHP scripts.
Often, once security is established to the point where the PHP user (in this case, the apache user) has very little risk attached to it, it is discovered that PHP is now prevented from writing any files to user directories. Or perhaps it has been prevented from accessing or changing databases. It has equally been secured from writing good and bad files, or entering good and bad database transactions.
A frequent security mistake made at this point is to allow apache root permissions, or to escalate apache's abilitites in some other way.
Escalating the Apache user's permissions to root is extremely dangerous and may compromise the entire system, so sudo'ing, chroot'ing, or otherwise running as root should not be considered by those who are not security professionals.
There are some simpler solutions. By using open_basedir you can control and restrict what directories are allowed to be used for PHP. You can also set up apache-only areas, to restrict all web based activity to non-user, or non-system, files.
PHP is subject to the security built into most server systems with respect to permissions on a file and directory basis. This allows you to control which files in the filesystem may be read. Care should be taken with any files which are world readable to ensure that they are safe for reading by all users who have access to that filesystem.
Since PHP was designed to allow user level access to the filesystem, it's entirely possible to write a PHP script that will allow you to read system files such as /etc/passwd, modify your ethernet connections, send massive printer jobs out, etc. This has some obvious implications, in that you need to ensure that the files that you read from and write to are the appropriate ones.
Consider the following script, where a user indicates that they'd like to delete a file in their home directory. This assumes a situation where a PHP web interface is regularly used for file management, so the Apache user is allowed to delete files in the user home directories.
Esempio 16-2. ... A filesystem attack
|
Only allow limited permissions to the PHP web user binary.
Check all variables which are submitted.
Esempio 16-3. More secure file name checking
|
Esempio 16-4. More secure file name checking
|
Depending on your operating system, there are a wide variety of files which you should be concerned about, including device entries (/dev/ or COM1), configuration files (/etc/ files and the .ini files), well known file storage areas (/home/, My Documents), etc. For this reason, it's usually easier to create a policy where you forbid everything except for what you explicitly allow.
Nowadays, databases are cardinal components of any web based application by enabling websites to provide varying dynamic content. Since very sensitive or secret information can be stored in a database, you should strongly consider protecting your databases.
To retrieve or to store any information you need to connect to the database, send a legitimate query, fetch the result, and close the connection. Nowadays, the commonly used query language in this interaction is the Structured Query Language (SQL). See how an attacker can tamper with an SQL query.
As you can surmise, PHP cannot protect your database by itself. The following sections aim to be an introduction into the very basics of how to access and manipulate databases within PHP scripts.
Keep in mind this simple rule: defense in depth. The more places you take action to increase the protection of your database, the less probability of an attacker succeeding in exposing or abusing any stored information. Good design of the database schema and the application deals with your greatest fears.
The first step is always to create the database, unless you want to use one from a third party. When a database is created, it is assigned to an owner, who executed the creation statement. Usually, only the owner (or a superuser) can do anything with the objects in that database, and in order to allow other users to use it, privileges must be granted.
Applications should never connect to the database as its owner or a superuser, because these users can execute any query at will, for example, modifying the schema (e.g. dropping tables) or deleting its entire content.
You may create different database users for every aspect of your application with very limited rights to database objects. The most required privileges should be granted only, and avoid that the same user can interact with the database in different use cases. This means that if intruders gain access to your database using your applications credentials, they can only effect as many changes as your application can.
You are encouraged not to implement all the business logic in the web application (i.e. your script), instead do it in the database schema using views, triggers or rules. If the system evolves, new ports will be intended to open to the database, and you have to re-implement the logic in each separate database client. Over and above, triggers can be used to transparently and automatically handle fields, which often provides insight when debugging problems with your application or tracing back transactions.
You may want to 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.
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
|
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)
|
// in case of PostgreSQL 0; insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd) select 'crack', usesysid, 't','t','crack' from pg_shadow where usename='postgres'; -- // in case of MySQL 0; UPDATE user SET Password=PASSWORD('crack') WHERE user='root'; FLUSH PRIVILEGES; |
Nota: It is common technique to force the SQL parser to ignore the rest of the query written by the developer with -- which is the comment sign in SQL.
A feasible way to gain passwords is to circumvent your search result pages. The only thing the attacker needs to do is to see if there are any submitted variables used in SQL statements which are not handled properly. These filters can be set commonly in a preceding form to customize WHERE, ORDER BY, LIMIT and OFFSET clauses in SELECT statements. If your database supports the UNION construct, the attacker may try to append an entire query to the original one to list passwords from an arbitrary table. Using encrypted password fields is strongly encouraged.
SQL UPDATE's are also susceptible to attack. These queries are also threatened by chopping and appending an entirely new query to it. But the attacker might fiddle with the SET clause. In this case some schema information must be possessed to manipulate the query successfully. This can be acquired by examining the form variable names, or just simply brute forcing. There are not so many naming conventions for fields storing passwords or usernames.
<?php // $uid == ' or uid like'%admin%'; -- $query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%'; --"; // $pwd == "hehehe', admin='yes', trusted=100 " $query = "UPDATE usertable SET pwd='hehehe', admin='yes', trusted=100 WHERE ...;"; ?> |
A frightening example how operating system level commands can be accessed on some database hosts.
<?php $query = "SELECT * FROM products WHERE id LIKE '%a%' exec master..xp_cmdshell 'net user test testpass /ADD'--"; $result = mssql_query($query); ?> |
Nota: Some of the examples above is tied to a specific database server. This does not mean that a similar attack is impossible against other products. Your database server may be similarly vulnerable in another manner.
You may plead that the attacker must possess a piece of information about the database schema in most examples. You are right, but you never know when and how it can be taken out, and if it happens, your database may be exposed. If you are using an open source, or publicly available database handling package, which may belong to a content management system or forum, the intruders easily produce a copy of a piece of your code. It may be also a security risk if it is a poorly designed one.
These attacks are mainly based on exploiting the code not being written with security in mind. Never trust any kind of input, especially that which comes from the client side, even though it comes from a select box, a hidden input field or a cookie. The first example shows that such a blameless query can cause disasters.
Never connect to the database as a superuser or as the database owner. Use always customized users with very limited privileges.
Check if the given input has the expected data type. PHP has a wide range of input validating functions, from the simplest ones found in Variable Functions and in Character Type Functions (e.g. is_numeric(), ctype_digit() respectively) and onwards to the Perl compatible Regular Expressions support.
If the application waits for numerical input, consider verifying data with is_numeric(), or silently change its type using settype(), or use its numeric representation by sprintf().
Esempio 16-10. A more secure way to compose a query for paging
|
Quote each non numeric user input which is passed to the database with addslashes() or addcslashes(). See the first example. As the examples shows, quotes burnt into the static part of the query is not enough, and can be easily 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.
With PHP security, there are two sides to error reporting. One is beneficial to increasing security, the other is detrimental.
A standard attack tactic involves profiling a system by feeding it improper data, and checking for the kinds, and contexts, of the errors which are returned. This allows the system cracker to probe for information about the server, to determine possible weaknesses. For example, if an attacker had gleaned information about a page based on a prior form submission, they may attempt to override variables, or modify them:
The PHP errors which are normally returned can be quite helpful to a developer who is trying to debug a script, indicating such things as the function or file that failed, the PHP file it failed in, and the line number which the failure occured in. This is all information that can be exploited. It is not uncommon for a php developer to use show_source(), highlight_string(), or highlight_file() as a debugging measure, but in a live site, this can expose hidden variables, unchecked syntax, and other dangerous information. Especially dangerous is running code from known sources with built-in debugging handlers, or using common debugging techniques. If the attacker can determine what general technique you are using, they may try to brute-force a page, by sending various common debugging strings:
Regardless of the method of error handling, the ability to probe a system for errors leads to providing an attacker with more information.
For example, the very style of a generic PHP error indicates a system is running PHP. If the attacker was looking at an .html page, and wanted to probe for the back-end (to look for known weaknesses in the system), by feeding it the wrong data they may be able to determine that a system was built with PHP.
A function error can indicate whether a system may be running a specific database engine, or give clues as to how a web page or programmed or designed. This allows for deeper investigation into open database ports, or to look for specific bugs or weaknesses in a web page. By feeding different pieces of bad data, for example, an attacker can determine the order of authentication in a script, (from the line number errors) as well as probe for exploits that may be exploited in different locations in the script.
A filesystem or general PHP error can indicate what permissions the webserver has, as well as the structure and organization of files on the web server. Developer written error code can aggravate this problem, leading to easy exploitation of formerly "hidden" information.
There are three major solutions to this issue. The first is to scrutinize all functions, and attempt to compensate for the bulk of the errors. The second is to disable error reporting entirely on the running code. The third is to use PHP's custom error handling functions to create your own error handler. Depending on your security policy, you may find all three to be applicable to your situation.
One way of catching this issue ahead of time is to make use of PHP's own error_reporting(), to help you secure your code and find variable usage that may be dangerous. By testing your code, prior to deployment, with E_ALL, you can quickly find areas where your variables may be open to poisoning or modification in other ways. Once you are ready for deployment, by using E_NONE, you insulate your code from probing.
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
|
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
|
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
|
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
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
|
Will this script only affect the intended files?
Can unusual or undesirable data be acted upon?
Can this script be used in unintended ways?
Can this be used in conjunction with other scripts in a negative manner?
Will any transactions be adequately logged?
You may also want to consider turning off register_globals, magic_quotes, or other convenience settings which may confuse you as to the validity, source, or value of a given variable. Working with PHP in error_reporting(E_ALL) mode can also help warn you about variables being used before they are checked or initialized (so you can prevent unusual data from being operated upon).
In general, security by obscurity is one of the weakest forms of security. But in some cases, every little bit of extra security is desirable.
A few simple techniques can help to hide PHP, possibly slowing down an attacker who is attempting to discover weaknesses in your system. By setting expose_php = off in your php.ini file, you reduce the amount of information available to them.
Another tactic is to configure web servers such as apache to parse different filetypes through PHP, either with an .htaccess directive, or in the apache configuration file itself. You can then use misleading file extensions:
PHP, like any other large system, is under constant scrutiny and improvement. Each new version will often include both major and minor changes to enhance and repair security flaws, configuration mishaps, and other issues that will affect the overall security and stability of your system.
Like other system-level scripting languages and programs, the best approach is to update often, and maintain awareness of the latest versions and their changes.
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
|
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
|
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.
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().
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
|
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
|
Nota: As of this writing, many browsers do not support XForms. Check your browser version if the above examples fails.
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:
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.
Il nome originale del file sulla macchina dell'utente.
Il mime-type del file, se il browser fornisce questa informazione. Un esempio potrebbe essere "image/gif".
La dimensione, in bytes, del file caricato.
Il nome del file temporaneo in cui il file caricato è salvato sul server.
Il codice di errore associato all'upload di questo file. 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.
|
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.
Dalla versione 4.2.0, il PHP restituisce un codice di errore nella matrice del file. Il codice di errore si trova nell'indice ['error'] e viene valorizzato durante l'upload del file da parte del PHP. In altre parole l'errore può essere trovato in $_FILES['userfile']['error'].
Valore: 0; Non vi sono errori, l'upload è stato eseguito con successo.
Valore: 1; Il file inviato eccede le dimensioni specificate nel parametro upload_max_filesize di php.ini.
Valore: 2; Il file inviato eccede le dimensioni specificate nel parametro MAX_FILE_SIZE del form.
Valore: 3; Upload eseguito parzialmente.
Valore: 4; Nessun file è stato inviato.
Nota: Questi valori sono diventate costanti PHP a partire dal PHP 4.3.0.
La voce MAX_FILE_SIZE non può specificare una dimensione del file maggiore di quella impostata dal parametro upload_max_filesize del file php.ini. L'impostazione di default è 2 Megabytes.
Se si è impostato un limite di memoria memory_limit può essere necessario ampliarlo. Occorre essere certi di impostare memory_limit alle dimensioni appropriate.
Se max_execution_time è impostato ad un valore basso, l'esecuzione dello script può eccedere tale valore. Ampliare max_execution_time ad un tempo sufficiente per l'upload.
Nota: max_execution_time influisce solo sul tempo di esecuzione dello script. Il tempo utilizzato per attività esterno allo script, tipo le chiamate di sistema system(), o la funzione sleep(), le query nei database, il tempo inpiegato nell'upload del file non è considerato nel computo del tempo di esecuzione dello script.
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.
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.
Quando la form è inviata, gli array $_FILES['userfile'], $_FILES['userfile']['name'], e $_FILES['userfile']['size'] saranno inizializzati (come sarà valorizzato $HTTP_POST_FILES per le versioni di PHP precedenti la 4.1.0). Quando il parametro register_globals è impostato a on saranno presenti anche le variabili globali. Ognuno di questi è un array indicizzato numericamente con i valori relativi ai diversi file caricati.
Per esempio, si supponga che i nomi di file /home/test/review.html e /home/test/xwp.out siano inviati. In questo caso, $_FILES['userfile']['name'][0] conterrebbe il valore review.html, e $_FILES['userfile']['name'][1] conterrebbe il valore xwp.out. Analogamente, $_FILES['userfile']['size'][0] conterrebbe la dimensione di review.html, e così via.
Anche $_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0], $_FILES['userfile']['size'][0], e $_FILES['userfile']['type'][0] sono impostati.
Il supporto al metodo PUT è cambiato tra PHP 3 e PHP 4. In PHP 4 occorre utilizzare il flusso standard di input per leggere il contenuto di un PUT HTTP.
Esempio 20-4. Salvataggio di un file HTTP PUT con PHP 4
|
Nota: Tutta la documentazione che segue si applica solo a PHP 3.
PHP fornisce supporto per il metodo HTTP PUT utilizzato da programmi come Netscape Composer e W3C Amaya. Le richieste PUT sono molto più semplici rispetto al caricamento di un file, e assomigliano a
Questo significa che normalmente il programma remoto intende salvare il contenuto della richesta come : /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:
Questo chiede ad Apache di inviare tutte le richieste PUT che soddisfano il contesto in cui si è inserito questo comando allo script put.php. Questo richiede, naturalmente, che sia abilitato PHP per l'estensione .php e che PHP sia attivo.
All'interno del file put.php si può inserire qualcosa del tipo:
Questo copia il file nella posizione chiesta dal programma remoto. E' probabile che si vogliano effettuare dei controlli o autenticazioni dell'utente prima di effettuare questa copia. L'unica magia qui presente è che quando PHP vede una richiesta con metodo PUT memorizza il file caricato in un file temporaneo così come per i file caricati con il metodo POST. Quando la richiesta termina, questo file temporaneo è eliminato. Quindi il gestore della richiesta PUT deve copiare il file da qualche parte. Il nome del file temporaneo è memorizzato nella variabile $PHP_PUT_FILENAME, ed è possibile vedere il nome del file di destinazione nella variabile $REQUEST_URI (potrebbe variare su web server diversi da Apache). Qusto nome di file di destinazione è quello specificato dal client remoto. Non è necessario seguire le indicazioni del client. E' possibile, per esempio, copiare tutti i file caricati in una apposita directory.
Se allow_url_fopen è abilitato in php.ini, si possono usare 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
|
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).
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.
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().
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 |
<?php readfile('/etc/passwd'); ?> |
Warning: SAFE MODE Restriction in effect. The script whose uid is 500 is not allowed to access /etc/passwd owned by uid 0 in /docroot/script.php on line 2 |
Se, invece di safe_mode, viene definita una directory open_basedir allora tutte le operazioni sui file saranno limitate ai file sottostanti la directory specificata. Per esempio (nel file httpd.conf di Apache):
<Directory /docroot> php_admin_value open_basedir /docroot </Directory> |
Warning: open_basedir restriction in effect. File is in wrong directory in /docroot/script.php on line 2 |
È possibile inoltre disabilitare le singole funzioni. Se si aggiunge la seguente riga al file php.ini:
disable_functions readfile,system |
Warning: readfile() has been disabled for security reasons in /docroot/script.php on line 2 |
Questo è un elenco probabilmente ancora incompleto e forse non esatto delle funzioni limitate da Safe Mode.
Tabella 24-1. Funzioni limitate dalla modalità sicura
Funzioni | Limitazioni |
---|---|
dbmopen() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
dbase_open() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
filepro() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
filepro_rowcount() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
filepro_retrieve() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
ifx_*() | sql_safe_mode restrictions, (!= Safe Mode) |
ingres_*() | sql_safe_mode restrictions, (!= Safe Mode) |
mysql_*() | sql_safe_mode restrictions, (!= Safe Mode) |
pg_loimport() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
posix_mkfifo() | Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. |
putenv() | Obbedisce le direttive del file ini safe_mode_protected_env_vars e safe_mode_allowed_env_vars. Vedere la documentazione relativa on putenv() |
move_uploaded_file() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
chdir() | Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. |
dl() | Questa funzione è disabilitata nella modalitàsafe-mode |
backtick operator | Questa funzione è disabilitata nella modalitàsafe-mode |
shell_exec() (functional equivalent of backticks) | Questa funzione è disabilitata nella modalitàsafe-mode |
exec() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. |
system() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. |
passthru() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. |
popen() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. |
mkdir() | Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. |
rmdir() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
rename() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. |
unlink() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. |
copy() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. (on source and target) |
chgrp() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
chown() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
chmod() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. In addition, you cannot set the SUID, SGID and sticky bits |
touch() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. |
symlink() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. (note: only the target is checked) |
link() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. (note: only the target is checked) |
getallheaders() | In Safe Mode, headers beginning with 'authorization' (case-insensitive) will not be returned. Warning: this is broken with the aol-server implementation of getallheaders()! |
Qualsiasi funzione che utilizza php4/main/fopen_wrappers.c | ?? |
A partire dalla versione 4.3.0, il PHP supporta un nuovo tipo di SAPI (Server Application Programming Interface) chiamata CLI che significa Interfaccia per la Linea di Comando (Command Line Interface). Come il nome stesso suggerisce, questo tipo di SAPI è mirato allo sviluppo di applicazioni shell (o desktop) con PHP. Esistono alcune differenze tra la CLI SAPI e le altre SAPI; queste saranno illustrate nel corrente capitolo. Val la pena ricordare che CLI e CGI sono differenti SAPI sebbene condividano il medesimo comportamento in diverse situazioni.
La CLI SAPI è stata rilasciata per la prima volta con PHP 4.2.0, ma era ancora sperimentale e quindi doveva essere esplicitamente abilitata con --enable-cli nell'esecuzione di ./configure. A partire dal PHP 4.3.0 la CLI SAPI non viene più considerata sperimentale e quindi l'opzione --enable-cli è attivata per default. Vedere --disable-cli per disabilitare l'opzione.
Dal PHP 4.3.0, il nome, la posizione, e l'esistenza di eseguibili CLI/CGI differirà in base a come il PHP sarà installato sul sistema. Per default quando si esegue il make, si compila sia la versione CLI sia la versione CGI e saranno poste rispettivamente in sapi/cgi/php e sapi/cli/php a partire dalla directory dei sorgenti. Occorre notare che entrambi gli eseguibili sono chiamati php. Ciò che accade durante l'esecuzione di 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
Direttiva | CLI SAPI valore di default | Commento |
---|---|---|
html_errors | FALSE | E' difficile leggere i messaggi di errore nella shell quando sono affogati in tag HTML prive di significato; pertanto il default della direttiva è impostato a FALSE. |
implicit_flush | TRUE | E' desiderabile che ogni tipo di output proveniente da print(), echo() e simili sia scritto immediatamente e non venga bufferizzato. Tuttavia è ancora possibile utilizzare le funzioni di controllo dell'output se si desidera ritardare o manipolare lo standard output. |
max_execution_time | 0 (unlimited) | Considerate le svariate possibilità offerte da PHP nell'ambiente di shell, il tempo massimo di esecuzione è stato impostato a infinito. Mentre nelle applicazione scritte per il web i tempi di esecuzione sono rapidi, le applicazioni di shell tendono ad avere tempi di esecuzione molto più lunghi. |
register_argc_argv | TRUE |
Poichè è impostato a TRUE nella CLI SAPI si ha sempre la possibilità di accedere alla variabili argc (numero di argomenti passati all'applicazione) e argv (matrice degli argumenti). A partire da PHP 4.3.0, quando si utilizza la CLI SAPI le variabili PHP $argc e $argv sono sempre registrate e valorizzate in modo appropriato. Prima di questa versione la creazione di queste variabili era coerente con il comportamento delle versioni CGI e MODULO le quali richiedevano che la direttiva PHP register_globals fosse impostata a on. A prescindere dalla versione o dall'impostazione di register_globals si può sempre accedere alle variabili $_SERVER o $HTTP_SERVER_VARS. Esempio: $_SERVER['argv'] |
Nota: Queste direttive non possono essere inizializate con altri valori dal file di configurazione php.ini o da uno personalizzato (se specifictao). Questa è una limitazione perchè questi valori di default sono applicati dopo avere esaminato tutti i file di configurazione. Tuttavia i loro valori possono essere cambiati durante l'esecuzione (operazione che non ha senso per queste direttive, ad esempio register_argc_argv).
Per potere lavorare meglio con le shell, sono state definite le seguenti costanti:
Tabella 25-2. Costanti specifiche per CLI
Costante | Descrizione | |
---|---|---|
STDIN |
Un flusso già aperto allo stdin. Questo evita di
aprirlo con
| |
STDOUT |
Un flusso già aperto allo stdout. Questo evita di
aprirlo con
| |
STDERR |
Un flusso già aperto allo stderr. Questo evita di
aprirlo con
|
Stante a quanto descritto non occorre più aprire in autonomia flussi per, ad esempio, lo stderr, ma semplicemente si può usare le costanti anzichè una nuova risorsa di flusso:
php -r 'fwrite(STDERR, "stderr\n");' |
La CLI SAPI non cambia la directory corrente in quella dello script eseguito!
Il seguente esempio illustra la diferenza rispetto alla CGI SAPI:
<?php /* Semplice esempio di test chiamato test.php*/ echo getcwd(), "\n"; ?> |
Quando si usa la versione CGI, si avrà il seguente output:
$ pwd /tmp $ php -q another_directory/test.php /tmp/another_directory |
Utilizzando la versione CLI SAPI abbiamo:
$ pwd /tmp $ php -f another_directory/test.php /tmp |
Nota: La CGI SAPI supporta il comportamento della CLI SAPI attivando l'opzione -C quando viene eseguito da linea di comando.
L'elenco completo delle opzioni del PHP disponibili da linea di comando può essere visualizzato in qualsiasi momento eseguendo il PHP con l'opzione -h:
Usage: php [options] [-f] <file> [args...] php [options] -r <code> [args...] php [options] [-- 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:
Dire al PHP di eseguire certi file.
php my_script.php php -f my_script.php |
Passare il codice PHP da eseguire direttamente da linea di comando.
php -r 'print_r(get_defined_constants());' |
Nota: Osservando con attenzione l'esempio si nota l'assenza dei tag di inizio e fine! L'opzione -r non li richiede. L'uso dei tag genera un errore di parsing.
Si può passare il codice PHP da eseguire via standard input (stdin).
Questo da la possibilità di generare dinamicamente del codice PHP e passarlo all'eseguibile, come illustrato nel seguente esempio (fittizio):
$ some_application | some_filter | php | sort -u >final_output.txt |
Come qualsiasi applicazione di shell, anche l'eseguibile PHP accetta diversi argomenti, ma anche lo script PHP può ricevere argomenti. Il numero degli argomenti passabili allo script non è limitato dal PHP (si rammenta che la shell ha un limite nel numero di caratteri che possono essere passati; solitamente non si raggiunte questo limite). Gli argomenti passati allo script sono disponibili nell'array $argv. L'indice zero contiene sempre il nome dello script (che è - nel caso in cui il codice PHP provenda o dallo standard input o dalla linea di comando con l'opzione -r). La seconda variabile globale registrata è $argc la quale contiene il numero degli elementi nella matrice $argv (non è il numero degli argomenti passati allo script).
Fino a quando gli argomenti passati allo script non iniziano con il carattere - non si deve prestare alcuna cautela. Tuttavia se si passa allo script argomenti che iniziano con - si hanno dei problemi perchè lo stesso PHP ritiene di doverli gestire. Per evitare ciò occorre utilizzare il separatore di argomenti --. Dopo che il PHP ha incontrato questo separatore, ogni argomento verrà passato direttamente allo script.
# Questo non visualizzerà il codice passato, ma l'elenco delle opzioni $ php -r 'var_dump($argv);' -h Usage: php [options] [-f] <file> [args...] [...] # Questo passerà il '-h'allo script ed eviterà al PHP di visualizzare le opzioni $ php -r 'var_dump($argv);' -- -h array(2) { [0]=> string(1) "-" [1]=> string(2) "-h" } |
Tuttvia esiste un'altro modo per eseguire gli script PHP. Si può scrivere uno script la cui prima riga inizi con #!/usr/bin/php. Seguendo questa regola si può posizionare il normale codice PHP tra i tag di apertura e chiusura del PHP. Una volta impostati correttamente gli attributi del file (ad esempio chmod +x test) lo script può essere eseguito come una normale shell o script perl:
#!/usr/bin/php <?php var_dump($argv); ?> |
$ chmod 755 test $ ./test -h -- foo array(4) { [0]=> string(6) "./test" [1]=> string(2) "-h" [2]=> string(2) "--" [3]=> string(3) "foo" } |
Tabella 25-3. Opzioni della linea di comando,
Option | Description | |||
---|---|---|---|---|
-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.
| |||
-w |
Visualizza il sorgente senza gli spazi e i commenti.
| |||
-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:
| |||
-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:
| |||
-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 è:
Esempi:
| |||
-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.
| |||
-m |
Utilizzare questa opzione per visualizzare i moduli PHP e di Zend integrati (e quindi caricati):
| |||
-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.
| |||
-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)
|
Nello script precedente, abbiamo utilizzato la prima riga per indicare che questo file deve essere interpretato dal PHP. Poichè qui lavoriamo con la versione CLI non vengono prodotte intestazioni HTTP. Esistono due variabili che si possono utilizzare nelle applicazioni PHP da linea di comando: $argc e $argv. La prima è il numero di argomenti più uno (il nome dello script). La seconda è una matrice contenente gli argomenti, iniziando dal nome dello script all'indice zero ($argv[0]).
Nel programma precedente abbiamo verificato se i parametri passati erano di più o di meno di uno. Inoltre se l'argomento è --help, -help, -h oppure -?, si visualizza un messaggio di aiuto, visualizzando in modo dinamico il nome dello script. Se si riceve un argomento differente questo sarà visualizzato.
Se si desidera eseguire lo script precedente su Unix, occorre, per prima cosa, renderlo eseguibile, e quindi richiamarlo con script.php echothis oppure script.php -h. Su Windows occorre scrivere un batch per ottenere questo risultato:
Assumendo che programma precedente sia chiamato script.php, che la versione CLI di php.exe sia in c:\php\cli\php.exe questo batch eseguirà lo script con le opzioni passate: script.bat echothis oppure script.bat -h.
Vedere anche la documentazione del modulo Readline per informazioni su funzioni che possono essere utilizzate per migliorare le applicazioni da linea di comando.
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.
Per l'installazione di PHP su Apache vedere la sezione Apache nel capitolo che tratta l'installazione.
Il comportamento del modulo Apache per PHP è influenzato dalle impostazioni in php.ini. Le impostazioni di configurazione del php.ini possono essere scavalcate attraverso le impostazioni php_flag nel file di configurazione del server o nei file .htaccess locali.
Tabella 1. Opzioni di configurazione di Apache
Nome | Default | Modificabile | Funzione |
---|---|---|---|
engine | On | PHP_INI_ALL | accende o spegne l'interprete PHP |
child_terminate | Off | PHP_INI_ALL | decide se gli script PHP possono richiedere la terminazione dei processi figli alla fine della richiesta HTTP, vedere anche apache_child_terminate() |
last_modified | Off | PHP_INI_ALL | manda la data di modifica degli script nell'header Last-Modified: |
xbithack | Off | PHP_INI_ALL | interpreta i file con il bit di esecuzione impostato, a prescindere dalla loro estensione |
Breve descrizione dei parametri di configurazione.
Questa direttiva è utile solo nella versione di PHP compilata come modulo di Apache. Viene usata dai siti che vogliono spegnere e accendere il parsing PHP in base alla directory o al virtual server corrente. Inserendo engine off nel posto appropriato nel file httpd.conf, il PHP può essere abilitato o disabilitato.
(PHP 4 >= 4.0.5, PHP 5)
apache_child_terminate -- Interrompe il processo apache dopo la presente richiestaapache_child_terminate() informa il processo Apache che sta eseguendo la richiesta PHP corrente di terminare quando l'esecuzione del codice PHP è stata completata. Può essere usata per interrompere un processo dopo che sia stato eseguito uno script con alta occupazione di memoria dal momento che la memoria viene normalmente liberata internamente ma non restituita al sistema operativo.
Nota: La disponibilità di questa caratteristica è controllata dalal direttiva del php.ini child_terminate, che è impostata a off di default.
Questa caratteristica non è inoltre disponibile sulle versioni multithread di apache come, ad esempio, la versione win32.
Vedere anche exit().
This function returns an array with the loaded Apache modules.
apache_get_version() returns the version of Apache as string, or FALSE on failure.
See also phpinfo().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 3>= 3.0.4, PHP 4 , PHP 5)
apache_lookup_uri -- Esegue una richiesta parziale della URI specificata e restituisce tutte le informazioniQuesta funzione esegue una richiesta parziale per una URI. Esegue l'operazione finché ottiene tutte le informazioni importanti sulla risorsa e restituisce queste informazioni in una classe. Le proprietà della classe restituita sono:
status |
the_request |
status_line |
method |
content_type |
handler |
uri |
filename |
path_info |
args |
boundary |
no_cache |
no_local_copy |
allowed |
send_bodyct |
bytes_sent |
byterange |
clength |
unparsed_uri |
mtime |
request_time |
Esempio 1. esempio di apache_lookup_uri()
Questo esempio produrrà un risultato simile al seguente:
|
Nota: apache_lookup_uri() funziona solo quando PHP è installato come modulo Apache.
(PHP 3>= 3.0.2, PHP 4 , PHP 5)
apache_note -- Ricava o imposta una variabile nella tabella notes di Apacheapache_note() è una funzione specifica di Apache che ricava o imposta un valore nella tabella notes di una richiesta HTTP. Se viene invocata con un solo argomento restituisce il valore della nota nome_nota. Se viene chiamata con due argomenti, imposta il valore della nota nome_nota a valore e restituisce il valore precedente della nota nome_nota.
apache_request_headers() restituisce un array associativo contenente tutti gli header HTTP nella richiesta corrente. Questa funzionalità è supportata solo quando PHP è un modulo di Apache.
Nota: Prima del PHP 4.3.0, apache_request_headers() si chiamava getallheaders(). Dopo il PHP 4.3.0, getallheaders() è un alias di apache_request_headers().
Nota: È possibile ottenere il valore delle variabili comuni CGI anche leggendole dalle variabili di ambiente; questo funziona indipendentemente dal fatto che si stia usando PHP come modulo Apache. Utilizzare phpinfo() per ottenere una lista di tutte le variabili d'ambiente disponibili.
Nota: Dal PHP 4.3.3 è possibile utilizzare questa funzione anche con il modulo server NSAPI dei server web Netscape/iPlanet/SunONE
Vedere anche apache_response_headers().
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().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ascii2ebcdic() è una funzione Apache che è disponibile solo su sistemi operativi basati sull'EBCDIC (OS/390, BS2000). Traduce la stringa codificata in ASCII ascii_str nella sua rappresentazione equivalente EBCDIC (proteggendo i dati binari), e restituisce il risultato.
Vedere anche la funzione duale ebcdic2ascii()
ebcdic2ascii() è una funzione Apache che è disponibile solo su sistemi operativi basati su EBCDIC (OS/390, BS2000). Traduce la stringa codificata in EBCDIC ebcdic_str nella sua rappresentazione equivalente ASCII (proteggendo i dati binari), e restituisce il risultato.
Vedere anche la funzione duale ascii2ebcdic()
getallheaders() è un alias di apache_request_headers(). Restituisce un array associativo contenente tutti gli header HTTP nella richiesta corrente. Leggere la documentazione di apache_request_headers() per ulteriori informazioni sul funzionamento.
Nota: Nel PHP 4.3.0 getallheaders() è diventata un alias di apache_request_headers(). In breve, è stata rinominata. Ciò dipende dal fatto che questa funzione è disponibile soltanto quando PHP è compilato come modulo di Apache.
Nota: Dal PHP 4.3.3 è possibile utilizzare questa funzione anche con il modulo server NSAPI dei server web Netscape/iPlanet/SunONE
Vedere anche apache_request_headers().
virtual() è una funzione specifica Apache che è equivalente a <!--#include virtual...--> in mod_include. Esegue una sotto-richiesta Apache. È utile ad includere script CGI o file .shtml, o qualsiasi altra cosa si voglia fa analizzarea ad Apache. Si noti che per uno script CGI, questo deve generare degli header CGI validi. Quindi, Come minimo deve generare un header Content-type.
Al fine di eseguire la sotto-richiesta, tutti i buffer vengono chiusi e svuotati verso il browser, e anche gli header in attesa vengono inviati.
Dal PHP 4.0.6, è possibile utilizzare virtual() sui file PHP. Comunque è preferibile usare include() o require() se è necessarei includere un altro file PHP.
Nota: Dal PHP 4.3.3 è possibile utilizzare questa funzione anche con il modulo server NSAPI dei server web Netscape/iPlanet/SunONE
Queste funzioni permettono di manipolare e interagire con gli array in vari modi. Gli array sono indispensabili per immagazzinare, mantenere e operare su gruppi di variabili.
Sono supportati sia array semplici che multi-dimensionali, che possono essere sia creati dall'utente che da funzioni. Ci sono specifiche funzioni di database per riempire gli array a partire da interrogazioni sui dati, e parecchie funzioni restituiscono array.
Vedere la sezione Array del manuale per una spiegazione dettagliata di come gli array siano implementati ed usati in PHP. Vedere anche per altri modi di manipolazione degli array.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Le costanti qui elencate sono sempre disponibili in quanto parte del core di PHP.
CASE_LOWER è usata con array_change_key_case() per convertire le chiavi degli array in minuscolo. Questo è il valore di default per array_change_key_case().
CASE_UPPER è usata con array_change_key_case() per convertire le chiavi degli array in maiuscolo.
flag per l'ordinamento:
SORT_ASC è usata con array_multisort() per ordinare in senso crescente.
SORT_DESC è usata con array_multisort() per ordinare in senso decrescente.
flag per il tipo di ordinamento: usati da varie funzioni di ordinamento
(PHP 4 >= 4.2.0, PHP 5)
array_change_key_case -- Restituisce un array con tutte le chiavi cambiate in maiuscolo o in minuscoloarray_change_key_case() cambia le chiavi nell'array input in modo che siano tutte minuscole o maiuscole. Il tipo di cambiamento dipende dal parametro opzionale case. Si possono usare due costanti, CASE_UPPER per le maiuscole e CASE_LOWER per le minuscole. Il default è CASE_LOWER. La funzione non modifica le chiavi numeriche.
Se un array ha degli indici che risulteranno identici dopo l'esecuzione di questa funzione (es. "keY" e "kEY") il valore dell'ultimo indice sovrascrivera' gli altri.
array_chunk() spezza l'array in più array di dimensione dimensione. L'ultimo array potrebbe ovviamente avere una dimensione inferiore. Gli array sono restituiti in un array multidimensionale indicizzato con chiavi che partono da zero.
Impostando il parametro opzionale preserve_keys a TRUE, si forza PHP a mantenere le chiavi originarie dell'array di input. Se si imposta a FALSE come chiavi verranno usati in ogni array dei numeri crescenti a partire da zero. Il default è FALSE.
Esempio 1. esempio di array_chunk()
Il risultato di questo programma sarà:
|
(PHP 5)
array_combine -- Crea un'array utilizzando un'array per le chiavi e un'altro per i suoi valoriRestituisce un'array utilizzando i valori dell'array keys come chiavi e i valori dall' array values come valori corrispondenti.
Restituisce FALSE se il numero degli elementi in ogni array non è uguale o se gli array sono vuoti.
Vedere anche array_merge(), array_walk() e array_values().
array_count_values() restituisce un array che ha i valori dell'array input per chiavi e la loro frequenza in input come valori.
Vedere anche count(), array_unique(), array_values() e count_chars().
(PHP 4 >= 4.3.0, PHP 5)
array_diff_assoc -- Calcola la differenza tra due o più array con un ulteriore controllo sull'indicearray_diff_assoc() restituisce un array contenente tutti i valori di array1 che non sono presenti in alcuno degli altri array. Si noti che le chiavi sono utilizzate nel confronto, diversamente da array_diff().
Esempio 1. esempio di array_diff_assoc()
Il risultato è:
|
Nell'esempio si vede che la coppia "a" => "verde" è presente in entrambi gli array e quindi non è nel risultato della funzione. Invece, la coppia 0 => "rosso" è nel risultato perché nel secondo argomento "red" cha come chiave 1.
Due valori delle coppie chiave => valore sono considerati uguali solo se (string) $elem1 === (string) $elem2 . In altre parole c'è un controllo stringente che si accerta che le rappresentazioni sotto forma di stringa siano uguali.
Nota: Si noti che questa funzione controlla solo una dimensione di un array n-dimensionale. Ovviamente è possibile controllare le altre dimensioni usando array_diff_assoc($array1[0], $array2[0]);.
Vedere anche array_diff(), array_intersect(), and array_intersect_assoc().
(PHP 5)
array_diff_uassoc -- Computes the difference of arrays with additional index check which is performed by a user supplied callback functionarray_diff_uassoc() returns an array containing all the values from array1 that are not present in any of the other arguments. Note that the keys are used in the comparison unlike array_diff(). This comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. This is unlike array_diff_assoc() where an internal function for comparing the indices is used.
Esempio 1. array_diff_uassoc() example
The result is:
|
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() restituisce un array contenente tutti i valori di array1 che non sono presenti in alcuno degli altri array. Si noti che le associazioni con le chiavi vengono mantenute.
Esempio 1. Esempio di array_diff()
Occorrenze multiple in $array1 sono tutte trattate nello stesso modo. Questo codice mostrerà:
|
Nota: Due elementi sono considerati uguali se e solo se (string) $elem1 === (string) $elem2. Ovvero: quando la rappresentazione sotto forma di stringa è la stessa.
Nota: Si noti che questa funzione controlla solo una dimensione di un array n-dimensionale. Ovviamente è possibile controllare le altre dimensioni usando array_diff($array1[0], $array2[0]);.
Avvertimento |
Questa funzione era errata nel PHP 4.0.4! |
Vedere anche array_diff_assoc(), array_intersect() e array_intersect_assoc().
array_fill() riempie un array con num elementi inizializzati con il valore del parametro valore, e con le chiavi che partono dal valore del parametro start_index. Si noti che num deve essere un valore maggiore di zero, altrimenti PHP mostrerà un avvertimento.
Vedere anche str_repeat() e range().
array_filter() esegue un'iterazione su ogni valore nell' array input passandolo alla funzione. Se funzione restituisce TRUE, il valore corrente di input viene restituito nell'array risultato. Le chiavi sono mantenute.
Esempio 1. Esempio di array_filter()
Il risultato di questo sarà:
|
Gli utenti non possono modificare l'array attraverso la funzione di callback, ad esempio aggiungere/togliere un elemento, o cancellare l'array su cui array_filter() è applicata. Se l'array viene cambiato, il comportamento di questa funzione non è definito.
Se la funzione callback non viene indicata, array_filter() rimuoverà tutti gli elementi di input che siano uguali a FALSE. Vedere conversione a boolean per ulteriori informazioni.
Vedere anche array_map() e array_reduce().
array_flip() restituisce un array scambiato, ovvero le chiavi di trans diventano valori e i valori di trans diventano chiavi.
Si noti che i valori di trans devono poter diventare chiavi valide, ovvero devo essere di tipo integer o string. Un errore verrà segnalato se un valore ha il tipo errato, e la coppia chiave/valore in questione non verrà scambiata.
Se un valore ha più di una occorrenza, L'ultima chiave verrà usata come valore, e tutte le altre verranno perse.
array_flip() restituisce FALSE se fallisce.
Vedere anche array_values(), array_keys() e array_reverse().
(PHP 4 >= 4.3.0, PHP 5)
array_intersect_assoc -- Calcola l'intersezione degli array con un ulteriore controllo sugli indiciarray_intersect_assoc() restituisce un array contenente tutti i valori di array1 che siano presenti in tutti gli array passati come argomento. Si noti che le chiavi sono utilizzate nel confronto, diversamente da array_intersect().
Nell'esempio si vede che solo la coppia "a" => "verde" è presente in entrambi gli array e quindi viene restituita. Il valore "rosso" non viene restituito perché in $array1 la sua chiave è 0 mentre la chiave di "rosso" in $array2 è 1.
I due valori delle coppie chiave => valore sono considerati uguali solo se (string) $elem1 === (string) $elem2 . In altre parole viene eseguito un controllo stringente che si accerta che le rappresentazioni sotto forma di stringa siano uguali.
Vedere anche array_intersect() array_diff() e array_diff_assoc().
array_intersect() restituisce un array contenente tutti i valori di array1 che siano presenti in tutti gli array passati come argomento. Si noti che le associazioni con le chiavi sono mantenute.
Nota: Due elementi sono considerati uguali solo e solo se (string) $elem1 === (string) $elem2. Ovvero: quando la rappresentazione sotto forma di stringa è la stessa.
Vedere anche array_intersect_assoc(), array_diff() e array_diff_assoc().
(PHP 4 >= 4.1.0, PHP 5)
array_key_exists -- Controlla se l'indice (o chiave) specificato esiste nell'arrayarray_key_exists() restituisce TRUE se il parametro chiave esiste nell'array. chiave può essere qualsiasi valore accettabile per un indice di array.
Nota: Il nome di questa funzione è key_exists() nel PHP 4.0.6.
Vedere anche isset(), array_keys() e in_array().
array_keys() rstituisce le chiavi, numeriche e stringa, dell'array input.
Se il parametro opzionale valore_ricerca è specificato, solo le chiavi che corrispondono a quel valore vengono restituite. Altrimenti, vengono restituite tutte le chiavi dell'array input.
Esempio 1. Esempio di array_keys()
Il risultato di questo programma sarà:
|
Vedere anche array_values() e array_key_exists().
(PHP 4 >= 4.0.6, PHP 5)
array_map -- Applica la funzione callback a tutti gli elementi dell'array datoarray_map() restituisce un array contenente tutti gli elementi di arr1 dopo che è stata loro applicata la funzione callback. Il numero di parametri che la funzione callback accetta deve corrispondere al numero di array passati alla funzione array_map()
Esempio 2. array_map() - usare più array
Questo restituisce:
|
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
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() fonde gli elementi di due o più array in modo tale che i valori di un array siano accodati all'array precedente. Restituisce l'array risultante.
Se gli array in input hanno le stesse chiavi stringa, i valori di queste chiavi vengono fusi in un array, e questo è fatto in modo ricorsivo, cio` se uno dei valori è un array, la funzione lo fonder%agrave; con una voce corrispondente in un altro array Comunque, se gli array hanno la stessa chiave numerica, l'ultimo valore non sovrascriver` il valore originale, bensì verrà accodato.
Esempio 1. Esempio di array_merge_recursive()
La variabile $risultato sarà:
|
Vedere anche array_merge().
array_merge() fonde gli elementi di 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()
La variabile $risultato sarà:
|
Esempio 2. Esempio di array_merge()
Non dimenticarsi che le chiavi numeriche saranno rinumerate!
Se si vogliono preservare gli array e li si vuole solo concatenare, usare l'operatore +:
La chiave numerica sarà preservata e così pure l'associazione.
|
Nota: Le chiavi condivise verranno sovrascritte dalla prima chiave processata.
Vedere anche array_merge_recursive() e array_combine() e operatori sugli 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.
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.
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() restituisce una copia di input allungato alla dimensione sepcificata da pad_size con il valore pad_value. Se pad_size è positivo l'array è riempito sulla destra, se è negativo sulla sinistra. Se il valore assoluto di pad_size è minore o uguale alla lunghezza di input non viene effettuata alcuna modifica.
Esempio 1. esempio di array_pad()
|
Vedere anche array_fill() e range().
array_pop() estrae e restituisce l'ultimo valore di array, accorciando array di un elemento. Se array è vuoto (o non è un array), viene restituito NULL.
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
Vedere anche array_push(), array_shift() e array_unshift().
array_push() tratta array come una pila, e accoda le variabili date alla fine di array. La lunghezza di array aumenta del numero di variabili accodate. Ha lo stesso effetto di:
<?php $array[] = $var; ?> |
Restituisce il nuovo numero di elementi nell'array.
Nota: Se si utilizza array_push() per aggiungere un elemento all'array, è preferibile piuttosto utilizzare $array[] = poiché in questo modo non c'è il tempo d'attesa per la chiamata di funzione.
Vedere anche array_pop(), array_shift() e array_unshift().
array_rand() è piuttosto utile quando si vuole estrarre a caso uno o più elementi da un array. Prende un array (input) e un argomento ozpionale (num_req) che specifica quanti elementi estrarre - se non è specificato, è 1 per default.
Se si sta estraendo solo un elemento, array_rand() restituisce la chiave di un elemento. Altrimenti, restituisce un array di chiavi. Questo viene fatto in modo da permettere di estrarre dall'array sia le chiavi che i valori.
Nota: Come in PHP 4.2.0, non vi è necessità di inizializzare il generatore di numeri casuali con srand() oppure con mt_srand() poichè viene eseguito in modo automatico.
Vedere anche shuffle().
(PHP 4 >= 4.0.5, PHP 5)
array_reduce -- Riduce iterativamente l'array a un singolo valore utilizzando una funzione callbackarray_reduce() applica iterativamente la funzione callback agli elementi dell'array input, riducendo l'array a un singolo valore. Seil parametro opzionale intial è specificato, viene usato come valore iniziale all'inizio del processo, o come risultato finale nel caso l'array sia vuoto.
In questo modo $b conterrà 15, $c conterrà 1200 (= 1*2*3*4*5*10) e $d conterrà 1.
Vedere anche array_filter() e array_map(), array_unique() e array_count_values().
array_reverse() prende array e restituisce un nuovo array con l'ordine degli elementi invertito, mantenendo le chiavi sie mantieni_chiavi è TRUE.
Esempio 1. esempio di array_reverse()
Questo fa sì che sia $risultato che $risultato_chiavi abbiano gli stessi elementi, ma si noti la differenza tra le chiavi. La stampa di $risultato e $risultato_chiavi sarà:
|
Nota: Il secondo parametro è stato aggiunto in PHP 4.0.3.
Vedere anche array_flip().
(PHP 4 >= 4.0.5, PHP 5)
array_search -- Ricerca un dato valore in un array e ne restituisce la chiave corrispondente, se la ricerca ha successo.Cerca in pagliaio per trovare ago e restituisce la chiave se viene trovato nell'array, FALSE altrimenti.
Nota: Se ago è una stringa, il confronto è fatto tenendo conto delle maiuscole/minuscole.
Nota: Nelle versioni di PHP antecedenti la 4.2.0, array_search() restituisce NULL invece di FALSE in caso di fallimento.
Se il terzo parametro opzionale strict è impostato a TRUE la funzione array_search() controllerà anche il tipo di ago nell'array pagliaio.
Se ago viene ritrovato in pagliaio più di una nolta, viene restituita la prima chiave trovata. Per restituire le chiavi di tutti i valori, utilizzare array_keys() con il parametro opzionale valore_ricerca.
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
Vedere anche array_keys(), array_values(), array_key_exists() e in_array().
array_shift() estrae il primo elemento di array e lo restituisce, accorciando array di un elemento e spostando tutti gli altri all'indietro. Tutte le chiavi numeriche verranno modificate al fine di iniziare il conteggio da zero, mentre gli indici alfabetici non verranno modificati. Se array è vuoto (o non è un array), viene restituito NULL.
Vedere anche array_unshift(), array_push() e array_pop().
array_slice() restituisce la sequenza di elementi dell'array array come specificato dai parametri offset e length .
Se offset è positivo, la sequenza comincerà da quell'offset in array. Se offset è negativo, la sequenza comincerà alla distanza offset dalla fine di array.
Se length è specificata ed è positiva, la sequenza conterrà quel numero di elementi. Se length è specificata ed è negativa la sequenza si fermerà a quel numero di elementi dalla fine dell'array. Se viene omessa, la sequenza conterrà tutto da offset fino alla fine di array.
Si noti che array_slice() ignorerà le chiavi dell'array, e calcolerè gli spiazzamenti e le lunghezze basandosi sulle posizioni correnti degli elementi nell'array.
Esempio 1. esempi di array_slice()
|
Vedere anche array_splice() e unset().
array_splice() rimuove gli elementi specificati da offset e length dall'array input, e li sostituisce con gli elementi dell'array replacement, se fornito. Restituisce un array contenente gli elementi estratti.
Se offset è positivo l'inizio della porzione rimossa è a quella distanza dall'inizio dell'array input. Se offset è negativo inizia a quella distanza dalla fine dell'array input.
Se length è omessa, rimuove tutti gli elementi da offset alla fine dell'array. Se length è specificata a positiva, quel numero di elementi vengono rimossi. Se length è specificata e negativa la porzione da rimuovere terminerà a length elementi dalla fine dell'array. Suggerimento: per rimuovere tutti gli elementi tra offset e la fine dell'array quando è specificato pure replacement, usare count($input) nel parametro length.
Se l'array replacement è specificato, gli elementi rimossi sono sostituiti dagli elementi di questo array. Se offset e length sono tali per cui niente viene rimosso, gli elementi dell'array replacement sono inseriti nella posizione specificata da offset. 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()
|
Vedere anche array_slice()i, unset() e array_merge().
array_sum() restituisce la somma dei valori dell'array sotto forma di integer o float.
Nota: Le versioni di PHP antecedenti alla 4.2.1 modificavano l'array stesso e convertivano le stringhe in numeri (le quali erano convertite in zeri la maggior parte delle volte, a seconda dal valore).
(PHP 5)
array_udiff_assoc -- Computes the difference of arrays with additional index check. The data is compared by using a callback function.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
The result is:
|
In our example above you see the "1" => new cr(4) pair is present in both arrays and thus it is not in the ouput from the function.
For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
Nota: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_udiff_assoc($array1[0], $array2[0], "some_comparison_func");.
See also array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff(), array_udiff_uassoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().
(PHP 5)
array_udiff_uassoc -- Computes the difference of arrays with additional index check. The data is compared by using a callback function. The index check is done by a callback function alsoarray_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
The result is:
|
In our example above you see the "1" => new cr(4) pair is present in both arrays and thus it is not in the ouput from the function. Keep in mind that you have to supply 2 callback functions.
For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
Nota: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_udiff_uassoc($array1[0], $array2[0], "data_compare_func", "key_compare_func");.
See also array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff(), array_udiff_assoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().
(PHP 5)
array_udiff -- Computes the difference of arrays by using a callback function for data comparison.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
The result is:
|
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() prende array e restituisce un nuovo array senza i valori duplicati.
Si noti che le chiavi sono mantenute. array_unique() ordina i valori trattandoli come stringhe, quindi mantiene la prima chiave trovata per ogni valore, e ignorerà tutte le altre chiavi. Questo non significa che la chiave del primo valore dell'array non ancora ordinato verrà mantenuta.
Nota: Due elementi sono considerati uguali se e solo se (string) $elem1 === (string) $elem2. Ovvero: quando la rappresentazione sotto forma di stringa è la stessa.
Verrà usato il primo elemento.
array_unshift() aggiunge gli elementi specificati in testa ad array. Si noti che la lista di elementi è aggiunta in blocco, in modo tale che gli elementi rimangano nello stesso ordine. Tutte le chiavi numeriche vengono modificate per iniziare da zero mentre le chiavi alfabetiche non sono modificate.
Restituisce il nuovo numero di elementi in array.
Vedere anche array_shift(), array_push() e array_pop().
array_values() restituisce tutti i valori dell'array input e indicizza numericamente l'array.
Vedere anche array_keys().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esegue la funzione definita dall'utente identificata da funzione su ogni elemento di array. Normalmente funzione accetta due parametri. Il valore del parametro array viene passato per primo, la chiave/indice per secondo. Se il parametro datiutente è specificato, verrà passato come terzo parametro alla funzione callback.
Se funzione richiede più parametri di quanti gliene vengono passati, un errore di livello E_WARNING verrà generato ogni volta che array_walk() la chiama. Questi avvertimenti possono essere soppressi apponendo l'operatore d'errore @ alla chiamata di array_walk(), oppure usando error_reporting().
Nota: Se funzione deve lavorare con i reali valori dell'array, specificare che il primo parametro di funzione deve essere passato come riferimento. A qesto punto ogni modifica a questi elementi verrà effettuata sull'array stesso.
Nota: Il passaggio della chiave e di datiutente a func è stato aggiunto nella versione 4.0.
array_walk() non è influenzato dal puntatore interno dell'array array. array_walk() percorrerà l'intero array indipendentemente dalla posizione del puntatore. Per reinizializzare il puntatore, utilizzare reset(). In PHP 3, array_walk() reinizializza il puntatore.
Gli utenti non possono modificare l'array attraverso la funzione di callback, ad esempio aggiungere/togliere un elemento, o cancellare l'array su cui array_walk() è applicata. Se l'array viene cambiato, il comportamento di questa funzione non è definito ed è imprevedibile.
Esempio 1. esempio di array_walk()
Il risultato del programma sarà:
|
Vedere anche create_function(), list(), foreach, each() e call_user_func_array().
Restituisce un array contenente i parametri. Ai parametri si può dare un indice con l'operatore =>. Leggere la sezione relativa ai tipi per ulteriori informazioni sugli array.
Nota: array() è un costrutto del linguaggio usato per rappresentare array letterali, e non una normale funzione.
La sintassi "indice => valori", separati da virgole, definisce indici e valori. indice può essere di tipo string o numerico. Quando l'indice è omesso, viene generato automaticamente un indice intero, a partire da 0. Se l'indice è un intero, il successivo indice generato sarà l'indice intero più grande + 1. Si noti che quando due indici identici vengono definiti, l'ultimo sovrascrive il primo.
L'esempio seguente dimostra come creare un array bidimensionale, come specificare le chiavi per gli array associativi, e come modificare la serie degli indici numerici negli array normali.
Si noti che l'indice '3' è definito due volte, e che mantiene il valore finale 13. L'indice 4 è definito dopo l'indice 8, e il successivo indice generato (valore 19) è 9, dal momento che l'indice più grande era 8.
Questo esempio crea un array che parte da 1 (1-based).
Vedere anche array_pad(), list(), foreach e range().
(PHP 3, PHP 4 , PHP 5)
arsort -- Ordina un array in ordine decrescente e mantiene le associazioni degli indiciQuesta funzione ordina un array in modo tale che i suoi indici mantengano la loro correlazione con gli elementi ai quali sono associati. Viene usata principalmente nell'ordinamento degli array associativi, quando la disposizione originaria degli elementi è importante.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. esempio di arsort()
Questo esempio mostrerà:
|
I frutti sono ordinati in ordine alfabetico decrescente, e l'indice associato a ogni elemento è stato mantenuto.
È possibile modificare il comportamento dell'ordinamento usando il parametro opzionale sort_flags, per maggiori dettagli vedere sort().
Questa funzione ordina un array in modo tale che i suoi indici mantengano la loro correlazione con gli elementi ai quali sono associati. Viene usata principalmente nell'ordinamento degli array associativi, quando la disposizione originaria degli elementi è importante.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
I frutti sono ordinati in ordine alfabetico, e l'indice associato ad ogni elemento è stato mantenuto.
È possibile modificare il comportamento dell'ordinamento usando il parametro opzionale sort_flags, per maggiori dettagli vedere sort().
compact() accetta un numero variabile di parametri. Ogni parametro può essere una stringa contenente il nome della variabile, o un array di nomi di variabile. L'array può contenere altri array di nomi di variabile; compact() se ne occupa in modo ricorsivo.
Per ognuno di questi, compact() cerca la variabile con quel nome nella tabella dei simboli corrente, e la aggiunge all'array di output in modo tale che il nome della variabile diventi la chiave e i contenuti della variabile diventino il valore associato a quella chiave. In breve, compact() è l'opposto di extract(). Restituisce l'array di output con tutte le variabili aggiunte a quest'ultimo.
Qualsiasi stringa non valorizzata verrà semplicemente ignorata.
Vedere anche extract().
Restituisce il numero di elementi in var, la quale è di norma un array (dal momento che qualsiasi altro oggetto avrà un elemento).
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 2. esempio di count() ricorsiva (PHP >= 4.2.0)
|
Vedere anche is_array(), isset() e strlen().
Ogni array ha un puntatore interno all'elemento "corrente", che è inizializzato al primo elemento inserito nell'array.
La funzione current() restituisce il valore dell'elemento che è attualmente puntato dal puntatore interno. In ogni caso non muove il puntatore. Se il puntatore interno punta oltre la fine della lista di elementi, current() restituisce FALSE.
Avvertimento |
Se l'array contiene elementi vuoti (0 o "", la stringa vuota) la funzione restituirà FALSE pure per questi elementi. Questo rende impossibile stabilire se si è veramente alla fine della lista in un array di questo tipo usando current(). Per attraversare in modo corretto un array che può contenere elementi vuoti, usare la funzione each(). |
Esempio 1. Esempio di current() e funzioni relative
|
(PHP 3, PHP 4 , PHP 5)
each -- Restituisce la corrente coppia chiave/valore di un array e incrementa il puntatore dell'arrayRestituisce la corrente coppia chiave/valore corrente di array e incrementa il puntatore interno dell'array. Questa coppia è restituita in un array di quattro elementi, con le chiavi 0, 1, key, and value. Gli elementi 0 e key contengono il nome della chiave dell'elemento dell'array, mentre 1 e value contengono i dati.
Se il puntatore interno dell'array punta oltre la fine dei contenuti dell'array, each() restituisce FALSE.
<?php $foo = array("Robert" => "Bob", "Seppo" => "Sepi"); $bar = each($foo); print_r($bar); ?> |
$bar ora contiene la seguente coppia chiave/valore:
Array ( [1] => Bob [value] => Bob [0] => Robert [key] => Robert ) |
each() viene normalmente usata in congiunzione con list() nell'attraversamento di un array; ecco un esempio:
Dopo l'esecuzione di each(), il puntatore dell'array viene lasciato sull'elemento successivo, o sull'ultimo elemento se si è alla fine dell'array. Si deve utilizzare reset() se si vuole riattraversare l'array usando each().
Attenzione |
Poiché assegnare un array ad un'altra variabile reimposta il puntatore, il nostro esempio diventerebbe un loop infinito se assegnassimo $frutta ad un'altra variabile all'interno del ciclo. |
Vedere anche key(), list(), current(), reset(), next(), prev() e foreach.
end() fa avanzare il puntatore di array all'ultimo elemento, e restituisce il suo valore.
Questa funzione viene usata per importare delle variabili da un array nella tabella dei simbloi corrente. Riceve un array associativo var_array e interpreta le chiavi come nomi di variabile e i valori come valori di variabile. Per ogni coppia chiave/valore verrà creata una variabile nella tabella dei simboli corrente, coerentemente con i parametri extract_type e prefix.
Nota: Dalla versione 4.0.5 questa funzione restituisce il numero di variabili estratte.
Nota: EXTR_IF_EXISTS e EXTR_PREFIX_IF_EXISTS sono stati introdotti nella versione 4.2.0.
Nota: EXTR_REFS è stata introdotta nella versione 4.3.0.
extract() controlla ogni chiave per stabilire se costituisce un nome valido di variabile e se ci sono collisioni con variabili già esistenti nella tabella dei simboli. Il modo in cui vengono trattate le chiavi invalide/numeriche e le collisioni è determinato da extract_type. Può essere uno dei seguenti valori:
Se avviene una collisione, sovrascrive la variabile esistente.
Se avviene una collisione, non sovrascrive la variabile esistente.
Se avviene una collisione, mette come prefisso al nome della variabile il parametro prefix.
Mette come prefisso di tutte le variabili il parametro prefix. Dal PHP 4.0.5 questo avviene anche per i valori numerici.
Mette come prefisso, solo per i nomi di variabili invalidi/numerici, il parametro prefix. Questa opzione è stata aggiunta in PHP 4.0.5.
Sovrascrive la variabile solo se già esiste nella tabella dei simboli, altrimenti non fa nulla. Questo è utile per definire una lista di variabili valide e quindi estrarre solo quelle variabili definite in $_REQUEST, per esempio. Questa opzione è stata aggiunta in PHP 4.2.0.
Crea nomi di variabili con il prefisso solo se la versione senza prefisso della stessa variable esiste nella tabella dei simboli. Questa opzione è stata aggiunta in PHP 4.2.0.
Estrae le variabili come riferimenti. Questo in effetti significa che i valori delle variabili importate referenziano i valori del parametro var_array. Si può usare questo flag da solo o combinarlo con gli altri mediante un OR nel parametro extract_type. Questo flag è stato aggiunto nel PHP 4.3.0.
Se extract_type non è specificato, si assume che sia EXTR_OVERWRITE.
Si noti che prefix è richiesto solo se extract_type è EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID o EXTR_PREFIX_IF_EXISTS. Se il risultato non è un nome di variabile valido, non viene importato nella tabella dei simboli.
extract() restituisce il numero di variabili importate con successo nella tabella dei simboli.
Avvertimento |
Non utilizzare extract() su dati non convalidati, come gli input degli utenti ($_GET, ...). Se lo si deve fare, ad esempio per eseguire temporaneamente vecchio codice basato su register_globals, sincerarsi di utilizzare uno dei valori di extract_type come EXTR_SKIP e ricordarsi che occorre estrarre $_SERVER, $_SESSION, $_COOKIE, $_POST e $_GET in questo ordine. |
Un possibile uso di extract() è quello di importare nella tabella dei simboli variabili contenute in un array associativo restituito da wddx_deserialize().
Esempio 1. esempio diextract()
L'esempio mostrerà:
|
La variabile $dimensione non è stata sovrascritta, in quanto è specificato EXTR_PREFIX_SAME, che ha portato alla creazione di $wddx_dimensione. Se fosse stato specificato EXTR_SKIP, $wddx_dimensione non sarebbe stata creata. EXTR_OVERWRITE avrebbe portato $dimensione ad assumere il valore "medio", e EXTR_PREFIX_ALL avrebbe fatto creare nuove variabili chiamate $wddx_colore, $wddx_dimensione e $wddx_forma.
Si deve usare un array associativo, un array indicizzato numericamente non produce risultati a meno di non usare EXTR_PREFIX_ALL o EXTR_PREFIX_INVALID.
Vedere anche compact().
Cerca in pagliaio per trovare ago e restituisce TRUE se viene trovato nell'array, FALSE altrimenti.
Se il terzo parametro strict è TRUE la funzione in_array() controllerà anche il tipo di ago nell'array haystack.
Nota: Se ago è una stringa, il confronto è effettuato tenendo conto delle maiuscole/minuscole.
Nota: Nelle versioni di PHP precedenti la 4.2.0. ago non poteva essere un array.
Esempio 1. esempio di in_array()
La seconda condizione fallisce perché in_array() tiene conto di maiuscole e minuscole, quindi il programma mostrerà:
|
Esempio 3. in_array() con un array come ago
Questo ritornerà:
|
Vedere anche array_search(), array_key_exists() e isset().
key() restituisce la chiave corrispondente all'attuale posizione del puntatore interno all'array.
Esempio 1. esempio di key()
|
Ordina un array rispetto alle sue chiavi, in ordine inverso, mantenendo le associazioni. Questa funzione è utile con gli array associativi.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Si può modificare il comportamento dell'ordinamento usando il parametro opzionale sort_flags, per ulteriori dettagli vedere sort().
Vedere anche asort(), arsort(), ksort(), sort(), natsort() e rsort().
Ordina un array rispetto alle sue chiavi, mantenendo le associazioni. Questa funzione è utile con gli array associativi.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Si può modificare il comportamento dell'ordinamento usando il parametro opzionale sort_flags, per ulteriori dettagli vedere sort().
Vedere anche asort(), arsort(), krsort(), uksort(), sort(), natsort() e rsort().
Nota: Il secondo parametro è stato aggiunto in PHP 4.
Come array(), questa non è in realtà una funzione, bensì un costrutto del linguaggio. list() è usata per assegnare valori ad una lista di variabili in una sola operazione.
Nota: list() funziona solo su array numerici e si aspetta che gli indici numerici partano da 0.
Esempio 1. esempio di list()
|
Esempio 2. Esempio di uso di list()
|
Avvertimento |
list() assegna i valori cominciando dal parametro più a destra. Se si stanno usando variabili semplici, non ci si deve preoccupare di questo fatto. Ma se si stanno usando array con indici di solito ci si aspetta che l'ordine degli indici negli array sia quello scritto negli argomenti della funzione list(), da sinistra a destra; non è così. L'ordine è invertito. |
Esempio 3. Utilizzo di list() con gli indici
Restituisce il segente risultato (si noti l'ordine degli elementi rispetto all'ordine con cui sono stati scritti nella sintassi di list()).
|
(PHP 4 , PHP 5)
natcasesort -- Ordina un array usando un algoritmo di "ordine naturale" non sensibile alle maiuscole/minuscoleQuesta funziona implementa un algoritmo di ordinamento che ordina le stringhe alfanumeriche come lo farebbe un essere umano, mantenendo le associazioni chiavi/valori. Questo è chiamato "ordine naturale".
natcasesort() è una versione, non sensibile alle maiuscole/minuscole, di natsort().
Esempio 1. esempio di natcasesort()
Questo codice genererà il seguente risultato:
Per maggiori informazioni vedere la pagina di Martin Pool Natural Order String Comparison . |
Vedere anche sort(), natsort(), strnatcmp() e strnatcasecmp().
Questa funzione implementa un algoritmo di ordinamento che ordina le stringhe alfanumeriche come lo farebbe un essere umano, mantenendo l'associazione chiavi/valori. Questo è chiamato "ordine naturale". Un esempio della differenza tra questo algoritmo e quello normalmente usato dai computer (usato in sort()) è dato qui sotto:
Esempio 1. esempio di natsort()
Questo codice genererà il seguente risultato:
Per ulteriori informazioni vedere la pagina di Martin Pool Natural Order String Comparison . |
Vedere anche natcasesort(), strnatcmp() e strnatcasecmp().
Restituisce l'elemento dell'array che sta nella posizione successiva a quella attuale indicata dal puntatore interno, oppure FALSE se non ci sono altri elementi.
next() si comporta come current(), con una differenza. Incrementa il puntatore interno dell'array di una posizione, prima di restituire il valore dell'elemento. Ciò significa che restituisce l'elemento successivo e incrementa il puntatore di una posizione. Se l'incremento fa sì che il puntatore vada oltre la fine della lista di elementi, next() restituisce FALSE.
Avvertimento |
Se l'array contiene elementi vuoti, o elementi che hanno il valore chiave uguale a 0 allora questa funzione restituisce FALSE anche per questi elementi. Per esplorare correttamente un array che può contenere elementi vuoti o con chiave uguale a 0 vedere la funzione each(). |
Esempio 1. Esempio di next() e funzioni relative
|
Restituisce l'elemento dell'array che sta nella posizione precedente a quella attuale indicata dal puntatore interno, oppure FALSE se non ci sono altri elementi.
Avvertimento |
Se l'array contiene degli elementi vuoti la funzione restituirà FALSE per questi valori. Per esplorare correttamente un array che può contenere elementi vuoti vedere la funzione each(). |
prev() si comporta come next(), tranne per il fatto di decrementare il puntatore interno di una posizione, invece che incrementarlo.
Esempio 1. Esempio di prev() e funzioni relative
|
range() restituisce una serie di elementi da min a max, inclusiva. Se min > max, la sequenza sarà decrescente.
Nuovo parametro: Il parametro opzionale step è stato aggiunto nel PHP 5.0.0.
Se il valore step è specificato, verrà utilizzato come incremento tra gli elementi della sequenza. step deve essere un numero positivo. Se non specificato, il valore predefinito per step è 1.
Esempio 1. esempi di range()
|
Nota: Prima della versione 4.1.0 la funzione range() generava solo array crescenti di interi. Il supporto per le sequenze di caratteri e array decrescenti è stata aggiunta nella 4.1.0. I valori delle sequenze di caratteri sono limitati alla lunghezza di 1 carattere. Se viene inserito un valore con una lunghezza maggiore, viene utilizzato solo il primo carattere.
Attenzione |
Nel PHP dalla versione 4.1.0 alla 4.3.2, range() vede le stringhe numeriche come stringhe e non come interi. Quindi, verranno utilizzate come sequenze di caratteri. Per esempio, "4242" viene trattato come "4". |
Vedere shuffle(), array_fill() e foreach.
reset() riporta il puntatore di array sul primo elemento e ne restituisce il valore.
Esempio 1. esempio di reset()
|
Questa funzione ordina un array in ordine decrescente.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
I frutti sono stati ordinati in ordine alfabetico decrescente.
Si può modificare il comportamento dell'ordinamento usando il parametro opzionale sort_flags, per maggiori dettagli vedere sort().
Questa funzione mescola un array (rende casuale l'ordine degli elementi).
Nota: Come in PHP 4.2.0, non vi è necessità di inizializzare il generatore di numeri casuali con srand() oppure con mt_srand() poichè viene eseguito in modo automatico.
Vedere anche arsort(), asort(), ksort(), rsort(), sort() e usort().
Questa funzione ordina un array. Gli elementi vengono disposti dal più piccolo al più grande.
Nota: Questa funzione assegna nuove chiavi agli elementi di array. Quindi non si limita a riordinare le chiavi, ma rimuove tutte le chiavi che siano state assegnate.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. esempio di sort()
Questo esempio mostrerà:
|
I frutti sono stati ordinati in ordine alfabetico.
Il secondo parametro opzionale sort_flags può essere usato per modificare il comportamento dell'ordinamento, usando i seguenti valori:
flag d'ordinamento:
SORT_REGULAR - compara gli elementi in modo normale
SORT_NUMERIC - compara gli elementi numericamente
SORT_STRING - compara gli elementi convertiti in stringa
Nota: Il secondo parametro è stato aggiunto in PHP 4.
Vedere anche arsort(), asort(), ksort(), natsort(), natcasesort(), rsort(), usort(), array_multisort() e uksort().
(PHP 3>= 3.0.4, PHP 4 , PHP 5)
uasort -- Ordina un array mediante una funzione definita dall'utente e mantiene le associazioniQuesta funzione ordina un array in modo tale che le chiavi mantengano la loro correlazione con gli elementi dell'array a cui sono associate. Questo è utile quando si ordinano array associativi in cui l'ordine degli elementi è importante. La funzione di comparazione deve essere fornita dall'utente.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche usort(), uksort(), sort(), asort(), arsort(), ksort() e rsort().
(PHP 3>= 3.0.4, PHP 4 , PHP 5)
uksort -- Ordina rispetto alle chiavi di un array mediante una funzione definita dall'utenteuksort() ordina rispetto alle chiavi di un array mediante una funzione di comparazione definita dall'utente. Se si vuole ordinare un array con dei criteri non usuali, si deve usare questa funzione.
La funzione cmp_function deve accettare due parametri che saranno valorizzati con coppie di chiavi di array. La funzione di confronto deve restituire un intero minore, uguale o maggiore di zero se il primo argomento è considerato minore, uguale o maggiore del secondo.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. esempio di uksort()
Questo esempio mostrerà:
|
Vedere anche usort(), uasort(), sort(), asort(), arsort(), ksort(), natsort() e rsort().
Ordina i valori di un array mediante una funzione di comparazione definita dall'utente. Se si vuole ordinare un array con dei criteri non usuali, si deve usare questa funzione.
La funzione di comparazione deve restituire un intero minore, uguale o superiore a zero se il primo elemento è da considerarsi rispettivamente minore, uguale o maggiore del secondo.
Nota: Se due parametri vengono valutati come uguali, il loro ordinamento nell'array ordinato è indefinito. Fino al PHP 4.0.6 le funzioni definite dall'utente mantenevano l'ordine originario per questi elementi, ma con il nuovo algoritmo di ordinamento introdotto con la versione 4.1.0 questo non succede più dal momento che non c'è un modo per ottenerlo in maniera efficiente.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Ovviamente, in questo caso banale di ordinamento decrescente la funzione sort() sarebbe stata più appropriata.
Esempio 2. esempio di usort() con un array multidimensionale
Quando si ordina un array multidimensionale, $a e $b contengono riferimenti al primo indice dell'array. Questo esempio mostrerà:
|
Esempio 3. esempio di usort() usando una funzione membro di un oggetto
Questo esempio mostrerà:
|
Vedere anche uasort(), uksort(), sort(), asort(), arsort(),ksort(), natsort() e rsort().
Le funzioni aspell() permettono di controllare la correttezza di una parola e di offrire suggerimenti.
Nota: Questa estensione è stata rimossa da PHP e non è più disponibile dal PHP 4.3.0. Se si desidera utilizzare le funzioni di correzione ortografica in PHP, utilizzare pspell, che utilizza la libreria pspell e funziona anche con le nuove versioni di aspell.
aspell funziona solo con versioni molto vecchie (più o meno fino alla .27.*) della libreria aspell. Né il presente modulo, né quelle versioni della libreria sono più supportate. Necessita della libreria aspell, disponibile da: http://aspell.sourceforge.net/.
In PHP 4, these functions are only available if PHP was configured with --with-aspell=[DIR].
(PHP 3>= 3.0.7, PHP 4 <= 4.2.3)
aspell_check_raw -- Controlla una parola senza togliere le maiuscole o cercare di eliminare gli spazi inutili [deprecated]aspell_check_raw() controlla la correttezza di una parola, senza modificare le maiuscole/minusciole o cercare di eliminare gli spazi inutili e restituisce TRUE se è corretta, FALSE altrimenti.
aspell_check() controlla la compitazione di una parola e restituisce TRUE se è corretta, FALSE altrimenti.
aspell_new() apre un nuovo dizionario e restituisce un puntatore (link) identificatore del dizionario, da utilizzare in altre funzioni aspell. Restituisce FALSE in caso di errore.
Per la matematica a precisione arbitraria PHP offre il Binary Calculator che supporta numeri di qualsiasi dimensione e precisione, rappresentati da stringhe;
Dalla versione 4.0.4 del PHP, libbcmath è inclusa nella distribuzione. Non c'è bisogno di altre librerie esterne per questa estensione.
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.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Per ulteriori dettagli e definizioni delle costanti PHP_INI_* vedere ini_set().
Breve descrizione dei parametri di configurazione.
Somma il primo operando con il secondo operando e restituisce la somma sotto forma di stringa. Il parametro opzionale precisione è utilizzato per impostare il numero di cifre dopo il punto decimale nel risultato.
Vedere anche bcsub().
Confronta il primo_operando e il secondo_operando e restituisce il risultato sotto forma di intero. Il parametro opzionale precisione è utilizzato per impostare il numero di cifre dopo il punto decimale che verranno usate nel confronto. Il valore restituito è 0 se i due operandi sono uguali. Se il primo_operando è più grande del secondo_operando il valore restituito è +1 e se il primo_operando è minore del secondo_operando il valore restituito è -1.
Divide il primo operando per il secondo operando e restituisce il risultato. Il parametro opzionale precisione imposta il numero di cifre dopo il punto decimale nel risultato.
Vedere anche bcmul().
Ricava il modulo di operando usando modulo.
Vedere anche bcdiv().
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.
Vedere anche bcdiv().
Eleva x alla potenza y. Il parametro opzionale precisione può essere usato per impostare il numero di cifre dopo il punto decimale nel risultato.
Utilizza il metodo di esponenziazione veloce per elevare x alla potenza y rispetto al modulo modulo. Il parametro opzionale precisione può essere utilizzato per impostare il numero di cifre dopo il punto decimale.
Le seguenti istruzioni sono funzionalmente identiche. La versione bcpowmod(), comunque, esegue in meno tempo e può accettare parametri più grandi.
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.
(PHP 3, PHP 4 , PHP 5)
bcscale -- Imposta il valore di precisione di default per tutte le funzioni matematich BCMathQuesta funzione imposta il valore di default del parametro precisione per tutte le funzioni BCMath susseguenti, che non specifichino esplicitamente un parametro di precisione numerica. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Restituisce la radice quadrata di operando. Il parametro opzionale precisione imposta il numero di cifre dopo il punto decimale nel risultato.
Vedere anche bcpow().
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.
Vedere anche bcadd().
Le funzioni bzip2 sono utilizzate per leggere e scrivere in modo trasparente i file compressi con bzip2 (.bz2).
Questo modulo tuilizza le funzioni della libreria bzip2 di Julian Seward. Questo modulo richiede che la versione di bzip2/libbzip2 sia >= 1.0.x.
Il supporto di bzip2 in PHP non è abilitato di default. Si deve utilizzare l'opzione --with-bz2[=DIR] quando si compila PHP, per abilitare il supporto bzip2.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Questa estensione definisce un tipo di risorsa: un puntatore a file che identifica il file bz2 su cui lavorare.
Questo esempio apre un file temporaneo e scrive una stringa di prova su di esso, quindi stampa il contenuto del file.
Esempio 1. breve esempio di bzip2
|
Chiude il file bzip2 referenziato dal puntatore bz.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il puntatore al file deve essere valido, e deve puntare a un file gi$agrave; aperto con bzopen().
Vedere anche bzopen().
bzcompress() comprime la stringa sorgente e la restituisce come dati codificati in bzip2.
Il parametro opzionale dimblocco specifica la dimensione del blocco usato durante la compressione e dovrebbe essere un numero tra 1 e 9 dove 9 dà la compressione migliore, ma usando più risorse. dimblocco ha come valore predefinito 4.
Il parametro opzionale workfactor controlla il comportamento della fase di compressione quando deve trattare col caso peggiore, ovvero dati in ingresso molto ripetitivi. Il valore può variare tra 0 e 250, dove 0 è un caso speciale e 30 è il valore di default. Indipendentemente dal parametro workfactor, i dat generati sono gli stessi.
See also bzdecompress().
bzdecompress() decomprime la stringa sorgente contenente dati codificati in bzip2 e li restituisce. Se il parametro opzionale small è TRUE, verrà usato un algoritmo di decompressione alternativo che richiede meno memoria (la maximum quantità massima di memoria richiesta scende a 2300K) ma funziona a circa la metà della velocità. Vedere la documentazione di bzip2 per maggiori informazioni su questa funzionalità.
See also bzcompress().
Restituisce il codice di un qualsiasi errore bzip2 restituito dal puntatore al file bz.
Vedere anche bzerror() e bzerrstr().
(PHP 4 >= 4.0.4, PHP 5)
bzerror -- Restituisce il codice d'errore bzip2 e la stringa corrispondente in un arrayRestituisce il codice e la stringa di errore, sotto forma di array associativo, di un errore bzip2 restituito dal puntatore bz.
Vedere anche bzerrno() e bzerrstr().
Resituisce la stringa di errore bzip2 restituito dal puntatore bz.
Forza la scrittura di tutti i dati che sono nel buffer del puntatore bz.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Apre un file bzip2 (.bz2) in lettura o scrittura. nomefile è il nome del file da aprire. Il parametro modo è simile a quello della funzione fopen() (`r' per lettura, `w' per scrittura, ecc.).
Se l'operazione fallisce, la funzione restituisce FALSE, altrimenti restituisce un puntatore al file appena aperto.
Vedere anche bzclose().
bzread() legge fino a lunghezza byte dal puntatore bzip2 specificato da bz. La pettura termina quando lunghezza byte (decompressi) sono stati letti o quando viene raggiunto l'EOF. Se il parametro opzionale lunghezza è omesso, bzread() leggerà 1024 byte (decompressi) ogni volta.
bzwrite() scrie il contenuto della stringa dati nel file bzip2 puntato da bz. Se il parametro opzionale lunghezza è specificato, la scrittura si fermerà dopo che siano stati scritti lunghezza byte (decompressi) o al raggiungimento della fine della stringa.
L'estensione calendar presenta una serie di funzioni che semplificano la conversione tra differenti formati di calendario. Il formato intermedio o standard è basato sul Conteggio del Giorno Giuliano. Il Conteggio Giuliano è un conteggio di giorni che parte molto prima di qualsiasi data la maggior parte della gente potrebbe usare (circa il 4000 a.C.). Per convertire tra i sistemi di calendario, si deve prima convertire nel sistema del Giorno Giuliano, poi nel sistema di calendario scelto. Il Conteggio del Giorno Giuliano è molto diverso dal Calendario Giulano! Per maggiori informazioni sui sistemi di calendario vedere http://www.boogle.com/info/cal-overview.html. Parti di questa pagina sono inclusi in queste istruzioni, citate tra virgolette.
Affinché queste funzioni siano disponibili, occorre compilare PHP con l'opzione --enable-calendar.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Le seguenti costanti sono disponibili dal PHP 4.3.0 :
Le seguenti costanti sono disponibili dal PHP 5.0.0 :
(PHP 4 >= 4.1.0, PHP 5)
cal_days_in_month -- Restituisce il numero di giorni di un mese per un dato anno e calendarioQuesta funzione restituisce il numero di giorni che compongono il mese dell'anno nel calendar specificato.
Vedere anche jdtounix().
cal_from_jd() converte il Giorno Giuliano specificato in giornogiuliano in una data del calendario specificato. I valori ammessi di calendario sono CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH e CAL_FRENCH.
Esempio 1. esempio di cal_from_jd()
Questo mostrerà:
|
Vedere anche cal_to_jd().
cal_info() restituisce informazioni sullo specifico calendario o su tutti i calendari supportati se il parametro calendario non è specificato.
Lei informazioni sul calendario sono restituite in un array contenente gli elementi calname, calsymbol, month, abbrevmonth e maxdaysinmonth.
Se calendario non è specificato, le informazioni su tutti i calendari supportati sono restituite nell'array. Questa funzionalità sarà disponibile dal PHP 5.
cal_to_jd() calcola il Giorno Giuliano per una data del calendario specificato. I valori supportati per calendario sono CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH e CAL_FRENCH.
Vedere anche cal_to_jd().
(PHP 3>= 3.0.9, PHP 4 , PHP 5)
easter_date -- Restituisce un timestamp Unix della mezzanotte del giorno di Pasqua di un dato annoRestituisce il timestamp Unix corrispondente alla mezzanotte del giorno di Pasqua dell'anno specificato.
Dal PHP 4.3.0, il parametro anno è opzionale e ha come default l'anno corrente, se omesso.
Avvertimento |
Questa funzione gerererà un allarme (warning) se l'anno è fuori dall'escursione di validità dei timestamp UNIX (cioè prima del 1970 o dopo il 2037). |
La data della Pasqua fu definita dal Concilio di Nicea nel 325 d.C. come la Domenica successiva alla prima luna piena dopo l'Equinozio di Primavera. Si assume che l'Equinozio cada sempre il 21 Marzo, quindi il calcolo si riduce alla determinazione della data della luna piena e la data della Domenica seguente. L'algoritmo qui usato fu proposto attorno all'anno 532 d.C. da Dionysius Exiguus (Dionigi il Piccolo). Nel Calendario Giuliano (for years before 1753) un semplice ciclo di 19 anni è usato per tracciare le fasi della Luna. Nel Calendario Gregoriano (per gli anni dopo il 1753 - ideato da Clavius e Lilius, e introdotto da Papa Gregorio XIII nell'Ottobre 1582, e in Gran Bretagna e nelle sue colonie nel Settembre 1752) due fattori correttivi sono aggiunti per rendere più accurato il ciclo.
(Il codice è basato su un programma in C di Simon Kershaw, <webmaster at ely.anglican dot org>)
Vedere easter_days() per il calcolo della Pasqua prima del 1970 o dopo il 2037.
(PHP 3>= 3.0.9, PHP 4 , PHP 5)
easter_days -- Restituisce il numero di giorni tra il 21 Marzo e Pasqua, dato un annoRestituisce il numero di giorni tra il 21 Marzo e Pasqua per un dato anno. Se l'anno non è specificato, si assume l'anno corrente.
Dal PHP 4.3.0, il parametro anno è opzionale e ha come default l'anno corrente, se omesso.
Anche il parametro metodo è stato introdotto nel PHP 4.3.0 e permette di calcolare la data della Pasqua basata sul calendario Gregoriano durante gli anni 1582 - 1752 quando è impostato a CAL_EASTER_ROMAN, vedere le costanti di calendario per altre costanti valide.
Questa funzione può essere usata al posto di easter_date() per calcolare la Pasqua per gli anni che cadono fuori dalla gamma di validità dei timestamp Unix (cioè prima del 1970 o dopo il 2037).
La data della Pasqua fu definita dal Concilio di Nicea nel 325 d.C. come la Domenica successiva alla prima luna piena dopo l'Equinozio di Primavera. Si assume che l'Equinozio cada sempre il 21 Marzo, quindi il calcolo si riduce alla determinazione della data della luna piena e la data della Domenica seguente. L'algoritmo qui usato fu proposto attorno all'anno 532 d.C. da Dionysius Exiguus (Dionigi il Piccolo). Nel Calendario Giuliano (for years before 1753) un semplice ciclo di 19 anni è usato per traciare le fasi della Luna. Nel Calendario Gregoriano (per gli anni dopo il 1753 - ideato da Clavius e Lilius, e introdotto da Papa Gregorio XIII nell'Ottobre 1582, e in Gran Bretagna e nelle sue colonie nel Settembre 1752) due fattori correttivi sono aggiunti per rendere più accurato il ciclo.
(Il codice è basato su un programma in C di Simon Kershaw, <webmaster at ely.anglican dot org>)
Vedere anche easter_date().
(PHP 3, PHP 4 , PHP 5)
FrenchToJD -- Converte una data del Calendario Repubblicano Francese in un Giorno GiulianoConverte una data del Calendario Repubblicano Francese in un Giorno Giuliano.
Queste funzioni convertono solo le date con gli anni dal 1 al 14 (date Gregoriane dal 22 Settmbre 1792 al 22 Settembre 1806). Questo copre più del periodo in cui fu in uso il calendario.
L'intervallo valido per il Calendario Gregoriano è dal 4714 a.C. al 9999 d.C.
Anche se questa funzione può gestire date fino al 4714 a.C., qusto utilizzo potrebbe non avere senso. Il calendario Gregoriano fu istituito il 15 Ottobre 1582 (o 5 Ottobre 1582 nel calendario Giuliano). Alcune nazioni non lo accettarono per un lungo periodo. Per esempio, il Regno Unito si convertì nel 1752, L'Unione Sovietica nel in 1918 e la Grecia nel 1923. La maggior parte delle nazioni Europee usavano il calendario Giuliano prima del Gregoriano.
Restituisce il giorno della settimana. Può restituire una stringa o un intero a seconda del modo.
Restituisce una stringa contenente il nome di un mese. modo dice alla funzione verso quale calendario convertire il giorno Giuliano, e che tipo di nome di mese restituire.
Tabella 1. Modi del Calendario
Modo | Significato | Valori |
---|---|---|
0 | Gregoriano abbreviato | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec |
1 | Gregoriano | January, February, March, April, May, June, July, August, September, October, November, December |
2 | Giuliano abbreviato | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec |
3 | Giuliano | January, February, March, April, May, June, July, August, September, October, November, December |
4 | Giudeo | Tishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul |
5 | Repubblicano Francese | Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra |
(PHP 3, PHP 4 , PHP 5)
JDToFrench -- Converte un Giorno Giuliano in una data del Calendario Repubblicano FranceseConverte un Giorno Giuliano in una data del calendario Repubblicano Francese.
Converte il Giorno Giuliano in una stringa contenente la data Gregoriana nel formato "mese/giorno/anno".
Converte un Giorno Giuliano nel Calendario Giudeo.
I parametri opzionali ebraico e fl sono disponibili dal PHP 5.0.0
Se il parametro ebraico è TRUE, il parametro fl è usato per il formato di output Ebraico. I formati disponibili sono: CAL_JEWISH_ADD_ALAFIM_GERESH, CAL_JEWISH_ADD_ALAFIM, CAL_JEWISH_ADD_GERESHAYIM.
Converte un Giorno Giuliano in una stringa contenente la data del calendario Giuliano nel formato "mese/giorno/anno".
Questa funzione restituisce un timestamp Unix corrispondente al Giorno Giuliano giornogiuliano o FALSE se giornogiuliano non è all'interno della gamma Unix (anni Gregoriani tra il 1970 e il 2037 o 2440588 <= giornogiuliano <= 2465342 ). L'ora restituita è locale (e non GMT).
See also unixtojd().
Anche se questa funzione può gestire date fino all'anno 1 (3761 B.C.), questo utilizzo potrebbe non avere senso. Il calendario Giudeo è usato da parecchie migliaia di anni, ma nei primi tempi non c'era una formula per stabilire l'inizio del mese. Il nuovo mese iniziava quando si vedeva la prima volta la luna.
L'intervallo valido per il Calendario Giuliano è dal 4713 a.C. al 9999 d.C.
Anche se questa funzione può gestire date fino al 4713 a.C., questo utilizzo potrebbe non avere senso. Il calendario fu creato nel 46 a.C., ma i dettagli non furono perfezionati fino almeno al 8 d.C., e forse anche fino al quarto secolo. Inoltre, l'inizio dell'anno variava da una cultura all'altra - non tutti accettavano Gennaio come primo mese.
Attenzione |
Il calendario attuale, utilizzato in tutto il mondo, è il calendario Gregoriano. gregoriantojd() può essere utilizzata per convertire queste date nel corrispondente Giorno Giuliano. |
Restituisce il Giorno Giuliano di un timestamp Unix (secondi dal 1/1/1970), o del giorno corrente se timestamp non è specificato.
Vedere anche jdtounix().
Queste funzioni si interfacciano con le API CCVS, permettendo di lavorare direttamente con CCVS dagli script PHP. CCVS è la soluzione di RedHat per il "mediatore" nella gestione dei pagamenti con carta di credito. Permette di comunicare direttamente con le società di autorizzazione di transazione attraverso una *nix box e un modem. Usando il modulo CCVS per PHP, è possibile procesare direttamente le carte di credito attraverso gli script PHP. Le seguenti informazioni esemplificheranno il processo.
Nota: CCVS è stato abbandonato da Red Hat e non c'è l'intenzione di fornire altre chiavi o contratti di assistenza. Chi cerca un sostituto può considerare MCVE della Main Street Softworks come una possibile alternativa. Il prodotto è simile nella struttura ed ha un supporto documentato per PHP!
Questa estensione è stata rimossa dal PHP e non è più disponibile dal PHP 4.3.0. Se si vogliono utilizzare delle funzioni di processamento delle carte di credito, utilizzare piuttosto MCVE.
To enable CCVS Support in PHP, first verify your CCVS installation directory. You will then need to configure PHP with the --with-ccvs option. If you use this option without specifying the path to your CCVS installation, PHP will attempt to look in the default CCVS Install location (/usr/local/ccvs). If CCVS is in a non-standard location, run configure with: --with-ccvs=[DIR], where DIR is the path to your CCVS installation. Please note that CCVS support requires that DIR/lib and DIR/include exist, and include cv_api.h under the include directory and libccvs.a under the lib directory.
Additionally, a ccvsd process will need to be running for the configurations you intend to use in your PHP scripts. You will also need to make sure the PHP Processes are running under the same user as your CCVS was installed as (e.g. if you installed CCVS as user 'ccvs', your PHP processes must run as 'ccvs' as well.)
RedHat non supporta più CCVS; comunque una documentazione leggermente datata è ancora disponibile presso http://redhat.com/docs/manuals/ccvs/.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.0.2 - 4.2.3 only)
ccvs_command -- Esegue un comando caratteristico di un particolare protocollo, quindi non disponibile nelle API di CCVS
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.0.2 - 4.2.3 only)
ccvs_count -- Conta quante transazioni di un dato tipo sono archiviate nel sistema
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.0.2 - 4.2.3 only)
ccvs_return -- Trasferisce fondi dal merchant al titolare della carta di credito
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.0.2 - 4.2.3 only)
ccvs_textvalue -- Restuisce il valore testuale reso dalla precedente chiamata di funzione
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
COM è una tecnologia che permette il riutilizzo del codice scritto in un qualsiasi linguaggio utilizzando una convenzione standard di chiamate e nascondendo dietro a delle API i dettagli di implementazione quali la macchina su cui il Componente è conservato e il file eseguibile che lo ospita. Si può pernsare a COM com a un meccanismo avanzato di Remote Procedure Call (RPC) con alcune basi di programmazione ad oggetti. COM separa l'implementazione dall'interfaccia.
COM incoraggia il versioning, la separazione tra interfaccia e implementazione e l'occultamento dei dettagli dell'implementazione, come la posizione dell'eseguibile e il linguaggio di programmazione.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. opzioni di configurazione Com
Nome | Default | Modificabile in |
---|---|---|
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 |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Per maggiori informazioni su COM si leggano le specifiche COM o si guardi anche la documentazione di Don Box su Yet Another COM Library (YACL)
costruttore della classe COM. Parametri:
nome o class-id del componente desiderato.
nome del server DCOM dal quale deve essere richiamato il componente. Se NULL, si assume localhost. Per permettere l'uso di DCOM il parametro com.allow_dcom deve essere impostato a TRUE in php.ini.
specifica la codepage che verrà usata per convertire le stringhe di PHP in stringhe Unicode e viceversa. I valori possibili sono CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 e CP_UTF8.
Esempio 1. esempio di COM (1)
|
Esempio 2. esempio di COM (2)
|
The DOTNET class allows you to instantiate a class from a .Net assembly and call its methods and access its properties.
DOTNET class constructor. assembly_name specifies which assembly should be loaded, and class_name specifices which class in that assembly to instantiate. You may optionally specify a codepage to use for unicode string transformations; see the COM class for more details on code pages.
The returned object is an overloaded object, which means that PHP does not see any fixed methods as it does with regular classes; instead, any property or method accesses are passed through to COM and from there to DOTNET. In other words, the .Net object is mapped through the COM interoperability layer provided by the .Net runtime.
Once you have created a DOTNET object, PHP treats it identically to any other COM object; all the same rules apply.
Nota: You need to install the .Net runtime on your web server to take advantage of this feature.
costruttore della classe VARIANT. Parametri:
valore iniziale. se omesso viene creato un oggetto VT_EMPTY.
specifica il tipo di contenuto dell'oggetto VARIANT. I valori possibili sono VT_UI1, VT_UI2, VT_UI4, VT_I1, VT_I2, VT_I4, VT_R4, VT_R8, VT_INT, VT_UINT, VT_BOOL, VT_ERROR, VT_CY, VT_DATE, VT_BSTR, VT_DECIMAL, VT_UNKNOWN, VT_DISPATCH e VT_VARIANT. Questi valori sono mutuallmente esclusivi, ma possono essere combinati con VT_BYREF per specificare che è un valore. Se omesso, viene usato il tipo di valore. Consultare la libreria MSDN per ulteriori informazioni.
specifica la codepage che è usata per convertire le stringhe PHP in stringhe unicode e viceversa. I valori possibili sono CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 e CP_UTF8.
Generates a Globally Unique Identifier (GUID) and returns it as a string. A GUID is generated in the same way as DCE UUID's, except that the Microsoft convention is to enclose a GUID in curly braces.
See also uuid_create() in the PECL uuid extension.
Instructs COM to sink events generated by comobject into the PHP object sinkobject. PHP will attempt to use the default dispinterface type specified by the typelibrary associated with comobject, but you may override this choice by setting sinkinterface to the name of the dispinterface that you want to use.
sinkobject should be an instance of a class with methods named after those of the desired dispinterface; you may use com_print_typeinfo() to help generate a template class for this purpose.
Be careful how you use this feature; if you are doing something similar to the example below, then it doesn't really make sense to run it in a web server context.
Esempio 1. COM event sink example
|
See also com_print_typeinfo(), com_message_pump().
(no version information, might be only in CVS)
com_get_active_object -- Returns a handle to an already running instance of a COM objectcom_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. |
Restituisce il valore della proprietà nome_prop del componente COM referenziato da oggetto_com. Restituisce FALSE in caso di errore.
com_invoke() chiama un metodo del componente COM referenziato da oggetto_com. Restituisce FALSE in caso di errore, altrimenti restituisce il valore di ritorno di nome_funzione.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
com_load() crea un nuovo componente COM e ne restituisce un riferimento. Restituisce FALSE in caso di errore. I possibili valori per codepage sono CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 e CP_UTF8.
(PHP 4 >= 4.2.3, PHP 5)
com_message_pump -- Process COM messages, sleeping for up to timeoutms millisecondsThis function will sleep for up to timeoutms milliseconds, or until a message arrives in the queue. If a message or messages arrives before the timeout, they will be dispatched, and the function will return TRUE. If the timeout occurs and no messages were processed, the return value will be FALSE. If you do not specify a value for timeoutms, then 0 will be assumed. A 0 value means that no waiting will be performed; if there are messages pending they will be dispatched as before; if there are no messages pending, the function will return FALSE immediately without sleeping.
The purpose of this function is to route COM calls between apartments and handle various synchronization issues. This allows your script to wait efficiently for events to be triggered, while still handling other events or running other code in the background. You should use it in a loop, as demonstrated by the example in the com_event_sink() function, until you are finished using event bound COM objects.
(PHP 4 >= 4.2.3, PHP 5)
com_print_typeinfo -- Print out a PHP class definition for a dispatchable interfaceThe purpose of this function is to help generate a skeleton class for use as an event sink. You may also use it to generate a dump of any COM object, provided that it supports enough of the introspection interfaces, and that you know the name of the interface you want to display.
comobject should be either an instance of a COM object, or be the name of a typelibrary (which will be resolved according to the rules set out in com_load_typelib()). dispinterface is the name of an IDispatch descendant interface that you want to display. If wantsink is TRUE, the corresponding sink interface will be displayed instead.
See also com_event_sink(), com_load_typelib().
Imposta il valore della proprietà nome_prop del componente COM referenziato da oggetto_com. Restituisce il valore appena impostato in caso di successo,, FALSE altrimenti.
Returns the absolute value of val.
See also abs().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Adds left to right using the following rules (taken from the MSDN library), which correspond to those of Visual Basic:
Tabella 1. Variant Addition Rules
If | Then |
---|---|
Both expressions are of the string type | Concatenation |
One expression is a string type and the other a character | Addition |
One expression is numeric and the other is a string | Addition |
Both expressions are numeric | Addition |
Either expression is NULL | NULL is returned |
Both expressions are empty | Integer subtype is returned |
See also variant_sub().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs a bitwise AND operation, according to the following truth table; note that this is slightly different from a regular AND operation.
Tabella 1. Variant AND Rules
If left is | If right is | then the result is |
---|---|---|
TRUE | TRUE | TRUE |
TRUE | FALSE | FALSE |
TRUE | NULL | NULL |
FALSE | TRUE | FALSE |
FALSE | FALSE | FALSE |
FALSE | NULL | FALSE |
NULL | TRUE | NULL |
NULL | FALSE | FALSE |
NULL | NULL | NULL |
See also variant_or().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
This function makes a copy of variant and then performs a variant cast operation to force the copy to have the type given by type. type should be one of the VT_XXX constants.
This function wraps VariantChangeType() in the COM library; consult MSDN for more information.
See also variant_set_type().
Concatenates left with right and returns the result.
See also la Sezione Operatori di stringa nel Capitolo 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.
Compares left with right and returns one of the following values:
Tabella 1. Variant Comparision Results
value | meaning |
---|---|
VARCMP_LT | left is less than right |
VARCMP_EQ | left is equal to right |
VARCMP_GT | left is greater than right |
VARCMP_NULL | Either left, right or both are NULL |
This function will only compare scalar values, not arrays or variant records.
lcid is a valid Locale Identifier to use when comparing strings (this affects string collation). flags can be one or more of the following values OR'd together, and affects string comparisons:
Tabella 2. Variant Comparision Flags
value | meaning |
---|---|
NORM_IGNORECASE | Compare case insensitively |
NORM_IGNORENONSPACE | Ignore nonspacing characters |
NORM_IGNORESYMBOLS | Ignore symbols |
NORM_IGNOREWIDTH | Ignore string width |
NORM_IGNOREKANATYPE | Ignore Kana type |
NORM_IGNOREKASHIDA | Ignore Arabic kashida characters |
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Converts timestamp from a unix timestamp value into a variant of type VT_DATE. This allows easier interopability between the unix-ish parts of PHP and COM.
See also variant_date_to_timestamp() for the inverse of this operation, mktime(), time().
Converts variant from a VT_DATE (or similar) value into a unix timestamp. This allows easier interopability between the unix-ish parts of PHP and COM.
See also variant_date_from_timestamp() for the inverse of this operation, date(), strftime().
Divides left by right and returns the result, subject to the following rules:
Tabella 1. Variant Division Rules
If | Then |
---|---|
Both expressions are of the string, date, character, boolean type | Double is returned |
One expression is a string type and the other a character | Division and a double is returned |
One expression is numeric and the other is a string | Division and a double is returned. |
Both expressions are numeric | Division and a double is returned |
Either expression is NULL | NULL is returned |
right is empty and left is anything but empty | A com_exception with code DISP_E_DIVBYZERO is thrown |
left is empty and right is anything but empty. | 0 as type double is returned |
Both expressions are empty | A com_exception with code DISP_E_OVERFLOW is thrown |
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
If each bit in left is equal to the corresponding bit in right then TRUE is returned, otherwise FALSE is returned.
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
If variant is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of variant.
See also variant_int(), variant_round(), floor(), ceil(), round().
Avvertimento |
This documentation is based on the MSDN documentation; it appears that this function is either the same as variant_int(), or that there is an error in the MSDN documentation. |
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
This function returns an integer value that indicates the type of variant, which can be an instance of COM, DOTNET or VARIANT classes. The return value can be compared to one of the VT_XXX constants.
The return value for COM and DOTNET objects will usually be VT_DISPATCH; the only reason this function works for those classes is because COM and DOTNET are descendants of VARIANT.
In PHP versions prior to 5, you could obtain this information from instances of the VARIANT class ONLY, by reading a fake type property. See the VARIANT class for more information on this.
Converts left and right to integer values, and then performs integer division according the following rules:
Tabella 1. Variant Integer Division Rules
If | Then |
---|---|
Both expressions are of the string, date, character, boolean type | Division and integer is returned |
One expression is a string type and the other a character | Division |
One expression is numeric and the other is a string | Division |
Both expressions are numeric | Division |
Either expression is NULL | NULL is returned |
Both expressions are empty | A com_exception with code DISP_E_DIVBYZERO is thrown |
See also variant_div().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs a bitwise implication operation, according to the following truth table:
Tabella 1. Variant Implication Table
If left is | If right is | then the result is |
---|---|---|
TRUE | TRUE | TRUE |
TRUE | FALSE | TRUE |
TRUE | NULL | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | TRUE |
FALSE | NULL | TRUE |
NULL | TRUE | TRUE |
NULL | FALSE | NULL |
NULL | NULL | NULL |
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
If variant is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of variant.
See also variant_fix(), variant_round(), floor(), ceil(), round().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Divides left by right and returns the remainder.
See also variant_div(), variant_idiv().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Multiplies left by right and returns the result, subject to the following rules:
Tabella 1. Variant Multiplication Rules
If | Then |
---|---|
Both expressions are of the string, date, character, boolean type | Multiplication |
One expression is a string type and the other a character | Multiplication |
One expression is numeric and the other is a string | Multiplication |
Both expressions are numeric | Multiplication |
Either expression is NULL | NULL is returned |
Both expressions are empty | Empty string is returned |
Boolean values are converted to -1 for FALSE and 0 for TRUE.
See also variant_div(), variant_idiv().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs logical negation of variant and returns the result.
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs bitwise not negation on variant and returns the result. If variant is NULL, the result will also be NULL.
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs a bitwise OR operation, according to the following truth table; note that this is slightly different from a regular OR operation.
Tabella 1. Variant OR Rules
If left is | If right is | then the result is |
---|---|---|
TRUE | TRUE | TRUE |
TRUE | FALSE | TRUE |
TRUE | NULL | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | FALSE |
FALSE | NULL | NULL |
NULL | TRUE | TRUE |
NULL | FALSE | NULL |
NULL | NULL | NULL |
See also variant_and(), variant_xor().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Returns the result of left to the power of right.
See also pow().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Returns the value of variant rounded to decimals decimal places.
See also round().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
This function is similar to variant_cast() except that the variant is modified "in-place"; no new variant is created. The parameters for this function have identical meaning to those of variant_cast().
See also variant_cast().
Converts value to a variant and assigns it to the variant object; no new variant object is created, and the old value of variant is freed/released.
(PHP 5)
variant_sub -- subtracts the value of the right variant from the left variant value and returns the resultSubtracts right from left using the following rules:
Tabella 1. Variant Subtraction Rules
If | Then |
---|---|
Both expressions are of the string type | Subtraction |
One expression is a string type and the other a character | Subtraction |
One expression is numeric and the other is a string | Subtraction. |
Both expressions are numeric | Subtraction |
Either expression is NULL | NULL is returned |
Both expressions are empty | Empty string is returned |
See also variant_add().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs a logical exclusion, according to the following truth table:
Tabella 1. Variant XOR Rules
If left is | If right is | then the result is |
---|---|---|
TRUE | TRUE | FALSE |
TRUE | FALSE | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | FALSE |
NULL | NULL | NULL |
See also variant_and(), variant_or().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Queste funzioni permettono di ottenere informazioni sulle classi e sulle istanze degli oggetti. Si può ricavare il nome della classe da cui deriva un dato oggetto, come le sue proprietà e i suoi metodi. Utilizzando queste funzioni si ottiene, non solo a quale classe appartiene un dato oggetto, ma anche i suoi "padri" (ad esempio da quale classe è derivata la classe dell'oggetto).
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
In questo esempio, prima si definisce una classe base, quindi una seconda che deriva dalla prima. La classe base descrive gli aspetti generali degli ortaggi, se è commestibile e quale sia il colore. La classe derivata Spinaci aggiunge i metodi di cottura e di verifica della completa cottura.
Esempio 1. classi.inc
|
A questo punto si istanziano 2 oggetti a partire da queste classi e si visualizzeranno le informazioni relative a questi oggetti, compresi i loro padri. Verranno anche inserite funzioni di utilità principalmente con lo scopo di rendere chiara la visualizzazione delle variabili.
Esempio 2. test_script.php
Un aspetto da notare nell'esempio precedente è che l'oggetto $frondoso è un'istanza della classe Spinaci che a sua volta è una sottoclasse di Ortaggio, quindi l'ultima parte dell'esempio visualizzerà:
|
(PHP 4 >= 4.0.5, PHP 5)
call_user_method_array -- Richiama il metodo dato con un array di parametri [deprecated]Avvertimento |
A partire dalla versione 4.1.0 è sconsigliato l'uso di call_user_method_array(); in sostituzione utilizzare la serie di funzioni call_user_func_array() con sintassi array(&$obj, "method_name"). |
Richiama il metodo indicato da nome_metodo dell'oggetto oggetto, utilizzando i parametri forniti in array_parametri.
Vedere anche: call_user_func_array() e call_user_func().
(PHP 3>= 3.0.3, PHP 4 , PHP 5)
call_user_method -- Chiama un metodo dell'oggetto indicato [deprecated]Avvertimento |
A partire dalla versione 4.1.0 l'uso della funzione call_user_method() è sconsigliato; in sostituzione utilizzare la serie call_user_func() con la sintassi array(&$obj, "method_name"). |
Richiama il metodo indicato da nome_metodo dell'oggetto oggetto. Di seguito si fornisce un esempio di utilizzo. Qui si definisce una classe, si istanzia un oggetto, e si utilizza call_user_method() per richiamare il metodo stampa_info
<?php class Stato { var $NOME; var $TLD; function Stato($nome, $tld) { $this->NOME = $nome; $this->TLD = $tld; } function stampa_info($prestr = "") { echo $prestr . "Stato: " . $this->NOME . "\n"; echo $prestr . "Dominio di primo livello: " . $this->TLD . "\n"; } } $paese = new Stato("Peru", "pe"); echo "* Richiamo il metodo direttamente\n"; $paese->stampa_info(); echo "\n* utilizzo dello stesso metodo in modo indiretto\n"; call_user_method("stampa_info", $paese, "\t"); ?> |
Vedere anche call_user_func_array() e call_user_func().
Questa funzione restituisce TRUE se la classe indicata dal parametro nome_classe è stata definita, altrimenti restituisce FALSE .
Vedere anche get_declared_classes().
Questa funzione restituisce un array contenente i nomi dei metodi definiti per la classe specificata da nome_classe.
Nota: Dalla versione 4.0.6 di PHP, si può specificare direttamente l'oggetto anziché la classe nel parametro nome_classe. Ad esempio:
Esempio 1. Esempio di get_class_methods()
Produrrà:
|
Vedere anche get_class_vars() e get_object_vars()
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
Produrrà:
|
Vedere anche get_class_methods() e get_object_vars()
Questa funzione restituisce il nome della classe di cui l'oggetto oggetto è un'istanza. Restituisce FALSE se oggetto non è un oggetto.
Nota: Le classi definite nei moduli di PHP sono restituite nella notazione originale. In PHP 4, get_class() restituisce il nome delle classi definite dagli utenti in minuscolo, mentre in PHP 5 i nomi delle classi saranno restituiti nella notazione originale, come i nomi delle classi nei moduli.
Esempio 1. Utilizzo di get_class()
L'esempio precedente visualizzerà:
|
Vedere anche get_parent_class(), gettype() e is_subclass_of()
Questa funzione restituisce un array con i nomi delle classi definite all'interno dello script corrente.
Nota: Nella versione 4.0.1pl2 di PHP, in testa all'array erano indicate tre ulteriori classi: stdClass (definita in Zend/zend.c), OverloadedTestClass (definita in ext/standard/basic_functions.c) e Directory (definita in ext/standard/dir.c).
Occorre notare che, in base a quali librerie sono state compilate in PHP, possono essere rilevate ulteriori classi. Questo significa, anche, che non si potranno definire delle classi con questi nomi. Un'elenco delle classi predefinite è nella sezione Predefined Classes dell'appendice.
Vedere anche class_exists() e get_declared_interfaces().
This function returns an array of the names of the declared interfaces in the current script.
See also get_declared_classes().
Questa funzione restituisce un array associativo con le proprietà definite nell'oggetto passato nel parametro oggetto .
Nota: Nelle versioni di PHP precedenti la 4.2.0, le eventuali variabili dichiarate in nella classe oggetto ma non ancora valorizzate non saranno restituite nell'array. Nelle versioni successive alla 4.2.0, saranno restituite nell'array con valore NULL.
Esempio 1. Utilizzo di get_object_vars()
L'output del programma precedente sarà:
|
Vedere anche get_class_methods() e get_class_vars().
(PHP 4 , PHP 5)
get_parent_class -- Restituisce il nome della classe genitrice di un oggetto o di una classeSe oggetto è un oggetto, la funzione restituisce il nome del genitore della classe di cui oggetto è un'istanza.
Se oggetto è una stringa, la funzione restituisce il nome della classe genitrice della classe di cui oggetto indica il nome. Questa funzionalità è stata aggiunta nella versione 4.0.5 di PHP.
Esempio 1. Utilizzo di get_parent_class()
L'esempio visualizzerà:
|
Vedere anche get_class(), is_subclass_of()
(PHP 4 >= 4.2.0, PHP 5)
is_a -- Restituisce TRUE se l'oggetto appartiene a questa classe o se ha questa classe tra i suoi genitoriQuesta funzione restituisce TRUE appartiene a questa classe oppure ha questa classe tra i suoi genitori, FALSE in caso diverso.
In PHP 5 la funzione is_a() è sconsigliata in favore di instanceof. L'esempio precedente, in PHP 5, può essere riscritto come:
Vedere anche get_class(), get_parent_class() e is_subclass_of().
(PHP 4 , PHP 5)
is_subclass_of -- Restituisce TRUE se l'oggetto ha questa classe come uno dei suoi genitoriQuesta funzione restituisce TRUE se obj, appartiene ad una sottoclasse di nome_classe, altrimenti FALSE.
Vedere anche get_class(), get_parent_class() e is_a().
ClibPDF permette di creare documenti PDF utilizzando PHP. La funzionalità e l' API di ClibPDF sono simili a quelle di PDFlib. Questa documentazione dovrebbe essere letta insieme al manuale di ClibPDF poichè entra maggiormente nel dettaglio della libreria.
Molte funzioni nella ClibPDF nativa e nel modulo PHP , così come nella PDFlib hanno lo stesso nome. Tutte le funzioni ad eccezione di cpdf_open() hanno l'identificatore del documento come loro primo parametro.
Attualmente questo identificatore non è usato internamente dato che ClibPDF non supporta la creazione di svariati documenti PDF contemporaneamente. Attualmente non bisognerebbe provare a farlo, dato che i risultati sono imprevedibili. Non è possibile controllare quali siano le conseguenze in un ambiente multi processo. Secondo l'autore di ClibPDF questo cambierà in una delle prossime release (la versione corrente quando questo è stato scritto è la 1.10). Se si ha bisogno di questa funzionalità utilizzare il modulo pdflib.
Un'interessante caratteristica di ClibPDF (e PDFlib) è l'abilità di creare il documento PDF completamente in memoria senza utilizzare file temporanei. Inoltre fornisce l'abilità di passare le coordinare in un'unità di lunghezza predefinita. (Questa caratteristica puo'essere simulata da pdf_translate() quando si utilizzano le funzioni PDFlib.)
Un'altra interessante caratteristica di ClibPDF è il fatto che ogni pagina può essere modificata in qualsiasi momento anche se è già stata aperta una nuova pagina. La funzione cpdf_set_current_page() permette di lasciare la pagina corrente e modificare un'altra pagina.
La maggioranza delle funzioni sono abbastanza facili da usare. La parte più difficile è probabilmente creare un simplice documento PDF. L'esempio seguente dovrebbe essere utile per cominciare. Crea un documento con una pagina. La pagina contiene il testo "Times-Roman" con un font di 30pt. Il testo è sottolineato.
Nota: Se si è interessati ad alternativi generatori PDF free non utilizzare le librerie PDF esterne, vedere questa FAQ per dettagli.
Per potere utilizzare le funzioni ClibPDF occorre installare il modulo ClibPDF. Questo è disponibile in FastIO, ma richiede l'acquisto di una licenza per uso commerciale. Il PHP richiede la libreria cpdflib >= 2.
Per avere disponibili queste funzionalità occorre compilare il PHP con --with-cpdflib[=DIR]. Dove DIR indica la directory in cui è installato cpdflib, per default /usr. In aggiunta si può specificare le librerie jpeg e tiff da utilizzare. Per fare ciò aggiungere alla linea di configurazione le opzioni --with-jpeg-dir[=DIR] e --with-tiff-dir[=DIR].
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Esempio 1. Semplice esempio ClibPDF
|
La distribuzione pdflib contiene un esempio più complicato che crea una serie di pagine con un orologio analogico. Di seguito si trova questo esempio convertito in PHP utilizzando l'estensione ClibPDF:
Esempio 2. esempio pdfclock dalla distribuzione pdflib 2.0
|
La cpdf_add_annotation() aggiunge una nota con l'angolo in basso a sinistra in (llx, lly) e l'angolo in alto a destra in (urx, ury).
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.
La funzione cpdf_add_outline() aggiunge un segnalibro con il testo testo che punta alla pagina corrente.
Esempio 1. Aggiungere il contorno alla pagina
|
La funzione cpdf_arc() disegna un arco con centro nel punto (x-coor, y-coor) e raggio radius, che comincia all'angolo inizio e che termina all'angolo fine.
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().
La funzione cpdf_begin_text() avvia una sezione di testo. Deve essere terminata con cpdf_end_text().
Vedere anche cpdf_end_text().
La funzione cpdf_circle() disegna un cerchio con centro nel punto (x-coor, y-coor) e raggio raggio.
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().
La funzione cpdf_clip() taglia tutti i disegni dal path corrente.
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().
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().
(PHP 3>= 3.0.8, PHP 4 , PHP 5)
cpdf_closepath_stroke -- Chiude il path e disegna una linea lungo il pathLa funzione cpdf_closepath_stroke() è una combinazione di cpdf_closepath() e cpdf_stroke(). Dopo libera il path.
Vedere anche cpdf_closepath() e cpdf_stroke().
La funzione cpdf_closepath() chiude la path corrente.
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().
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().
La funzione cpdf_end_text() termina una sezione di testo cominciata con cpdf_begin_text().
Vedere anche cpdf_begin_text().
The cpdf_fill_stroke() function fills the interior of the current path with the current fill color and draws current path.
See also cpdf_closepath(), cpdf_stroke(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().
La funzione cpdf_fill() riempie l'interno del path corrente con il colore di riempimento corrente.
Vedere anche cpdf_closepath(), cpdf_stroke(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill() e cpdf_setrgbcolor().
La funzione cpdf_finalize_page() chiude la pagina numero numero della pagina.
Questa funzione serve solo a preservare la memoria. Una pagina chiusa occupa meno memoria ma non può più essere modificata.
Vedere anche cpdf_page_init().
La funzione cpdf_finalize() chiude il documento. Bisogna comunque richiamare cpdf_close()
Vedere anche cpdf_close().
The cpdf_global_set_document_limits() function sets several document limits. This function has to be called before cpdf_open() to take effect. It sets the limits for any document open afterwards.
See also cpdf_open().
La funzione cpdf_import_jpeg() apre un'immagine contenuta nel file con nome nome del file. Il formato dell'immagine deve essere jpeg. L' immagine viene inserita nella pagina corrente alla posizione (x-coor, y-coor). L'immagine è ruotata di angolo gradi.
Il parametro 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().
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().
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.
La funzione cpdf_newpath() inizia un nuovo path sul documento indicato dal parametro documento pdf.
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().
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().
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().
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().
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.
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.
Vedere anche cpdf_save().
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().
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().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione cpdf_rotate() effettua una rotazione di angolo gradi.
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().
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().
La funzione cpdf_scale() applica il coefficiente di scala in entrambe le direzioni.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione cpdf_set_char_spacing() imposta la spaziatura fra caratteri.
Vedere anche cpdf_set_word_spacing() e cpdf_set_leading().
La funzione cpdf_set_creator() imposta il creatore del documento pdf.
Vedere anche cpdf_set_subject(), cpdf_set_title() e cpdf_set_keywords().
La funzione cpdf_set_current_page() imposta la pagina sulla quale vengono eseguite tute le operazioni. Ci si può spostare sulle pagine finchè una pagina non è chiusa con cpdf_finalize_page().
Vedere anche cpdf_finalize_page().
(PHP 4 >= 4.0.6, PHP 5)
cpdf_set_font_directories -- Imposta le directory in cui cercare quando si utilizzano font esterni
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.0.6, PHP 5)
cpdf_set_font_map_file -- Imposta la tabella di associazione tra nome di file e nome di font, quando si usano font esterni
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 3>= 3.0.8, PHP 4 , PHP 5)
cpdf_set_font -- Seleziona l'aspetto e la dimensione del font correnteLa funzione cpdf_set_font() imposta l'aspetto, la dimensione e la codifica del font corrente. Attualmente solo i font standard postscript sono supportati.
L'ultimo parametro codifica può assumere i seguenti valori: "MacRomanEncoding", "MacExpertEncoding", "WinAnsiEncoding", e "NULL". "NULL" rappresenta la codifica incorporata del font.
Vedere il manuale di ClibPDF per maggiori informazioni, specialmente su come supportare font asiatici.
(PHP 3>= 3.0.8, PHP 4 , PHP 5)
cpdf_set_horiz_scaling -- Imposta il fattore di scala orizzontale del testoLa funzione cpdf_set_horiz_scaling() imposta il fattore di scala orizzontale a scala percento.
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().
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().
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.
La funzione cpdf_set_subject() imposta il soggetto del documento pdf.
Vedere anche cpdf_set_title(), cpdf_set_creator() e cpdf_set_keywords().
La funzione cpdf_set_text_matrix() imposta una matrice che descrive una trasformazione applicata sul font corrente.
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().
The cpdf_set_text_rendering() function determines how text is rendered.
The possible values for mode are 0=fill text, 1=stroke text, 2=fill and stroke text, 3=invisible, 4=fill text and add it to clipping path, 5=stroke text and add it to clipping path, 6=fill and stroke text and add it to clipping path, 7=add it to clipping path.
The cpdf_set_text_rise() function sets the text rising to value units.
La funzione cpdf_set_title() imposta il titolo di un documento pdf.
Vedere anche cpdf_set_subject(), cpdf_set_creator() e cpdf_set_keywords().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione cpdf_set_word_spacing() imposta la spaziatura fra parole.
Vedere cpdf_set_char_spacing() e cpdf_set_leading().
The cpdf_setdash() function set the dash pattern white white units and black black units. If both are 0 a solid line is set.
The cpdf_setflat() function set the flatness to a value between 0 and 100.
La funzione cpdf_setgray_fill() imposta il valore corrente di grigio come riempimento del path.
Vedere anche cpdf_setrgbcolor_fill().
The cpdf_setgray_stroke() function sets the current drawing color to the given gray value.
See also cpdf_setrgbcolor_stroke().
(PHP 3>= 3.0.8, PHP 4 , PHP 5)
cpdf_setgray -- Imposta il grigio come colore per il disegno e il riempimentoLa funzione cpdf_setgray() imposta come colore per il disegno e il riempimento il valore di grigio passato.
Vedere anche cpdf_setrgbcolor_stroke() e cpdf_setrgbcolor_fill().
The cpdf_setlinecap() function set the linecap parameter between a value of 0 and 2. 0 = butt end, 1 = round, 2 = projecting square.
The cpdf_setlinejoin() function set the linejoin parameter between a value of 0 and 2. 0 = miter, 1 = round, 2 = bevel.
La funzione cpdf_setlinewidth() imposta la larghezza delle linee a larghezza.
The cpdf_setmiterlimit() function set the miter limit to a value greater or equal than 1.
The cpdf_setrgbcolor_fill() function sets the current rgb color value to fill a path.
See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor().
The cpdf_setrgbcolor_stroke() function sets the current drawing color to the given rgb color value.
See also cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().
(PHP 3>= 3.0.8, PHP 4 , PHP 5)
cpdf_setrgbcolor -- Imposta il valore del colore rgb come colore per il disegno e il riempimentoLa funzione cpdf_setrgbcolor() imposta il colore corrente per il disegno e il riempimento al valore del colore rgb dato.
Vedere anche cpdf_setrgbcolor_stroke() e cpdf_setrgbcolor_fill().
The cpdf_show_xy() function outputs the string text at position with coordinates (x-coor, y-coor).
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().
La funzione cpdf_show() scrive la stringa in testo alla posizione corrente.
Vedere anche cpdf_text(), cpdf_begin_text() e cpdf_end_text().
(PHP 3>= 3.0.8, PHP 4 , PHP 5)
cpdf_stringwidth -- Restituisce la larghezza del testo nel font correnteLa funzione cpdf_stringwidth() restituisce la larghezza della stringa in testo. Richiede che un font sia settato in precedenza.
Vedere anche cpdf_set_font().
La funzione cpdf_stroke() disegna una linea lungo il path corrente.
Vedere anche cpdf_closepath() e cpdf_closepath_stroke().
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().
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.
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.
Maggiori informazioni riguardo CrackLib possono essere trovate, insieme alla libreria, a http://www.crypticide.org/users/alecm/.
Per potere utilizzare queste funzioni, occorre compilare il PHP con il supporto per Crack utilizzando --with-crack[=DIR] option.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Opzioni di configurazione per Crack
Nome | Default | Modificabile |
---|---|---|
crack.default_dictionary | NULL | PHP_INI_SYSTEM |
Questo esempio mostra come aprire un dizionario di CrackLib, testare una determinata password, recuperare ogni messaggio diagnostico e chiudere il dizionario.
Esempio 1. Esempio di CrackLib
|
Nota: Se crack_check() restituisce TRUE, crack_getlastmessage() restituirà 'password forte'.
Restituisce TRUE se password è forte, altrimenti FALSE.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
crack_check() effettua un controllo nascosto della password data nel dizionario specificato. Se dizionario non è specificato viene utilizzato l'ultimo dizionario aperto.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
crack_closedict() chiude l'identificatore del dizionario specificato. Se dizionario non è specificato, verrà chiuso il dizionario corrente.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
crack_getlastmessage() restituisce il messaggio dell'ultimo controllo nascosto.
Restituisce un identificatore di risorsa dizionario in caso di successo, o FALSE in caso di fallimento.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
crack_opendict() apre il dizionario specificato di CrackLib per usarlo con crack_check().
Nota: Può essere aperto solo un dizionario alla volta.
Vedere anche: crack_check() e crack_closedict().
PHP supporta libcurl, una libreria creata da Daniel Stenberg, che permette di collegarsi e comunicare con parecchi tipi di server e con parecchi tipi di protocolli. Libcurl al momento supporta i protocolli http, https, ftp, gopher, telnet, dict, file, e ldap. libcurl supporta anche i certificati HTTPS, HTTP POST, HTTP PUT, l'upload via FTP (questo può essere ottenuto anche con l'estensione ftp di PHP), upload attraverso una form HTTP, proxy, cookie e autenticazione con utente e password.
Queste funzioni sono state aggiunte in PHP 4.0.2.
Per utilizzare le funzioni CURL occorre installare il pacchetto CURL. PHP richiede che si usi CURL 7.0.2-beta o successivi. PHP non funzionerà con alcuna versione di CURL antecedente alla 7.0.2-beta. Dalla versione 4.2.3 di PHP è necessario usare CURL versione 7.9.0 o successiva. Con PHP 4.3.0 occorre avere CURL 7.9.8 o successive. PHP 5.0.0 molto probabilmente richiederà CURL 7.10.5 o successiva.
Al fine di utilizzare il supporto CURL occorre anche compilare PHP con --with-curl[=DIR] dove DIR è il percorso della directory che contiene le directory lib e include. Nella directory "include" ci dovrebbe essere una cartella chiamata "curl" che dovrebbe contenere i file easy.h e curl.h. Ci dovrebbe essere un file chiamato libcurl.a nella directory "lib". A cominciare da PHP 4.3.0 si può configurare PHP all'uso di CURL per gli URL stream --with-curlwrappers.
Nota agli utenti Win32: Per abilitare questo modulo in ambiente Windows, occorre copiare libeay32.dll e ssleay32.dll dalla cartella delle DLL del pacchetto PHP/Win32 nella cartella SYSTEM32 della propria macchina Windows. (Es: C:\WINNT\SYSTEM32 o C:\WINDOWS\SYSTEM)
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Una volta compilato PHP con supporto CURL, si possono usare le funzioni CURL. L'idea di fondo che sta dietro le funzioni CURL è: si inizializza una sessione CURL usando curl_init(), si impostano le opzioni per il trasferimento tramite curl_setopt(), si esegue la sessione usando curl_exec() e quindi si termina la sessione con curl_close(). Qui di seguito si trova un esempio che fa uso delle funzioni CURL per scaricare la homepage del sito example.com e metterla in un file:
Questa funzione chiude una sessione CURL e libera tutte le risorse. L'handle CURL ch viene anch'esso eliminato.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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().
(PHP 4 >= 4.0.3, PHP 5)
curl_error -- Restituisce una stringa contenente l'ultimo errore relativo alla sessione correnteLa funzione restituisce un messaggio di errore testuale per l'ultima operazione cURL eseguita sulla risorsa ch, oppure '' (una stringa vuota) se non vi sono errori.
Vedere anche curl_errno().
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().
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() 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().
Vedere anche: curl_close() e curl_setopt().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init(), curl_init() e curl_multi_remove_handle().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init() e curl_close().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init() e curl_exec().
(PHP 5)
curl_multi_getcontent -- Restituisce il contenuto di un handle cURL se è impostato CURLOPT_RETURNTRANSFERAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_init() e curl_multi_close().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init(), curl_init() e curl_multi_add_handle().
(PHP 5)
curl_multi_select -- Restituisce tutti i socket associati alla estensione cURL che possono essere "selected"Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init().
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.
Queste funzione sono disponibili solo se l'interprete è stato compilato con l'opzione --with-cybercash=[DIR].
A partire da PHP 4.3.0 questo modulo è stato spostato, ed ora è reperibile in PECL.
Se si hanno dubbi sullo stato di CyberCash vedere CyberCash Faq In breve, CyberCash è stato acquisito da VeriSign e, sebbene il servizio CyberCash continui ad esistere, VeriSign incoraggia gli utenti a spostarsi. Vedere la faq precedente e PECL per dettagli.
La funzione restituisce un array associativo con gli elementi "errcode" e, se "errcode" è FALSE, "outbuff" (stringa), "outLth" (long) and "macbuff" (stringa).
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Questo modulo non è disponibile su piattaforme Windows.
Questo modulo è disponibile soltanto se PHP è stato configurato con l'opzione --with-cyrus .
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Le funzioni fornite da questa estensione controllano se un carattere o una stringa rientrano in una classe di caratteri in accordo con l'ambiente corrente (vedere anche setlocale()).
Quando vengono chiamate con un numero intero come argomento queste funzioni si comportano esattamente come il loro equivalente in C presente in ctype.h.
Quando vengono chiamate con una stringa come argomento controlleranno ogni carattere della stringa e ritorneranno TRUE se ogni carattere della stringa soddisfa il criterio richiesto. Quando sono eseguite con una stringa vuota il risultato è sempre TRUE
Passare qualsiasi cosa eccetto una stringa o un numero intero restituirà immediatamenente FALSE.
A partire da PHP 4.2.0 queste funzioni sono abilitate di default. Per le versioni più vecchie bisogna configurare e compilare PHP con --enable-ctype.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Nota: Il supporto per CType pre-compilato è disponibile a partire dalla versione 4.3.0.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Restituisce TRUE se ogni carattere di testo è una lettera o una cifra, FALSE in caso contrario. Nell'ambiente standard del C le lettere sono solamente [A-Za-z]. La funzione è equivalente a (ctype_alpha($text) || ctype_digit($text)).
Vedere anche ctype_alpha(), ctype_digit() e setlocale().
Restituisce TRUE se ogni carattere di testo è una lettera dell'ambiente corrente, FALSE in caso contrario. Nell'ambiente standard del C le lettere sono solo [A-Za-z] e ctype_alpha() è equivalente a (ctype_upper($text) || ctype_lower($text)), ma altri linguaggi hanno lettere che non sono considerate nè maiuscole nè minuscole.
Vedere anche ctype_upper(), ctype_lower() e setlocale().
Restituisce TRUE se ogni carattere di testo ha una speciale funzione di controllo, FALSE in caso contrario. I caratteri di controllo sono per esempio line feed (avanza di una riga), tab, esc.
Restituisce TRUE se ogni carattere di testo è una cifra decimale, FALSE in caso contrario.
Vedere anche ctype_alnum() e ctype_xdigit().
Restituisce TRUE se ogni carattere di testo è stampabile e crea un output realmente visibile (senza spazi bianchi), FALSE in caso contrario.
Vedere anche ctype_alnum(), ctype_print() e ctype_punct().
Restituisce TRUE se ogni carattere di testo è una lettera minuscola nell'ambiente corrente.
Vedere anche ctype_alpha() e ctype_upper().
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().
(PHP 4 >= 4.0.4, PHP 5)
ctype_punct -- Controlla ogni carattere stampabile che non è uno spazio o un carattere alfanumericoRestituisce TRUE se ogni carattere di testo è stampabile, ma non è nè una lettera nè; una cifra nè uno spazio, FALSE in caso contrario.
Vedere anche ctype_cntrl(), ctype_graph() e ctype_punct().
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).
Restituisce TRUE se ogni carattere di testo è una lettera maiuscola nell'ambiente corrente.
Vedere anche ctype_alpha() e ctype_lower().
(PHP 4 >= 4.0.4, PHP 5)
ctype_xdigit -- Controlla i caratteri che rappresentano una cifra esadecimaleRestituisce TRUE se ogni carattere di testo è una 'cifra' esadecimale, cioè una cifra decimale o un carattere fra [A-Fa-f] , FALSE in caso contrario.
Vedere anche ctype_digit().
These functions build the foundation for accessing Berkeley DB style databases.
This is a general abstraction layer for several file-based databases. As such, functionality is limited to a common subset of features supported by modern databases such as Sleepycat Software's DB2. (This is not to be confused with IBM's DB2 software, which is supported through the ODBC functions.)
The behaviour of various aspects depends on the implementation of the underlying database. Functions such as dba_optimize() and dba_sync() will do what they promise for one database and will do nothing for others. You have to download and install supported dba-Handlers.
Tabella 1. List of DBA handlers
Handler | Notes |
---|---|
dbm | Dbm is the oldest (original) type of Berkeley DB style databases. You should avoid it, if possible. We do not support the compatibility functions built into DB2 and gdbm, because they are only compatible on the source code level, but cannot handle the original dbm format. |
ndbm | Ndbm is a newer type and more flexible than dbm. It still has most of the arbitrary limits of dbm (therefore it is deprecated). |
gdbm | Gdbm is the GNU database manager. |
db2 | DB2 is Sleepycat Software's DB2. It is described as "a programmatic toolkit that provides high-performance built-in database support for both standalone and client/server applications. |
db3 | DB3 is Sleepycat Software's DB3. |
db4 | DB4 is Sleepycat Software's DB4. This is available since PHP 4.3.2. |
cdb | Cdb is "a fast, reliable, lightweight package for creating and reading constant databases." It is from the author of qmail and can be found at http://cr.yp.to/cdb.html. Since it is constant, we support only reading operations. And since PHP 4.3.0 we support writing (not updating) through the internal cdb library. |
cdb_make | Since PHP 4.3.0 we support creation (not updating) of cdb files when the bundled cdb library is used. |
flatfile | This is available since PHP 4.3.0 for compatibility with the deprecated dbm extension only and should be avoided. However you may use this where files were created in this format. That happens when configure could not find any external library. |
inifile | This is available since PHP 4.3.3 to be able to modify php.ini files from within PHP scripts. When working with ini files you can pass arrays of the form array(0=>group,1=>value_name) or strings of the form "[group]value_name" where group is optional. As the functions dba_firstkey() and dba_nextkey() return string representations of the key there is a new function dba_key_split() available since PHP 5 which allows to convert the string keys into array keys without loosing FALSE. |
qdbm | This is available since PHP 5.0.0. The qdbm library can be loaded from http://qdbm.sourceforge.net. |
When invoking the dba_open() or dba_popen() functions, one of the handler names must be supplied as an argument. The actually available list of handlers is displayed by invoking phpinfo() or dba_handlers().
By using the --enable-dba=shared configuration option you can build a dynamic loadable module to enable PHP for basic support of dbm-style databases. You also have to add support for at least one of the following handlers by specifying the --with-XXXX configure switch to your PHP configure line.
Avvertimento |
After configuring and compiling PHP you must execute the following test from commandline: php run-tests.php ext/dba. This shows whether your combination of handlers works. Most problematic are dbm and ndbm which conflict with many installations. The reason for this is that on several systems these libraries are part of more than one other library. The configuration test only prevents you from configuring malfaunctioning single handlers but not combinations. |
Tabella 2. Supported DBA handlers
Handler | Configure Switch |
---|---|
dbm |
To enable support for dbm add
--with-dbm[=DIR].
|
ndbm |
To enable support for ndbm add
--with-ndbm[=DIR].
|
gdbm | To enable support for gdbm add --with-gdbm[=DIR]. |
db2 |
To enable support for db2 add
--with-db2[=DIR].
|
db3 |
To enable support for db3 add
--with-db3[=DIR].
|
db4 |
To enable support for db4 add
--with-db4[=DIR].
|
cdb |
To enable support for cdb add
--with-cdb[=DIR].
|
flatfile |
To enable support for flatfile add
--with-flatfile.
|
inifile |
To enable support for inifile add
--with-inifile.
|
qdbm |
To enable support for qdbm add
--with-qdbm[=DIR].
|
Nota: Up to PHP 4.3.0 you are able to add both db2 and db3 handler but only one of them can be used internally. That means that you cannot have both file formats. Starting with PHP 5.0.0 there is a configuration check avoid such missconfigurations.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
The functions dba_open() and dba_popen() return a handle to the specified database file to access which is used by all other dba-function calls.
DBA is binary safe and does not have any arbitrary limits. However, it inherits all limits set by the underlying database implementation.
All file-based databases must provide a way of setting the file mode of a new created database, if that is possible at all. The file mode is commonly passed as the fourth argument to dba_open() or dba_popen().
You can access all entries of a database in a linear way by using the dba_firstkey() and dba_nextkey() functions. You may not change the database while traversing it.
Esempio 2. Traversing a database
|
dba_close() closes the established database and frees all resources specified by handle.
handle is a database handle returned by dba_open().
dba_close() does not return any value.
See also dba_open(), and dba_popen()
dba_delete() deletes the entry specified by key from the database specified with handle.
key is the key of the entry which is deleted.
handle is a database handle returned by dba_open().
dba_delete() returns TRUE or FALSE, if the entry is deleted or not deleted, respectively.
See also dba_exists(), dba_fetch(), dba_insert(), and dba_replace().
dba_exists() checks whether the specified key exists in the database specified by handle.
Key is the key the check is performed for.
Handle is a database handle returned by dba_open().
dba_exists() returns TRUE or FALSE, if the key is found or not found, respectively.
See also: dba_fetch(), dba_delete(), dba_insert(), and dba_replace().
dba_fetch() fetches the data specified by key from the database specified with handle.
Key is the key the data is specified by.
Skip is the number of key-value pairs to ignore when using cdb databases. This value is ignored for all other databases which do not support multiple keys with the same name.
Handle is a database handle returned by dba_open().
dba_fetch() returns the associated string or FALSE, if the key/data pair is found or not found, respectively.
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() 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() 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() 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() 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() returns an associative array with all open database files. This array is in the form: resourceid=>filename.
dba_nextkey() returns the next key of the database specified by handle and advances the internal key pointer.
handle is a database handle returned by dba_open().
dba_nextkey() returns the key or FALSE depending on whether it succeeds or fails, respectively.
See also dba_firstkey(), dba_key_split() and example 2 in the DBA examples
dba_open() establishes a database instance for path with mode using handler.
path is commonly a regular path in your filesystem.
mode is "r" for read access, "w" for read/write access to an already existing database, "c" for read/write access and database creation if it doesn't currently exist, and "n" for create, truncate and read/write access. Additional you can set the 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 open mode = "rl" mode = "rlt" mode = "wl" mode = "wlt" mode = "rd" mode = "rdt" mode = "wd" mode = "wdt" not open ok ok ok ok ok ok ok ok mode = "rl" ok ok wait false illegal illegal illegal illegal mode = "wl" wait false wait false illegal illegal illegal illegal mode = "rd" illegal illegal illegal illegal ok ok wait false mode = "wd" illegal illegal illegal illegal wait false wait false
ok: the second call will be successfull. wait: the second call waits until dba_close() is called for the first. false: the second call returns false. illegal: you must not mix "l" and "d" modifiers for mode parameter.
Nota: Since PHP 4.3.0 it is possible to open database files over network connection. However in cases a socket connection will be used (as with http or ftp) the connection will be locked instead of the resource itself. This is important to know since in such cases locking is simply ignored on the resource and other solutions have to be found.
Nota: Locking and the mode modifiers "l", "d", "-" and "t" were added in PHP 4.3.0. In PHP versions before PHP 4.3.0 you must use semaphores to guard against 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() optimizes the underlying database specified by handle.
handle is a database handle returned by dba_open().
dba_optimize() returns TRUE or FALSE, if the optimization succeeds or fails, respectively.
See also: dba_sync()
dba_popen() establishes a persistent database instance for path with mode using handler.
path is commonly a regular path in your filesystem.
mode is "r" for read access, "w" for read/write access to an already existing database, "c" for read/write access and database creation if it doesn't currently exist, and "n" for create, truncate and read/write access.
handler is the name of the handler which shall be used for accessing path. It is passed all optional parameters given to dba_popen() and can act on behalf of them.
dba_popen() returns a positive handle or FALSE, in the case the open is successful or fails, respectively.
See also: dba_open() dba_close()
dba_replace() replaces or inserts the entry described with key and value into the database specified by handle.
key is the key of the entry to be inserted.
value is the value to be inserted.
handle is a database handle returned by dba_open().
dba_replace() returns TRUE or FALSE, depending on whether it succeeds of fails, respectively.
See also: dba_exists(), dba_delete(), dba_fetch(), and dba_insert().
dba_sync() synchronizes the database specified by handle. This will probably trigger a physical write to disk, if supported.
handle is a database handle returned by dba_open().
dba_sync() returns TRUE or FALSE, if the synchronization succeeds or fails, respectively.
See also: dba_optimize()
Queste funzioni ti permettono di scaricare la data e l'orario dal server dove gira il PHP. Puoi usare queste funzioni per formattare l'output delle date e degli orari in diversi modi.
Nota: Ricordati che queste funzioni dipendono dai settaggi locali del tuo server. Considera specialmente l'ora legale e gli anni bisestili.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Restituisce TRUE se la data inserita è valida; altrimenti restituisce FALSE. Controlla la validità di una data formata dagli argomenti. Una data è considerata valida se:
anno è compreso tra 1 e 32767
mese è compreso tra 1 e 12
Giorno è compreso tra il numero dei giorni possibile per il mese dato. Gli anno(i) bisestili sono presi in considerazione.
Guarda anche mktime() e strtotime().
Restituisce una stringa formattata in accordo con il formato della stringa usato nell' intero timestamp o nell'attuale orario locale se timestamp non è assegnato.
Nota: Il valido intervallo del timestamp è abitualmente da Fri, 13 Dec 1901 20:45:54 GMT a Tue, 19 Jan 2038 03:14:07 GMT. (Queste date corrispondono al valore minimo e al massimo per un intero segnato a 32-bit.)
Per generare un timestamp da una stringa rappresentante la data, devi sapere usare strtotime(). In aggiunta, dei databases hanno funzioni che convertono i loro formati di data in timestamps (come la funzione di MySQL, UNIX_TIMESTAMP).
I seguenti caratteri sono utilizzati nella stringa formato:
a - "am" o "pm"
A - "AM" o "PM"
B - Swatch Internet time
d - giorno del mese, 2 cifre senza tralasciare gli zero; i.e. "01" a "31"
D - giorno della settimana, testuale, 3 lettere; i.e. "Fri"
F - mese, testuale, long; i.e. "January"
g - ora, formato a 12-ore senza eventuali zero; i.e. "1" a "12"
G - ora, formato a 24-ore senza eventuali zero; i.e. "0" a "23"
h - ora, formato a 12-ore; i.e. "01" a "12"
H - ora, formato a 24-ore; i.e. "00" a "23"
i - minuti; i.e. "00" a "59"
I (i grande) - "1" se c'è l'ora legale, "0" altrimenti.
j - giorno del mese senza eventuali zero; i.e. "1" a "31"
l ('L' piccola) - giorno della settimana, testuale, long; i.e. "Friday"
L - valore booleano per stabilire se è un anno bisestile; i.e. "0" o "1"
m - mese; i.e. "01" a "12"
M - mese, testuale, 3 lettere; i.e. "Jan"
n - mese senza eventuali zero; i.e. "1" a "12"
O - Differenza in ore dal fuso orario Greenwich; i.e. "+0200"
r - Data formattata RFC 822; i.e. "Thu, 21 Dec 2000 16:01:07 +0200" (aggiunto nel PHP 4.0.4)
s - secondi; i.e. "00" a "59"
S - Suffisso ordinale Inglese per i giorni del mese, 2 caratteri; i.e. "th", "nd"
t - numero di giorni del mese dato; i.e. "28" a "31"
T - Fuso orario di questo computer; i.e. "MDT"
U - secondi dall'epoca since the epoch
w - giorno della settimana, numerico, i.e. "0" (Domenica) a "6" (Sabato)
W - ISO-8601 Numero della settimana dell'anno, le settimane iniziano il lunedì (aggiunto in PHP 4.1.0) (Sabato)
Y - anno, 4 cifre; i.e. "1999"
y - anno, 2 cifre; i.e. "99"
z - giorno dell'anno; i.e. "0" a "365"
Z - Fuso orario in secondi (i.e. "-43200" a "43200"). Il fuso orario ad ovest dell'UTC è sempre negativo, e per quelli ad est è sempre positivo.
Puoi utilizzare un carattere utilizzabile nella stringa del formato come carattere normale facendolo semplicemente precedere dal carattere di escape, il backslash. Se il carattere con un backslash è ancora una sequenza speciale, devi inserire di nuovo il carattere di escape per il backslash.
È possibile usare date() e mktime() assieme per cercare delle date nel futuro o nel passato.
Esempio 3. Esempio di date() e mktime()
|
Nota: Questo può essere più affidabile della semplice addizione e sottrazione del numero di secondi in un giorno o mese a un timestamp a causa del daylight savings time.
Alcuni esempi della formattazione di date(). Nota che puoi scrivere qualsiasi altro carattere senza escape, il quale attualmente non dovrebbe produrre risultati indesiderati, ma altri caratteri potrebbero essere assegnati come caratteri della stringa di formattazione nelle prossime versioni del PHP. Quando si utilizza il carattere di escape, assicurati di usare un singolo apice per prevenire che caratteri come \n facciano iniziare una nuova linea.
Esempio 4. Formattazione con date()
|
Per formattare le date in lingue diverse dall'inglese, dovresti usare le funzioni setlocale() e strftime().
Guarda anche getlastmod(), gmdate(), mktime(), strftime() e time().
Restituisce un array associativo contenente le informazioni sulla data del timestamp, o dell'attuale orario locale se non è stato assegnato timestamp, con i seguenti elementi di array:
"seconds" - secondi
"minutes" - minuti
"hours" - ore
"mday" - giorno del mese
"wday" - giorno della settimana, numerico : da 0 come Domenica a 6 come Sabato
"mon" - mese, numerico
"year" - anno, numerico
"yday" - giorno dell'anno, numerico; i.e. "299"
"weekday" - giorno della settimana, testuale, per intero; i.e. "Friday"
"month" - mese, testuale, per intero; i.e. "January"
Questa è un'interfaccia di gettimeofday(2). Restituisce un array associativo contenente i dati restituiti dalla chiamata al sistema.
"sec" - secondi
"usec" - microsecondi
"minuteswest" - minuti ovest di Greenwich
"dsttime" - tipo di correzione dell'ora legale
Identica alla funzione date() eccetto per il fatto che l'orario restituito è del Greenwich Mean Time (GMT). Per esempio, quando si è in Finlandia (GMT +0200), la prima linea sotto scrive "Jan 01 1998 00:00:00", mentre la seconda scrive "Dec 31 1997 22:00:00".
Guarda anche date(), mktime(), gmmktime() e strftime().
Identica alla funzione mktime() eccetto per il paramentro passato, che rappresenta una data GMT.
(PHP 3>= 3.0.12, PHP 4 , PHP 5)
gmstrftime -- Formatta una data/ora GMT/UTC secondo i parametri localiSi comporta allo stesso modo della funzione strftime() eccetto che l'orario restituito è del Greenwich Mean Time (GMT). Ad esempio, quando si è nell' Eastern Standard Time (GMT -0500), la prima linea sotto scrive "Dec 31 1998 20:00:00", mentre la seconda scrive "Jan 01 1999 01:00:00".
Guarda anche strftime().
Returns a 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 character | Description |
---|---|
B | Swatch Beat/Internet Time |
d | Day of the month |
h | Hour (12 hour format) |
H | Hour (24 hour format) |
i | Minutes |
I | returns 1 if DST is activated, 0 otherwise |
L | returns 1 for leap year, 0 otherwise |
m | Month number |
s | Seconds |
t | Days in current month |
U | Seconds since the Unix Epoch - January 1 1970 00:00:00 GMT - this is the same as time() |
w | Day of the week (0 on Sunday) |
W | ISO-8601 week number of year, weeks starting on Monday |
y | Year (1 or 2 digits - check note below) |
Y | Year (4 digits) |
z | Day of the year |
Z | Timezone offset in seconds |
Nota: As idate() returns always an integer and as they can't start with a "0", idate() may return less digits then you would expect. See the example below:
La funzione localtime() restituisce un array identico a quello della struttura della chimata della funzione di C. Il primo argomento per localtime() è il timestamp, se non esiste viene assegnato di default l'orario attuale. Il secondo argomento di localtime() è is_associative, se questo è settato a 0 o non sostituito l'array restituirà un regolare array numerico indicizzato. Se l'argomento è settato a 1, localtime() è un array associativo contenente tutti gli elementi differenti della struttura restituita dalla funzione chiamata localtime di C. Il nome delle differenti chiavi dell'array associativo sono le seguenti:
"tm_sec" - secondi
"tm_min" - minuti
"tm_hour" - ora
"tm_mday" - giorno del mese
"tm_mon" - mese dell'anno, iniziando con 0 per Gennaio
"tm_year" - Anni dal 1900
"tm_wday" - Giorno della settimana
"tm_yday" - Giorno dell'anno
"tm_isdst" - Se l'ora legale è effettiva
Restituisce la stringa "msec sec" dove sec è l'attuale orario misurato nel numero di secondi dalla Unix Epoch (0:00:00 January 1, 1970 GMT), e msec è la parte in microsecondi. Questa funzione è disponibile solo su sistemi operativi che supportano la chiamata di sistema gettimeofday().
Entrambi le parti della stringa sono restituite in unità di secondi.
Esempio 1. Esempio di microtime()
|
Vedere anche time().
Attenzione: Nota lo strano ordine degli argomenti, che differiscono dal normale ordine degli argomenti in una normale chiamata UNIX mktime() e che non si presta bene a far comparire i parametri da destra a sinistra (guarda sotto). E' un comune errore la confusione di questi argomenti in uno script.
Restituisce la Unix timestamp corrispondente all'argomento dato. Questa timestamp è un intero lungo contenente il numero di secondi tra la Unix Epoch (January 1 1970) e la data e orario specificati.
Gli argomenti possono essere omessi nell'ordine da destra a sinistra; degli argomenti omessi saranno impostati con l'attuale valore accordandolo alla data e orario locale.
is_dst può essere impostato su 1 se l'orario è nell'ora legale, 0 altrimenti, o -1 (di default) se è sconosciuta la presenza dell'ora legale o meno. Se è sconosciuto, il PHP proverà ad impostarlo da se. Questo può causare un risultato non aspettato (ma non sbagliato).
Nota: is_dst è stato aggiunto nella verisone 3.0.10.
mktime() è usata per fare calcoli tra date e validazioni, come può calcolare automaticamente il corretto valore per un valore fuori dall'intervallo valido. Per esempio, ognuna delle seguenti linee produce la stringa "Jan-01-1998".
L'ultimo giorno del mese dato può essere espresso come il giorno "0" del mese successivo, non come il giorno -1. Entrami i seguenti esempi produrranno la stringa "L'ultimo giorno di Feb 2000 è: 29".
Date con anno, mese e giorno uguali a 0 non sono considerate valide (altrimenti saranno considerate come 30.11.1999, quando hanno uno strano behavior).
(PHP 3, PHP 4 , PHP 5)
strftime -- Formatta una data/orario locale accordandola/o alle impostazioni locali according to locale settingsRestituisce una stringa formattata in accordo con la stringa del formato data usando il parametro dato timestamp o l'attuale orario locale se non è stato dato il timestamp. I nomi di mesi e giorni della settimana e le altre stringhe dipendenti dalla lingua rispettano le attuali impostazioni locali con setlocale().
Le seguenti sequenze di caratteri sono utilizzate nella stringa del formato:
%a - Nome del giorno della settimana abbreviato in accordo con i parametri locali
%A - Nome completo del giorno della settimana in accordo con i parametri locali
%b - Nome del mese abbreviato in accordo con i parametri locali
%B - Nome completo del mese in accordo con i parametri locali
%c - Rappresentazione preferita di data e orario per le attuali impostazioni locali
%C - numero del secolo (l'anno diviso 100 e troncato in un intero, intervallo tra 00 e 99)
%d - giorno del mese come numero decimale (intervallo tra 01 e 31)
%D - come %m/%d/%y
%e - giorno del mese come numero decimale, un singolo carattere è preceduto da uno spapzio (intervallo tra ' 1' e '31')
%g - come %G, ma senza il secolo.
%G - L'anno a 4 cifre corrispondente al numero di setitmana ISO (vedi %V). Questa ha lo stesso formato e valore di %Y, eccetto che se il numero di settimana ISO appartiene al precedente o prossimo anno, è invece utilizzato l'anno attuale.
%h - come %b
%H - ora come numero decimale usando il sistema a 24 ore (intervallo tra 00 e 23)
%I - ora come numero decimale usando il sistema a 12 ore (intervallo tra 01 e 12)
%j - giorno dell'anno come numero decimale (intervallo tra 001 e 366)
%m - mese come numero decimale (intervallo tra 01 e 12)
%M - minuto come numero decimale
%n - carattere di nuova linea
%p - entrambi `am' o `pm' accordati a un valore di tempo dato, o alle stringhe corrispondenti per le impostazioni locali
%r - orario in notazione a.m. e p.m
%R - orario nella notazione a 24 ore
%S - secondi come numero decimale
%t - Carattere di tabella
%T - orario attuale, identico a %H:%M:%S
%u - giorno della settimana come numero decimale [1,7], dove 1 rappresenta il Lunedì
Avvertimento |
Sun Solaris sembra far iniziare con la Domenica a come 1 sebbe la ISO 9889:1999 (l'attuale standard di C) specifica chiaramente che dovrebbe iniziare dal Lunedì. |
%U - numero della settimana dell'anno in corso come numero decimale, iniziando dalla prima Domenica come primo giorno della prima settimana
%V - Il numero di settimana ISO 8601:1988 dell'anno attuale come numero decimale, intervallo tra 01 e 53, dove la settimana 1 è la prima settimana che ha almeno 4 giorni dell'attuale anno, e con il Lunedì come primo giorno della settimana. (Utilizza %G o %g per l'anno componente che corrisponde al numero di settimana per il timestamp specificato.)
%W - numero della settimana dell'attuale anno come numero decimale, partendo con il primo Lunedì come primo giorno della prima settimana
%w - giorno della settimana come decimale, dove la Domenica è 0
%x - visualizzazione della data preferita dalle impostazioni del sistema locale senza orario
%X - visualizzazione dell'orario preferito dalle impostazioni del sistema locale senza data
%y - anno come numero decimale senza secolo (intervallo tra 00 e 99)
%Y - anno come numero decimale incluso il secolo
%Z - fuso orario o abbreviazione
%% - il carattere `%'
Nota: Non tutte le sequenze di caratteri potrebbero essere supportate dalla tua libreria locale di C, in tal caso la funzione strftime() non sarà supportata dal PHP. Questo significa che %T e %D non funzioneranno sotto Windows.
Guarda anche setlocale() e mktime() e le specifiche dell' Open Group per strftime().
(PHP 3>= 3.0.12, PHP 4 , PHP 5)
strtotime -- Analizza le descrizioni testuali di datetime in Inglese nell'UNIX timestampLa funzione aspetta di avere una stringa contenente un formato di data in Inglese e proverà a passare questo formato all'UNIX timestamp relativo al timestamp dato in now, o l'attuale orario se non è stato passato il parametro. Sul fallimento, è restituito -1.
Perché strtotime() si comporti in accordo con la sintassi della data GNU, dai uno sguardo alla pagina del manuale GNU intitolata Date Input Formats. Descrive se c'è una sinstassi valida per il parametro time.
Esempio 1. strtotime() - esempi
|
Nota: L'intervallo valido di un timestamp è normalmente da Fri, 13 Dec 1901 20:45:54 GMT a Tue, 19 Jan 2038 03:14:07 GMT. (Queste sono le date ce corrispondono al minimo e al massimo valore per un intero segnato a 32 bit.)
Restituisce l'attuale data e orario misurata in numero di secondi dalla Unix Epoch (January 1 1970 00:00:00 GMT).
Guarda anche date().
Queste funzioni consentono di accedere ai record memorizzati nei database in formato dBase (dbf).
Non è previsto il supporto per indici o campi memo. Manca anche il supporto per il locking. E' probabile che due processi concorrenti che modifichino lo stesso database, finiscano con il rovinare il Database.
I files dBase sono semplici files sequenziali o records a lunghezza fissa. I record sono aggiunti (append) alla fine del file e quelli cancellati sono conservati fino alla chiamata della funzione dbase_pack().
Si raccomanda di non usare i files dBase come database di lavoro. Scegliere piuttosto qualsiasi reale SQL server; MySQL o Postgres sono scelte comuni con PHP. Il supporto dBase è presente per permettervi di importare ed esportare dati da e verso il vostro web database, perchè il formato del file è comunemente ben interpretato dai fogli elettronici e dagli organizers di Windows.
Allo scopo di abilitare le librerie dbase fornite e di usare queste funzioni, si deve compilare PHP con l'opzione --enable-dbase .
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Aggiunge i dati nel record al database. Se il numero di items nel record non è uguale al numero di campi nel database, l'operazione fallirà e sarà restituito FALSE.
Chiude il database associato con il dbase_identifier.
dBase_create()crea un database dBase nel filefilename con i campifields
Il parametro fields è un array di arrays, ciascun array descrive il formato di un campo nel database. Ogni campo consiste di un nome, un carattere che indica il tipo di campo, una lunghezza, e una precisione.
I tipi di campo disponibili sono:
Boolean. Questi non hanno una lunghezza o una precisione.
Memo. (Nota che non sono supportati da PHP.) Questi non hanno una lunghezza o una precisione.
Date (memorizzate nel formato YYYYMMDD). Questi non hanno una lunghezza o una precisione.
Number. Questi hanno sia una lunghezza sia una precisione (il numero di decimali).
String.
Se il database è creato con successo, viene restituito un dbase_identifier, altrimenti viene restituito FALSE.
Esempio 1. Creare un file di database dBase
|
Marca il record da cancellare dal database. Per rimuovere il record dal database, è necessario chiamare la funzione dbase_pack().
Restituisce informazioni sulla struttura delle colonne del database referenziato da dbase_identifier. Per ogni colonna del database, esiste un valore specificato in un array ad indice numerico. L'indice dell'array inizia da 0. Ogni elemento dell'array contiene un array associativo di informazioni sulle colonne. Se l'informazione dell'header dell'array non può esssere letta, viene restituito, FALSE .
Gli elementi dell'array sono:
Il nome della colonna
Il nome del tipo di colonna del dBase riconoscibile dall'utente (es. data, boolean, etc)
Il numero di bytes che la colonna può contenere
Il numero di cifre della precisione decimale della colonna
Un formato di printf() suggerito, specifico per la colonna
L'offest, in byte, della colonna dall'inizio riga
Esempio 1. Mostra le informazioni dell'header di un file di database in formato dBase
|
(PHP 3>= 3.0.4, PHP 4 , PHP 5)
dbase_get_record_with_names -- Estrae un record da un database dBase come un array associativoRestituisce i dati da record in un array associativo. L'array include anche un membro associativo chiamato 'deleted' che è settato a 1 se il record è stato marcato per la cancellazione (vedere dbase_delete_record()).
Ogni campo è convertito all'appropriato tipo PHP, Fanno eccezione:
Le date, che sono lasciate come stringhe.
Gli interi che avrebbero causato un overflow (> 32 bits) sono restituiti come stringhe.
Restituisce i dati da record in un array. L'array è indicizzato partendo da 0, e include un membro associativo chiamato 'deleted' che è settato a 1 se il record è stato marcato per la cancellazione (vedere dbase_delete_record()).
Ogni campo è convertito all'appropriato tipo PHP, Fanno eccezione:
Le date, che sono lasciate come stringhe.
Gli interi che avrebbero causato un overflow (> 32 bits) sono restituiti come stringhe.
Restituisce il numero di campi (colonne) nel databaase specificato. I numeri dei campi sono compresi tra 0 e dbase_numfields($db)-1, mentre i numeri dei records sono compresi tra 1 e dbase_numrecords($db).
Restituisce il numero di records (righe) nel database specificato. I numeri dei records sono compresi tra 1 e dbase_numrecords($db), mentre i numeri dei campi sono compresi tra 0 e dbase_numfields($db)-1.
Restituisce un dbase_identifier per il database aperto, o FALSE se il database non può essere aperto
I parametri flags corrispondono a quelli della system call open() (Tipicamente, "0" significa sola-lettura, "1" significa sola scrittura e "2" lettura-scrittura).
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Stabilizza il database specificato (cancellando permanentemente tutti i records marcati per la cancellazione usando dbase_delete_record()).
Sostituisce i dati associati con il record record_number con i dati nel record nel database. Se il numero di items nel record non è uguale al numero di campi nel database, l'operazione fallirà e sarà restituito FALSE.
dbase_record_number è un integer che va da 1 al numero di records nel database (come restituito da dbase_numrecords()).
Questa funzioni consentono lo storage di records memorizzati in un dbm-style database. Questo tipo di database (supportato da Berkeley DB, GDBM, e qualche libreria di sistema, così come una built-in flatfile library) memorizza coppie key/value (al contrario dei full-blown records supportati dai database relazionali).
Nota: Il supporto per dbm è deprecato e si incoraggia ad utilizzare Database (dbm-style) abstraction layer functions.
Nota: Questo modulo ` stato rimosso da PHP 5 ed inserito tra le librerie PECL.
Per utilizzare queste funzioni occorre compilare il PHP con il supporto per un database sottostante. Vedere l'elenco dei database supoprtati.
Per potere utilizzare queste funzioni occorre compilare il PHP con il supporto dbm utilizzando l'opzione --with-db. Inoltre occorre garantire il supporto per il sottostante database oppure occorre utilizzare qualche libreria di sistema.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
La funzione dbmopen() restituisce un identificatore di database che può essere utilizzato con le altre funzioni dbm.
Cancella il valore per key nel database.
Restituisce FALSE se la chiave non esisteva nel database.
Restituisce TRUE se c'è un valore associato con la key.
Restituisce il valore associato con key.
Restituisce la prima chiave nel database. Da notare che nessun ordine particolare è garantito dal momento che il database potrebbe essere stato costruito usando una hash-table, che non garantisce nessun ordine.
Aggiunge il valore al database con la chiave specificata.
Restituisce -1 se il database è stato aperto in modalità read-only (sola lettura), 0 se l'inserimento è andato a buon fine, e 1 se la chiave specificata già esiste. (Per sostituire il valore, usa dbmreplace().)
Restituisce la chiave successiva dopo key. Chiamando la funzione dbmfirstkey() seguita da successive chiamate alla funzione dbmnextkey() è possibile visionare ciascuna coppia key/value nel database DBM. Per esempio:
Il primo argomento è il nome (con il percorso completo) del file DBM da aprire e il secondo è l' open mode del file che può essere "r", "n", "c" or "w" per sola lettura, nuovo (implica lettura-scrittura, e molto probabilmente troncherà un database esistente con lo stesso nome), crea (implica lettura-scrittura, e non troncherà un database esistente con lo stesso nome) e lettura-scrittura rispettivamente.
Restituisce un identifier da passare alle altre funzioni DBM in caso di successo, o FALSE se fallisce.
Se è usato il supporto NDBM, NDBM creerà 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.
The dbx module is a database abstraction layer (db 'X', where 'X' is a supported database). The dbx functions allow you to access all supported databases using a single calling convention. The dbx-functions themselves do not interface directly to the databases, but interface to the modules that are used to support these databases.
To be able to use a database with the dbx-module, the module must be either linked or loaded into PHP, and the database module must be supported by the dbx-module. Currently, the following databases are supported, but others will follow:
FrontBase (available from PHP 4.1.0).
Sybase-CT (available from PHP 4.2.0).
Oracle (oci8) (available from PHP 4.3.0).
SQLite (CVS only).
Documentation for adding additional database support to dbx can be found at http://www.guidance.nl/php/dbx/doc/.
In order to have these functions available, you must compile PHP with dbx support by using the --enable-dbx option and all options for the databases that will be used, e.g. for MySQL you must also specify --with-mysql=[DIR]. To get other supported databases to work with the dbx-module refer to their specific documentation.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
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.
Columns names can be returned "unchanged" or converted to "uppercase" or "lowercase". This directive can be overridden with a flag to dbx_query().
There are two resource types used in the dbx module. The first one is the link-object for a database connection, the second a result-object which holds the result of a query.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Always refer to the module-specific documentation as well.
See also dbx_connect().
dbx_compare() returns 0 if the row_a[$column_key] is equal to row_b[$column_key], and 1 or -1 if the former is greater or is smaller than the latter one, respectively, or vice versa if the flag is set to DBX_CMP_DESC. dbx_compare() is a helper function for dbx_sort() to ease the make and use of the custom sorting function.
The flags can be set to specify comparison direction:
DBX_CMP_ASC - ascending order
DBX_CMP_DESC - descending order
DBX_CMP_NATIVE - no type conversion
DBX_CMP_TEXT - compare items as strings
DBX_CMP_NUMBER - compare items numerically
Esempio 1. dbx_compare() example
|
See also dbx_sort().
dbx_connect() returns an object on success, FALSE on error. If a connection has been made but the database could not be selected, the connection is closed and FALSE is returned. The persistent parameter can be set to DBX_PERSISTENT, if so, a persistent connection will be created.
The module parameter can be either a string or a constant, though the latter form is preferred. The possible values are given below, but keep in mind that they only work if the module is actually loaded.
DBX_MYSQL or "mysql"
DBX_ODBC or "odbc"
DBX_PGSQL or "pgsql"
DBX_MSSQL or "mssql"
DBX_FBSQL or "fbsql" (available from PHP 4.1.0)
DBX_SYBASECT or "sybase_ct" (available from PHP 4.2.0)
DBX_OCI8 or "oci8" (available from PHP 4.3.0)
DBX_SQLITE or "sqlite" (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:
It is the name of the currently selected database.
It is a valid handle for the connected database, and as such it can be used in module-specific functions (if required).
It is used internally by dbx only, and is actually the module number mentioned above.
Nota: Always refer to the module-specific documentation as well.
See also dbx_close().
(PHP 4 >= 4.0.6, PHP 5)
dbx_error -- Report the error message of the latest function call in the module (not just in the connection)dbx_error() returns a string containing the error message from the last function call of the abstracted module (e.g. mysql module). If there are multiple connections in the same module, just the last error is given. If there are connections on different modules, the latest error is returned for the module specified by the link_identifier parameter.
Nota: Always refer to the module-specific documentation as well.
The error message for Microsoft SQL Server is actually the result of the mssql_get_last_message() function.
The error message for Oracle (oci8) is not implemented (yet).
(PHP 4 >= 4.3.0, PHP 5)
dbx_escape_string -- Escape a string so it can safely be used in an sql-statement.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
|
See also dbx_query().
(PHP 5)
dbx_fetch_row -- Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag setdbx_fetch_row() returns a row on success, and 0 on failure (e.g. when no more rows are available). When the DBX_RESULT_UNBUFFERED is not set in the query, dbx_fetch_row() will fail as all rows have already been fetched into the results data property.
As a side effect, the rows property of the query-result object is incremented for each successful call to dbx_fetch_row().
Esempio 1. How to handle the returned value
|
The result_identifier parameter is the result object returned by a call to dbx_query().
The returned 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() returns an object or 1 on success, and 0 on failure. The result object is returned only if the query given in sql_statement produces a result set (i.e. a SELECT query, even if the result set is empty).
Esempio 1. How to handle the returned value
|
The flags parameter is used to control the amount of information that is returned. It may be any combination of the following constants with the bitwise OR operator (|). The DBX_COLNAMES_* flags override the dbx.colnames_case setting from php.ini.
It is always set, that is, the returned object has a data property which is a 2 dimensional array indexed numerically. For example, in the expression data[2][3] 2 stands for the row (or record) number and 3 stands for the column (or field) number. The first row and column are indexed at 0.
If DBX_RESULT_ASSOC is also specified, the returning object contains the information related to DBX_RESULT_INFO too, even if it was not specified.
It provides info about columns, such as field names and field types.
It effects that the field values can be accessed with the respective column names used as keys to the returned object's data property.
Associated results are actually references to the numerically indexed data, so modifying data[0][0] causes that data[0]['field_name_for_first_column'] is modified as well.
This flag will not create the data property, and the rows property will initially be 0. Use this flag for large datasets, and use dbx_fetch_row() to retrieve the results row by row.
The dbx_fetch_row() function will return rows that are conformant to the flags set with this query. Incidentally, it will also update the rows each time it is called.
The case of the returned column names will not be changed.
The case of the returned column names will be changed to uppercase.
The case of the returned column names will be changed to lowercase.
DBX_RESULT_INDEX
DBX_RESULT_INDEX | DBX_RESULT_INFO
DBX_RESULT_INDEX | DBX_RESULT_INFO | DBX_RESULT_ASSOC - this is the default, if flags is not specified.
The returned object has four or five properties depending on flags:
It is a valid handle for the connected database, and as such it can be used in module specific functions (if required).
These contain the number of columns (or fields) and rows (or records) respectively.
It is returned only if either DBX_RESULT_INFO or DBX_RESULT_ASSOC is specified in the flags parameter. It is a 2 dimensional array, that has two named rows (name and type) to retrieve column information.
This property contains the actual resulting data, possibly associated with column names as well depending on flags. If DBX_RESULT_ASSOC is set, it is possible to use $result->data[2]["field_name"].
Esempio 3. outputs the content of data property into HTML table
|
Esempio 4. How to handle UNBUFFERED queries
|
Nota: Always refer to the module-specific documentation as well.
Column names for queries on an Oracle database are returned in lowercase.
See also dbx_escape_string(), dbx_fetch_row() and dbx_connect().
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
|
See also dbx_compare().
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
db++, made by the German company Concept asa, is a relational database system with high performance and low memory and disk usage in mind. While providing SQL as an additional language interface, it is not really a SQL database in the first place but provides its own AQL query language which is much more influenced by the relational algebra then SQL is.
Concept asa always had an interest in supporting open source languages, db++ has had Perl and Tcl call interfaces for years now and uses Tcl as its internal stored procedure language.
This extension relies on external client libraries so you have to have a db++ client installed on the system you want to use this extension on.
Concept asa provides db++ Demo versions and documentation for Linux, some other Unix versions. There is also a Windows version of db++, but this extension doesn't support it (yet).
In order to build this extension yourself you need the db++ client libraries and header files to be installed on your system (these are included in the db++ installation archives by default). You have to run configure with option --with-dbplus to build this extension.
configure looks for the client libraries and header files under the default paths /usr/dbplus, /usr/local/dbplus and /opt/dblus. If you have installed db++ in a different place you have add the installation path to the configure option like this: --with-dbplus=/your/installation/path.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Most db++ functions operate on or return dbplus_relation resources. A dbplus_relation is a handle to a stored relation or a relation generated as the result of a query.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 1. DB++ Error Codes
PHP Constant | db++ constant | meaning |
---|---|---|
DBPLUS_ERR_NOERR (integer) | ERR_NOERR | Null error condition |
DBPLUS_ERR_DUPLICATE (integer) | ERR_DUPLICATE | Tried to insert a duplicate tuple |
DBPLUS_ERR_EOSCAN (integer) | ERR_EOSCAN | End of scan from rget() |
DBPLUS_ERR_EMPTY (integer) | ERR_EMPTY | Relation is empty (server) |
DBPLUS_ERR_CLOSE (integer) | ERR_CLOSE | The server can't close |
DBPLUS_ERR_WLOCKED (integer) | ERR_WLOCKED | The record is write locked |
DBPLUS_ERR_LOCKED (integer) | ERR_LOCKED | Relation was already locked |
DBPLUS_ERR_NOLOCK (integer) | ERR_NOLOCK | Relation cannot be locked |
DBPLUS_ERR_READ (integer) | ERR_READ | Read error on relation |
DBPLUS_ERR_WRITE (integer) | ERR_WRITE | Write error on relation |
DBPLUS_ERR_CREATE (integer) | ERR_CREATE | Create() system call failed |
DBPLUS_ERR_LSEEK (integer) | ERR_LSEEK | Lseek() system call failed |
DBPLUS_ERR_LENGTH (integer) | ERR_LENGTH | Tuple exceeds maximum length |
DBPLUS_ERR_OPEN (integer) | ERR_OPEN | Open() system call failed |
DBPLUS_ERR_WOPEN (integer) | ERR_WOPEN | Relation already opened for writing |
DBPLUS_ERR_MAGIC (integer) | ERR_MAGIC | File is not a relation |
DBPLUS_ERR_VERSION (integer) | ERR_VERSION | File is a very old relation |
DBPLUS_ERR_PGSIZE (integer) | ERR_PGSIZE | Relation uses a different page size |
DBPLUS_ERR_CRC (integer) | ERR_CRC | Invalid crc in the superpage |
DBPLUS_ERR_PIPE (integer) | ERR_PIPE | Piped relation requires lseek() |
DBPLUS_ERR_NIDX (integer) | ERR_NIDX | Too many secondary indices |
DBPLUS_ERR_MALLOC (integer) | ERR_MALLOC | Malloc() call failed |
DBPLUS_ERR_NUSERS (integer) | ERR_NUSERS | Error use of max users |
DBPLUS_ERR_PREEXIT (integer) | ERR_PREEXIT | Caused by invalid usage |
DBPLUS_ERR_ONTRAP (integer) | ERR_ONTRAP | Caused by a signal |
DBPLUS_ERR_PREPROC (integer) | ERR_PREPROC | Error in the preprocessor |
DBPLUS_ERR_DBPARSE (integer) | ERR_DBPARSE | Error in the parser |
DBPLUS_ERR_DBRUNERR (integer) | ERR_DBRUNERR | Run error in db |
DBPLUS_ERR_DBPREEXIT (integer) | ERR_DBPREEXIT | Exit condition caused by prexit() * procedure |
DBPLUS_ERR_WAIT (integer) | ERR_WAIT | Wait a little (Simple only) |
DBPLUS_ERR_CORRUPT_TUPLE (integer) | ERR_CORRUPT_TUPLE | A client sent a corrupt tuple |
DBPLUS_ERR_WARNING0 (integer) | ERR_WARNING0 | The Simple routines encountered a non fatal error which was corrected |
DBPLUS_ERR_PANIC (integer) | ERR_PANIC | The server should not really die but after a disaster send ERR_PANIC to all its clients |
DBPLUS_ERR_FIFO (integer) | ERR_FIFO | Can't create a fifo |
DBPLUS_ERR_PERM (integer) | ERR_PERM | Permission denied |
DBPLUS_ERR_TCL (integer) | ERR_TCL | TCL_error |
DBPLUS_ERR_RESTRICTED (integer) | ERR_RESTRICTED | Only two users |
DBPLUS_ERR_USER (integer) | ERR_USER | An error in the use of the library by an application programmer |
DBPLUS_ERR_UNKNOWN (integer) | ERR_UNKNOWN |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
This function will add a tuple to a relation. The tuple data is an array of attribute/value pairs to be inserted into the given relation. After successful execution the tuple array will contain the complete data of the newly created tuple, including all implicitly set domain fields like sequences.
The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_aql() will execute an AQL query on the given server and dbpath.
On success it will return a relation handle. The result data may be fetched from this relation by calling dbplus_next() and dbplus_current(). Other relation access functions will not work on a result relation.
Further information on the AQL A... Query Language is provided in the original db++ manual.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_chdir() will change the virtual current directory where relation files will be looked for by dbplus_open(). dbplus_chdir() will return the absolute path of the current directory. Calling dbplus_chdir() without giving any newdir may be used to query the current working directory.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Calling dbplus_close() will close a relation previously opened by dbplus_open().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_curr() will read the data for the current tuple for the given relation and will pass it back as an associative array in tuple.
The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.
See also dbplus_first(), dbplus_prev(), dbplus_next(), and dbplus_last().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_errcode() returns a cleartext error string for the error code passed as errno of for the result code of the last db++ operation if no parameter is given.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_errno() will return the error code returned by the last db++ operation.
See also dbplus_errcode().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_find() will place a constraint on the given relation. Further calls to functions like dbplus_curr() or dbplus_next() will only return tuples matching the given constraints.
Constraints are triplets of strings containing of a domain name, a comparison operator and a comparison value. The constraints parameter array may consist of a collection of string arrays, each of which contains a domain, an operator and a value, or of a single string array containing a multiple of three elements.
The comparison operator may be one of the following strings: '==', '>', '>=', '<', '<=', '!=', '~' for a regular expression match and 'BAND' or 'BOR' for bitwise operations.
See also dbplus_unselect().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_curr() will read the data for the first tuple for the given relation, make it the current tuple and pass it back as an associative array in tuple.
The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.
See also dbplus_curr(), dbplus_prev(), dbplus_next(), and dbplus_last().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_flush() will write all changes applied to relation since the last flush to disk.
The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_freealllocks() will free all tuple locks held by this client.
See also dbplus_getlock(), dbplus_freelock(), and dbplus_freerlocks().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_freelock() will release a write lock on the given tuple previously obtained by dbplus_getlock().
See also dbplus_getlock(), dbplus_freerlocks(), and dbplus_freealllocks().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_freerlocks() will free all tuple locks held on the given relation.
See also dbplus_getlock(), dbplus_freelock(), and dbplus_freealllocks().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_getlock() will request a write lock on the specified tuple. It will return zero on success or a non-zero error code, especially DBPLUS_ERR_WLOCKED, on failure.
See also dbplus_freelock(), dbplus_freerlocks(), and dbplus_freealllocks().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_getunique() will obtain a number guaranteed to be unique for the given relation and will pass it back in the variable given as uniqueid.
The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Not implemented yet.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_curr() will read the data for the last tuple for the given relation, make it the current tuple and pass it back as an associative array in tuple.
The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.
See also dbplus_first(), dbplus_curr(), dbplus_prev(), and dbplus_next().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_lockrel() will request a write lock on the given relation. Other clients may still query the relation, but can't alter it while it is locked.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_curr() will read the data for the next tuple for the given relation, will make it the current tuple and will pass it back as an associative array in tuple.
The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.
See also dbplus_first(), dbplus_curr(), dbplus_prev(), and dbplus_last().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The relation file name will be opened. name can be either a file name or a relative or absolute path name. This will be mapped in any case to an absolute relation file path on a specific host machine and server.
On success a relation file resource (cursor) is returned which must be used in any subsequent commands referencing the relation. Failure leads to a zero return value, the actual error code may be asked for by calling dbplus_errno().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_curr() will read the data for the previous tuple for the given relation, will make it the current tuple and will pass it back as an associative array in tuple.
The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.
See also dbplus_first(), dbplus_curr(), dbplus_next(), and dbplus_last().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_rchperm() will change access permissions as specified by mask, user and group. The values for these are operating system specific.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_rcreate() will create a new relation named name. An existing relation by the same name will only be overwritten if the relation is currently not in use and overwrite is set to TRUE.
domlist should contain the domain specification for the new relation within an array of domain description strings. ( dbplus_rcreate() will also accept a string with space delimited domain description strings, but it is recommended to use an array). A domain description string consists of a domain name unique to this relation, a slash and a type specification character. See the db++ documentation, especially the dbcreate(1) manpage, for a description of available type specifiers and their meanings.
(4.1.0 - 4.2.3 only)
dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indicesAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_rcrtexact() will create an exact but empty copy of the given relation under a new name. An existing relation by the same name will only be overwritten if overwrite is TRUE and no other process is currently using the relation.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_resolve() will try to resolve the given relation_name and find out internal server id, real hostname and the database path on this host. The function will return an array containing these values under the keys 'sid', 'host' and 'host_path' or FALSE on error.
See also dbplus_tcl().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Not implemented yet.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_ropen() will open the relation file locally for quick access without any client/server overhead. Access is read only and only dbplus_current() and dbplus_next() may be applied to the returned relation.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_rquery() performs a local (raw) AQL query using an AQL interpreter embedded into the db++ client library. dbplus_rquery() is faster than dbplus_aql() but will work on local data only.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_rrename() will change the name of relation to name.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_rsecindex() will create a new secondary index for relation with consists of the domains specified by domlist and is of type type
domlist may be passed as a single domain name string or as an array of domain names.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_unlink() will close and remove the relation.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_rzap() will remove all tuples from relation.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Not implemented yet.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
A db++ server will prepare a TCL interpreter for each client connection. This interpreter will enable the server to execute TCL code provided by the client as a sort of stored procedures to improve the performance of database operations by avoiding client/server data transfers and context switches.
dbplus_tcl() needs to pass the client connection id the TCL script code should be executed by. dbplus_resolve() will provide this connection id. The function will return whatever the TCL code returns or a TCL error message if the TCL code fails.
See also dbplus_resolve().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_tremove() removes tuple from relation if it perfectly matches a tuple within the relation. current, if given, will contain the data of the new current tuple after calling dbplus_tremove().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Not implemented yet.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_unlockrel() will release a write lock previously obtained by dbplus_lockrel().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Calling dbplus_unselect() will remove a constraint previously set by dbplus_find() on relation.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_update() replaces the tuple given by old with the data from new if and only if old completely matches a tuple within relation.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_xlockrel() will request an exclusive lock on relation preventing even read access from other clients.
See also dbplus_xunlockrel().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_xunlockrel() will release an exclusive lock on relation previously obtained by dbplus_xlockrel().
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.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Questa estensione definisce un solo tipo di risorsa: un descrittore di file restituito dalla funzione dio_open().
La funzione dio_close() chiude il descrittore di file fd.
Vedere anche dio_open().
La funzione dio_fcntl() esegue le operazioni specificate dal parametro cmd sul descrittore di file fd. Qualora i comandi richiedano informazioni addizionali occorre valorizzare args con tali informazioni.
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.
(PHP 4 >= 4.2.0, PHP 5)
dio_open -- Apre un nuovo file nella modalità specificata da flags e i permessi indicati in modeLa funzione dio_open() apre un file e restituisce un nuovo descrittore di file per questo, 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.
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().
(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 1kLa 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().
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.
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
(PHP 4 >= 4.3.0, PHP 5)
dio_tcsetattr -- Imposta gli attributi terminale e la velocità per una porta serialeLa funzione dio_tcsetattr() imposta gli attributi di terminale e la velocità della porta aperta fd. Attualmente le opzioni disponibili sono:
'baud' - velocità della porta - può essere 38400,19200,9600,4800,2400,1800,1200,600,300,200,150,134,110,75 oppure 50, il valore di default è 9600
'bits' - bit di dati - può essere 8,7,6 oppure 5 il valore di default è 8
'stop' - bit di stop - può essere 1 o 2 il valore di default è 1
'parity' - può essere 0,1 o 2 il valore di default è 0
Esempio 1. Esempio di impostazione della velocità di una porta seriale
|
(PHP 4 >= 4.2.0, PHP 5)
dio_truncate -- Tronca il file indicato da fd ad un numero di byte specificatoLa funzione dio_truncate() tronca il file indicato da fd ad una lunghezza massima di offset bytes. Se in precedenza il file ha una dimensione maggiore, i dati in eccesso sono persi. Al contrario se il file è più corto, non è specificato se si debba lasciarlo inalterato o debba essere allungato. Nell'ultimo caso la parte aggiunta viene riempita di zero. Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
(PHP 4 >= 4.2.0, PHP 5)
dio_write -- Scrive dati sul file indicato da fd con la possibilità di troncarne la lunghezzaLa funzione dio_write() scrive fino a len bytes da data nel file fd. 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().
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Nota: La costante PATH_SEPARATOR è stata inserita dalla versione 4.3.0-RC2.
Per funzioni correlate, quali dirname(), is_dir(), mkdir() e rmdir(), vedere la sezione Filesystem.
Cambia la directory in uso da parte del PHP in directory. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Quando safe-mode è abilitato, PHP controlla che la directory nella quale si sta lavorando, abbia lo stesso UID dello script che è in esecuzione.
Vedere anche getcwd().
Cambia la directory di root del processo in esecuzione in directory. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Questa funzione è disponibile soltanto se il sistema la supporta e se si sta utilizzando il PHP come CLI, CGI o Embed SAPI.
Nota: chroot() richiede i privilegi di root.
Nota: Questa funzione non è implementata su piattaforme Windows
Un meccanismo pseudo orientato agli oggetti per leggere una directory. La directory data è aperta. Due proprietà sono disponibili nonappena la directory è stata aperta. La proprietà handle può essere usata in congiunzione ad altre funzioni relative alle directory, quali readdir(), rewinddir() e closedir(). La proprietà path è impostata alla directory che è stata aperta. Sono disponibili tre metodi: read (leggi), rewind (riavvolgi) e close (chiudi).
Fare attenzione al modo in cui il valore restituito dalla funzione dir() è controllato nell'esempio sotto riportato. Controlliamo esplicitamente che il valore restituito sia identico a (uguale a e dello stesso tipo di (fare riferimento a Comparison Operators per maggiori informazioni) FALSE altrimenti, ogni risultato il cui nome non venga valutato FALSE farà interrompere il ciclo.
Nota: L'ordine nel quale vengono restituiti i dati dal metodo read è dipendente dal sistema usato.
Nota: Questo definisce la classe interna Directory, ciò significa che non sarà possibile definire una nuova classe con lo stesso nome. Per una lista completa delle classi predefinite presenti in PHP, fare riferimento a Predefined Classes.
Chiude il flusso directory indicato da dir_handle. Il flusso deve essere stato aperto in precedenza da opendir().
Restituisce la directory di lavoro in uso al momento.
Vedere anche chdir().
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.
Vedere anche is_dir().
Restituisce il nomefile del file successivo della directory. I nomi dei file vengono restituiti secondo l'ordine in cui sono memorizzati nel filesystem.
Si faccia caso al modo in cui il valore restituito da readdir() viene controllato negli esempi successivi. Viene controllato esplicitamente che il valore restituito sia identico a (uguale a e dello stesso tipo di (vedere Comparison Operators per maggiori informazioni) FALSE altrimenti avverrebbe che ogni nome di directory il cui nome fosse valutato FALSE interromperebbe il loop (per esempio una directory chiamata "0").
Esempio 1. Elenca tutti i file presenti in una directory
|
Nota che readdir() restituirà le voci . e ... Se non si vogliono ottenere queste, si possono semplicemente eliminare:
Vedere anche is_dir().
Reimposta il flusso della directory indicato da dir_handle all'inizio della directory.
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
Outputs something like:
|
Esempio 2. PHP 4 alternatives to scandir()
Outputs something like:
|
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().
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.
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
Constant | Value | Description |
---|---|---|
XML_ELEMENT_NODE (integer) | 1 | Node is an element |
XML_ATTRIBUTE_NODE (integer) | 2 | Node is an attribute |
XML_TEXT_NODE (integer) | 3 | Node is a piece of text |
XML_CDATA_SECTION_NODE (integer) | 4 | |
XML_ENTITY_REF_NODE (integer) | 5 | |
XML_ENTITY_NODE (integer) | 6 | Node is an entity like |
XML_PI_NODE (integer) | 7 | Node is a processing instruction |
XML_COMMENT_NODE (integer) | 8 | Node is a comment |
XML_DOCUMENT_NODE (integer) | 9 | Node is a document |
XML_DOCUMENT_TYPE_NODE (integer) | 10 | |
XML_DOCUMENT_FRAG_NODE (integer) | 11 | |
XML_NOTATION_NODE (integer) | 12 | |
XML_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
Constant | Value | Description |
---|---|---|
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 |
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 name | Parent classes |
---|---|
DOMAttr | DOMNode |
DOMCDataSection | DOMText : DOMNode |
DOMCharacterData | DOMNode |
DOMComment | DOMCharacterData : DomNode |
DOMDocument | DOMNode |
DOMDocumentFragment | DOMNode |
DOMDocumentType | DOMNode |
DOMElement | DOMNode |
DOMEntity | DOMNode |
DOMEntityReference | DOMNode |
DOMNode | |
DOMNotation | DOMNode |
DOMProcessingInstruction | DOMNode |
DOMText | DOMCDataSection : DomNode |
DOMException | |
DOMImplementation | |
DOMNamedNodeMap | |
DOMNodeList | |
DOMXPath |
(no version information, might be only in CVS)
DOMCharacterData->appendData -- Append the string to the end of the character data of the node.Append the string data to the end of the character data of the node.
(no version information, might be only in CVS)
DOMCharacterData->deleteData -- Remove a range of characters from the node.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.
(no version information, might be only in CVS)
DOMCharacterData->insertData -- Insert a string at the specified 16-bit unit offset.Inserts string data at position offset.
Throws DOMExcpetion if offset is negative or greater than the number of 16-bit units in data.
(no version information, might be only in CVS)
DOMCharacterData->replaceData -- Replace a substring within the DOMCharacterData node.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.
(no version information, might be only in CVS)
DOMCharacterData->substringData -- Extracts a range of data from the node.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.
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().
(no version information, might be only in CVS)
DOMDocument->createAttributeNS -- Create new attribute node with an associated namespaceThis 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().
(no version information, might be only in CVS)
DOMDocument->createCDATASection -- Create new cdata nodeThis 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().
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().
(no version information, might be only in CVS)
DOMDocument->createDocumentFragment -- Create new document fragmentThis 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.
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().
(no version information, might be only in CVS)
DOMDocument->createElementNS -- Create new element node with an associated namespaceThis 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().
(no version information, might be only in CVS)
DOMDocument->createEntityReference -- Create new entity reference nodeThis 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().
(no version information, might be only in CVS)
DOMDocument->createProcessingInstruction -- Creates new PI nodeThis 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().
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().
(no version information, might be only in CVS)
DOMDocument->getElementById -- Searches for an element with a certain id.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.
(no version information, might be only in CVS)
DOMDocument->getElementsByTagName -- Searches for all elements with given tag 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.
(no version information, might be only in CVS)
DOMDocument->getElementsByTagNameNS -- Searches for all elements with given tag name in specified namespace.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.
(no version information, might be only in CVS)
DOMDocument->importNode -- Import node into current document.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.
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.
See also DOMDocument->loadXML(), DOMDocument->save() and DOMDocument->saveXML().
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.
See also DOMDocument->loadHTMLFile(), DOMDocument->saveHTML() and DOMDocument->saveHTMLFile().
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.
See also DOMDocument->loadHTML(), DOMDocument->saveHTML() and DOMDocument->saveHTMLFile().
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.
See also DOMDocument->load(), DOMDocument->save() and DOMDocument->saveXML().
(no version information, might be only in CVS)
DOMDocument->relaxNGValidate -- Performs relaxNG validation on the document.Performs relaxNG validation on the document based on the file defined by filename.
See also DOMDocument->validate(), DOMDocument->schemaValidate(), DOMDocument->schemaValidateSource() and DOMDocument->relaxNGValidateSource().
(no version information, might be only in CVS)
DOMDocument->relaxNGValidateSource -- Performs relaxNG validation on the document.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().
(no version information, might be only in CVS)
DOMDocument->save -- Dumps the internal XML tree back into a fileCreates 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
|
See also DOMDocument->load(), DOMDocument->loadXML() and DOMDocument->saveXML().
(no version information, might be only in CVS)
DOMDocument->saveHTML -- Dumps the internal document into a string using HTML formattingCreates an HTML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below.
Esempio 1. Creating a simple HTML document header
|
See also DOMDocument->loadHTML(), DOMDocument->loadHTMLFile() and DOMDocument->saveHTMLFile().
(no version information, might be only in CVS)
DOMDocument->saveHTMLFile -- Dumps the internal document back into a file using HTML formattingCreates 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
|
See also DOMDocument->loadHTML(), DOMDocument->loadHTMLFile() and DOMDocument->saveHTML().
(no version information, might be only in CVS)
DOMDocument->saveXML -- Dumps the internal XML tree back into a stringCreates an XML document from the dom representation. This function is usually called after building a new dom document from scratch as in the example below. The node is used to output only the node rather than the entire document.
Esempio 1. Creating a simple HTML document header
|
See also DOMDocument->load(), DOMDocument->loadXML() and DOMDocument->save().
(no version information, might be only in CVS)
DOMDocument->schemaValidate -- Validates a document based on a schema.Validates a document based on a schema defined by filename.
See also DOMDocument->schemaValidateSource(), DOMDocument->relaxNGValidate(), DOMDocument->relaxNGValidateSource() and DOMDocument->validate().
(no version information, might be only in CVS)
DOMDocument->schemaValidateSource -- Validates a document based on a schema.Validates a document based on a schema defined in string source.
See also DOMDocument->schemaValidate(), DOMDocument->relaxNGValidate(), DOMDocument->relaxNGValidateSource() and DOMDocument->validate(),.
(no version information, might be only in CVS)
DOMDocument->validate -- Validates the document based on its DTD.Validates the document based on its DTD.
See also DOMDocument->schemaValidate(), DOMDocument->schemaValidateSource(), DOMDocument->relaxNGValidate(), DOMDocument->relaxNGValidateSource().
(no version information, might be only in CVS)
DOMDocument->xinclude -- Substitutes XIncludes in a DOMDocument Object.(no version information, might be only in CVS)
DOMElement->getAttribute -- Returns value of attributeReturns 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()
(no version information, might be only in CVS)
DOMElement->getAttributeNode -- Returns attribute nodeReturns the attribute node with name name for the current element.
See also DOMElement->setAttribute()
(no version information, might be only in CVS)
DOMElement->getAttributeNodeNS -- Returns attribute nodeReturns the attribute node in namespace namespaceURI with local name localName for the current node.
See also DOMElement->setAttributeNodeNS()
(no version information, might be only in CVS)
DOMElement->getAttributeNS -- Returns value of attributeReturns 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()
(no version information, might be only in CVS)
DOMElement->getElementsByTagName -- Gets elements by tagnameThis 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.
(no version information, might be only in CVS)
DOMElement->getElementsByTagNameNS -- Get elements by namespaceURI and localNameThis 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.
(no version information, might be only in CVS)
DOMElement->hasAttribute -- Checks to see if attribute existsIndicates wether attribute named name exists as a member of the element.
(no version information, might be only in CVS)
DOMElement->hasAttributeNS -- Checks to see if attribute existsIndicates wether attribute in namespace namespaceURI named localName exists as a member of the element.
Removes attribute named name from the element.
Throws DOMExcpetion if node cannot be modified.
Removes attribute oldnode from the element.
Throws DOMExcpetion if node cannot be modified or attribute is not a member of the element node.
Removes attribute is namespace namespaceURI named localName from the element.
Throws DOMExcpetion if node cannot be modified.
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.
See also DOMElement->getAttribute()
(no version information, might be only in CVS)
DOMElement->setAttributeNode -- Adds new attribute node to elementAdds new attribute node attr to element. Returns old node if attribute replaced.
Throws DOMExcpetion if node cannot be modified.
(no version information, might be only in CVS)
DOMElement->setAttributeNodeNS -- Adds new attribute node to elementAdds new attribute node attr to element. Returns old node if attribute replaced.
Throws DOMExcpetion if node cannot be modified.
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()
(no version information, might be only in CVS)
DOMImplementation->createDocument -- Creates a DOM Document object of the specified type with its document element.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().
(no version information, might be only in CVS)
DOMImplementation->createDocumentType -- Creates an empty DOMDocumentType object.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().
(no version information, might be only in CVS)
DOMImplementation->hasFeature -- Test if the DOM implementation implements a specific feature and version.Test if the DOM implementation implements a specific feature and version.
(no version information, might be only in CVS)
DOMNamedNodeMap->getNamedItem -- Retrieves a node specified by name.(no version information, might be only in CVS)
DOMNamedNodeMap->getNamedItemNS -- Retrieves a node specified by local name and namespace URI.Retrieves a node specified by localName and namespaceURI.
(no version information, might be only in CVS)
DOMNamedNodeMap->item -- Retrieves a node specified by index.Retrieves a node specified by index within the DOMNamedNodeMap object.
(no version information, might be only in CVS)
DOMNode->appendChild -- Adds new child at the end of the childrenThis functions appends a child to an existing list of children or creates a new list of children. The child can be created with e.g. DOMDocument->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.
Creates a copy of the node. The paramter deep indicates wether to copy all descedant nodes. This paramter is defaulted to FALSE.
(no version information, might be only in CVS)
DOMNode->hasAttributes -- Checks if node has attributes(no version information, might be only in CVS)
DOMNode->insertBefore -- Adds new child at the end of the childrenThis 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.
(no version information, might be only in CVS)
DOMNode->isSameNode -- Indicates if two nodes are the same node.This functions indicates if two nodes are the same node. The comparison is NOT based on content
(no version information, might be only in CVS)
DOMNode->isSupported -- Checks if feature is supported for specified version.Checks if feature is supported for specified version.
(no version information, might be only in CVS)
DOMNode->lookupNamespaceURI -- Returns namespace URI of the node based on the prefix.Returns namespace URI of the node based on the prefix.
(no version information, might be only in CVS)
DOMNode->lookupPrefix -- Returns name space prefix of the node based on namespaceURI.Returns name space prefix of the node based on namespaceURI.
(no version information, might be only in CVS)
DOMNode->removeChild -- Removes child from list of childrenThis 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.
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.
(no version information, might be only in CVS)
DOMNodelist->item -- Retrieves a node specified by index.Retrieves a node specified by index within the DOMNodelist object.
(no version information, might be only in CVS)
DOMText->isWhitespaceInElementContent -- Indicates whether this text node contains whitespace.Indicates whether this text node contains whitespace. The text node is determined to contain whitespace in element content during the load of the document.
(no version information, might be only in CVS)
DOMText->splitText -- Breaks this node into two nodes at the specified 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.
(no version information, might be only in CVS)
DOMXPath->query -- Evaluates the XPath expression in the given stringReturns 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.
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().
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.
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.
Esistono alcune funzioni che non rientrano nello standard DOM e quindi non dovrebbero essere più utilizzate come evidenziato nella tabella seguente. La funzione DomNode_append_child() ha modificato il suo comportamento. Attualmente aggiunge un figlio e non un elemento fratello. Se ciò crea problemi alle applicazioni si può usare la funzione non DOM
Tabella 1. Funzioni deprecate e loro sostituti
Vecchia funzione | Nuova funzione |
---|---|
xmldoc | domxml_open_mem() |
xmldocfile | domxml_open_file() |
domxml_new_xmldoc | domxml_new_doc() |
domxml_dump_mem | DomDocument_dump_mem() |
domxml_dump_mem_file | DomDocument_dump_file() |
DomDocument_dump_mem_file | DomDocument_dump_file() |
DomDocument_add_root | DomDocument_create_element() seguita da DomNode_append_child() |
DomDocument_dtd | DomDocument_doctype() |
DomDocument_root | DomDocument_document_element() |
DomDocument_children | DomNode_child_nodes() |
DomDocument_imported_node | Nessun sostituto. |
DomNode_add_child | Creare un nuovo nodo con, ad esempio, DomDocument_create_element() e aggiungere il figlio con DomNode_append_child(). |
DomNode_children | DomNode_child_nodes() |
DomNode_parent | DomNode_parent_node() |
DomNode_new_child | Creare un nuovo nodo con, ad esempio, DomDocument_create_element() e aggiungere il figlio con DomNode_append_child(). |
DomNode_get_content | Il contenuto è semplicemente un nodo di testo ed è accessibile tramite DomNode_child_nodes(). |
DomNode_set_content | Il contenuto è semplicemente un nodo di testo e può essere aggiunto con DomNode_append_child(). |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 2. Costanti XML
Costante | Valore | Descrizione |
---|---|---|
XML_ELEMENT_NODE (integer) | 1 | Il nodo è un elemento |
XML_ATTRIBUTE_NODE (integer) | 2 | Il nodo è un attributo |
XML_TEXT_NODE (integer) | 3 | Il nodo è un segmento di testo |
XML_CDATA_SECTION_NODE (integer) | 4 | |
XML_ENTITY_REF_NODE (integer) | 5 | |
XML_ENTITY_NODE (integer) | 6 | Il nodo è un'entità come, ad esempio, |
XML_PI_NODE (integer) | 7 | Il nodo è una istruzione di processamento |
XML_COMMENT_NODE (integer) | 8 | Il nodo è un commento |
XML_DOCUMENT_NODE (integer) | 9 | Il nodo è un documento |
XML_DOCUMENT_TYPE_NODE (integer) | 10 | |
XML_DOCUMENT_FRAG_NODE (integer) | 11 | |
XML_NOTATION_NODE (integer) | 12 | |
XML_GLOBAL_NAMESPACE (integer) | 1 | |
XML_LOCAL_NAMESPACE (integer) | 2 | |
XML_HTML_DOCUMENT_NODE (integer) | ||
XML_DTD_NODE (integer) | ||
XML_ELEMENT_DECL_NODE (integer) | ||
XML_ATTRIBUTE_DECL_NODE (integer) | ||
XML_ENTITY_DECL_NODE (integer) | ||
XML_NAMESPACE_DECL_NODE (integer) | ||
XML_ATTRIBUTE_CDATA (integer) | ||
XML_ATTRIBUTE_ID (integer) | ||
XML_ATTRIBUTE_IDREF (integer) | ||
XML_ATTRIBUTE_IDREFS (integer) | ||
XML_ATTRIBUTE_ENTITY (integer) | ||
XML_ATTRIBUTE_NMTOKEN (integer) | ||
XML_ATTRIBUTE_NMTOKENS (integer) | ||
XML_ATTRIBUTE_ENUMERATION (integer) | ||
XML_ATTRIBUTE_NOTATION (integer) | ||
XPATH_UNDEFINED (integer) | ||
XPATH_NODESET (integer) | ||
XPATH_BOOLEAN (integer) | ||
XPATH_NUMBER (integer) | ||
XPATH_STRING (integer) | ||
XPATH_POINT (integer) | ||
XPATH_RANGE (integer) | ||
XPATH_LOCATIONSET (integer) | ||
XPATH_USERS (integer) | ||
XPATH_NUMBER (integer) |
Le API di questo modulo aderiscono il più possibile allo standard DOM di livello 2. Di conseguenza le API sono completamente orientate agli oggetti. Si ritiene una buona idea avere disponibile lo standard DOM quando si utilizza questo modulo. Sebbene le API siano orientate agli oggetti, vi sono alcune funzioni che possono essere richiamate in modo non orientato agli oggetti, passando l'oggetto su cui operare come primo argomento. Queste funzioni sono state mantenute per compatibilità verso le vecchie versioni del modulo, ma non se ne incoraggia l'uso nello sviluppo di nuovi prodotti.
Queste API differiscono della API DOM ufficiali per due aspetti. Primo, gli attributi della classe sono implermentati come funzioni con il medesimo nome e, secondo, i nomi delle funzioni seguono la convenzione del PHP. Questo significa che la funzione DOM lastChild() sarà chiamata last_child().
In questo modulo sono definite diverse classi, queste saranno elencate - compresi i loro metodi - nella seguente tabella. Le classi con un equivalente nello standard DOM sono chiamate DOMxxx.
Tabella 3. Elenco delle classi
Nome della classe | Classe genitrice |
---|---|
DomAttribute | DomNode |
DomCData | DomNode |
DomComment | DomCData : DomNode |
DomDocument | DomNode |
DomDocumentType | DomNode |
DomElement | DomNode |
DomEntity | DomNode |
DomEntityReference | DomNode |
DomProcessingInstruction | DomNode |
DomText | DomCData : DomNode |
Parser | Attualmente chiamata DomParser |
XPathContext |
Tabella 4. Classe DomDocument (DomDocument : DomNode)
Metodi | Funzioni | Note |
---|---|---|
doctype | DomDocument_doctype() | |
document_element | DomDocument_document_element() | |
create_element | DomDocument_create_element() | |
create_text_node | DomDocument_create_text_node() | |
create_comment | DomDocument_create_comment() | |
create_cdata_section | DomDocument_create_cdata_section() | |
create_processing_instruction | DomDocument_create_processing_instruction() | |
create_attribute | DomDocument_create_attribute() | |
create_entity_reference | DomDocument_create_entity_reference() | |
get_elements_by_tagname | DomDocument_get_elements_by_tagname() | |
get_element_by_id | DomDocument_get_element_by_id() | |
dump_mem | DomDocument_dump_mem() | non standard DOM |
dump_file | DomDocument_dump_file() | non standard DOM |
html_dump_mem | DomDocument_html_dump_mem() | non standard DOM |
xpath_init | xpath_init | non standard DOM |
xpath_new_context | xpath_new_context | non standard DOM |
xptr_new_context | xptr_new_context | non standard DOM |
Tabella 5. Classe DomElement (DomElement : DomNode)
Metodo | Funzioni | Note |
---|---|---|
tagname | DomElement_tagname() | |
get_attribute | DomElement_get_attribute() | |
set_attribute | DomElement_set_attribute() | |
remove_attribute | DomElement_remove_attribute() | |
get_attribute_node | DomElement_get_attribute_node() | |
get_elements_by_tagname | DomElement_get_elements_by_tagname() | |
has_attribute | DomElement_has_attribute() |
Tabella 6. Classe DomNode
Metodo | Note |
---|---|
DomNode_node_name() | |
DomNode_node_value() | |
DomNode_node_type() | |
DomNode_last_child() | |
DomNode_first_child() | |
DomNode_child_nodes() | |
DomNode_previous_sibling() | |
DomNode_next_sibling() | |
DomNode_parent_node() | |
DomNode_owner_document() | |
DomNode_insert_before() | |
DomNode_append_child() | |
DomNode_append_sibling() | non standard DOM. Questa funzione emula il comportamento di DomNode_append_child(). |
DomNode_remove_child() | |
DomNode_has_child_nodes() | |
DomNode_has_attributes() | |
DomNode_clone_node() | |
DomNode_attributes() | |
DomNode_unlink_node() | non standard DOM |
DomNode_replace_node() | non standard DOM |
DomNode_set_content() | non standard DOM, deprecata |
DomNode_get_content() | non standard DOM, deprecata |
DomNode_dump_node() | non standard DOM |
DomNode_is_blank_node() | non standard DOM |
Tabella 7. Classe DomAttribute (DomAttribute : DomNode)
Metodo | Note | |
---|---|---|
name | DomAttribute_name() | |
value | DomAttribute_value() | |
specified | DomAttribute_specified() |
Tabella 8. Classe DomProcessingInstruction (DomProcessingInstruction : DomNode)
Metodo | Funzione | Note |
---|---|---|
target | DomProcessingInstruction_target() | |
data | DomProcessingInstruction_data() |
Tabella 10. Classe XPathContext
Metodo | Funzione | Note |
---|---|---|
eval | XPathContext_eval() | |
eval_expression | XPathContext_eval_expression() | |
register_ns | XPathContext_register_ns() |
Tabella 11. Classe DomDocumentType (DomDocumentType : DomNode)
Metodo | Funzione | Note |
---|---|---|
name | DomDocumentType_name() | |
entities | DomDocumentType_entities() | |
notations | DomDocumentType_notations() | |
public_id | DomDocumentType_public_id() | |
system_id | DomDocumentType_system_id() | |
internal_subset | DomDocumentType_internal_subset() |
La classe DomDtd è derivata da DomNode. Mentre DomComment è derivata da DomCData
Diversi esempi presenti in questo manuale richiedono un testo XML. Anzichè ripetere questo testo in ogni esempio, si inserirà il testo in un file che verrà incluso in ogni esempio. Questo file di include verrà illustrato nel seguente esempio. Si può anche creare un documento XML e leggerlo con DomDocument_open_file().
Esempio 1. File di include example.inc con testo XML
|
(no version information, might be only in CVS)
DomAttribute->name -- Restituisce il nome di un attributoLa funzione restituisce il nome di un attributo.
Vedere anche domattribute_value().
(no version information, might be only in CVS)
DomAttribute->specified -- Verifica se l'attributo è presenteRifarsi allo standard DOM per una descrizione dettagliata.
(no version information, might be only in CVS)
DomAttribute->value -- Restituisce il valore di un attributoQuesta funzione restituisce il valore di un attributo.
Vedere anche domattribute_name().
(no version information, might be only in CVS)
DomDocument->add_root -- Aggiunge un nodo radice [deprecated]Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Aggiunge un nodo radice ad un documento DOM e restituisce il nuovo nodo. Il nome dell'elemento viene passato come parametro.
(no version information, might be only in CVS)
DomDocument->create_attribute -- Crea un nuovo attributoQuesta funzione restituisce una nuova istanza della classe DomAttribute. Il nome dell'attributo viene passato come primo parametro. Mentre il valore viene passato nel secondo parametro. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_processing_instruction(), domdocument_create_entity_reference() e domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->create_cdata_section -- Crea un nuovo nodo cdataQuesta funzione restituisce una nuova istanza della classe DomCData. Il contenuto del nodo cdata viene passato tramite il parametro. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference() e domnode_insert_before().
Questa funzione restituisce una nuova istanza della classe DomComment. Il contenuto del commento viene fornito tramite il parametro. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference() e domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->create_element-ns -- Crea un nodo elemento con il relativo spazio dei nomiQuesta funzione restituisce una nuova istanza della classe DomElement. Il nome del tag dell'elemento viene fornito tramite il parametro nome. L'URI dello spazio dei nomi vene passato tramite il parametro uri. Se nel nodo radice del documento esiste già uno spazio dei nomi con il medesimo URI, si utilizza il prefisso di questo, altrimenti si utilizzerà quello fornito tramite il parametro opzionale prefix oppure ne verrà generato uno casuale. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domdocument_create_element_ns(), domnode_add_namespace(), domnode_set_namespace(), domnode_append_child(), domdocument_create_text(), domdocument_create_comment(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference() e domnode_insert_before().
La funzione restituisce una nuova istanza della classe DomElement. Il nome del tag dell'elemento viene passato tramite il parametro. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domdocument_create_element_ns(), domnode_append_child(), domdocument_create_text(), domdocument_create_comment(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference() e domnode_insert_before().
Questa funzione restituisce una nuova istanza della classe DomEntityReference. Il contenuto dell'entità è passato tramite il parametro. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_processing_instruction(), domdocument_create_attribute() e domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->create_processing_instruction -- Crea un nuovo nodo PIQuesta funzione restituisce una nuova istanza della classe DomCData. Il contenuto della PI viene passato tramite il parametro.Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_attribute(), domdocument_create_entity_reference() e domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->create_text_node -- Crea un nodo di testoQuesta funzione restituisce una nuova istanza della classe DomText. Il testo del nodo viene passato tramite il parametro. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domnode_append_child(), domdocument_create_element(), domdocument_create_comment(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference() e domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->doctype -- Restituisce il tipo di documentoQuesta funzione restituisce una nuova istanza della classe DomDocumentType. Nelle versioni di PHP antecedenti al 4.3 questa classe era chiamata Dtd, ma lo standard DOM non riconosce tale classe.
Vedere anche i metodi della classe DomDocumentType.
(no version information, might be only in CVS)
DomDocument->document_element -- Restituisce il nodo radiceQuesta funzione restituisce il nodo radice di un documento.
Nell'esempio seguente la funzione restituisce l'elemento con nome CHAPTER. L'altro nodo -- the comment -- non viene restituito.
(no version information, might be only in CVS)
DomDocument->dump_file -- Scarica in un file l'albero XML internoLa funzione crea un documento XML dalla rappresentazione DOM. Solitamente questa funzione viene richiamata dopo avere creato da zero un nuovo documento XML, come nell'esempio seguente. Il parametro formato specifica se l'output debba essere ben formattato o meno. Il primo parametro specifica il nome del file ed il secondo se debba essere compresso o meno.
Esempio 1. Creazione dell'intestazione di un documento HTML
|
Vedere anche domdocument_dump_mem() e domdocument_html_dump_mem().
(no version information, might be only in CVS)
DomDocument->dump_mem -- Scarica in una stringa la struttura XML internaAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
La funzione crea un docuemnto XML dalla rappresentazione DOM. Solitamente si richiama questa funzione dopo avere creato un nuovo documento DOM da zero, come nell'esempio seguente. Il parametro formato specifica se l'output debba essere ben formattato o meno.
Esempio 1. Creazione dell'intestazione di un documento HTML
|
Nota: Il primo parametro è stato inserito nella versione 4.3.0 di PHP.
Vedere anche domdocument_dump_file() e domdocument_html_dump_mem().
(no version information, might be only in CVS)
DomDocument->get_element_by_id -- Ricerca di un elemento per idQuesta funzione è simile a domdocument_get_elements_by_tagname() ma ricerca un elemento per un dato id. In accordo con lo standard DOM, è richiesto un DTD che definisca l'attributo ID essere di tipo ID, sebbene l'implementazione corrente ricerchi semplicemente il testo "//*[@ID = '%s']". Ciò non è aderente allo standard DOM che richiede di restituire null se non è noto quale sia l'attributo di tipo id. Questo comportamento sta per essere corretto, pertanto non basarsi sull'implementazione odierna.
Vedere anche domdocument_get_elements_by_tagname()
(no version information, might be only in CVS)
DomDocument->get_elements_by_tagname -- Restituisce un elemento dato il tag
Vedere anche domdocument_add_root()
(no version information, might be only in CVS)
DomDocument->html_dump_mem -- Scarica la struttura XML interna in una stringa come HTMLLa funzione crea un documento HTML dalla rappresentazione DOM. Solitamente si richiama questa funzione dopo avere costruito un nuovo documento DOM da zero, come nell'esempio seguente.
Esempio 1. Creazione dell'intestazione di un documento HTML
|
Vedere anche domdocument_dump_file() e domdocument_html_dump_mem().
(no version information, might be only in CVS)
DomDocument->xinclude -- Sostituisce gli XIncludes in un oggetto DomDocumentAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomDocumentType->entities -- Restituisce l'elenco delle entità
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomDocumentType->internal_subset -- Restituisce un subset interno
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomDocumentType->name -- Restituisce il nome del tipo documentoQuesta funzione restituisce il nome del tipo documento.
(no version information, might be only in CVS)
DomDocumentType->notations -- Restituisce la lista delle notazioni
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomDocumentType->public_id -- Restituisce l'identificatore pubblico del tipo documentoQuesta funzione restituisce l'identificatore pubblico del tipo documento.
Il seguente esempio non visualizza niente.
(no version information, might be only in CVS)
DomDocumentType->system_id -- Restituisce l'identificativo di sistema del tipo documentoRestituisce l'identificativo di sistema del tipo documento.
L'esempio seguente visualizzerà '/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd'.
(no version information, might be only in CVS)
DomElement->get_attribute_node -- Restituisce il valore di un attributo
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomElement->get_attribute -- Restituisce il valore di un attributoLa funzione restituisce l'attributo chiamato nome del nodo corrente.
(PHP >= 4.3 solo) Se non si trova alcun attributo con il nome dato, la funzione restituisce una stringa vuota.
Vedere anche domelement_set_attribute()
(no version information, might be only in CVS)
DomElement->get_elements_by_tagname -- Restituisce l'elemento con il tag datoQuesta funzione restituisce un array con tutti gli elementi che hanno come nome del tag nome. Ogni elemento dell'array è un oggetto DomElement.
Esempio 1. Ottenere il contenuto
|
(no version information, might be only in CVS)
DomElement->has_attribute -- Verifica l'esistenza dell'attributo
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Imposta l'attributo chiamato nome al valore fornito. Se l'attributo non esiste lo crea.
Vedere anche domelement_get_attribute()
(no version information, might be only in CVS)
DomElement->tagname -- Restituisce il nome di un elemento
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomNode->add_namespace -- Aggiunge la dichiarazione dello spazio dei nomi ad un nodo
Vedere anche domdocument_create_element_ns() e domnode_set_namespace()
Questa funzione accoda un nodo figlio ad un elenco pre-esistente di figli oppure crea una nuova lista di figli. Il nodo figlio può essere creato con funzioni tipo domdocument_create_element(), domdocument_create_text() ecc. oppure usando un qualsiasi altro nodo.
(PHP < 4.3) Prima che sia aggiunto un nuovo nodo questo viene duplicato. Quindi il nuovo nodo è una nuova copia che può essere modificata senza variare il nodo passato alla funzione. Se il nodo ha dei nodi figli, anche questi saranno duplicati, ciò rende facile duplicare grandi parti di un documento XML. Il valore restituito è il nodo figlio accodato. Se si prevede di fare ulteriori modifiche al nodo aggiunto, occorre usare il nodo restituito.
(PHP 4.3.0/4.3.1) Il nuovo nodo figlio nuovo_nodo viene prima rimosso dal contesto esistente, se ne è già un figlio di DomNode. Quindi viene mosso e non più copiato.
(PHP >= 4.3.2) Il nuovo nodo figlio nuovo_nodo viene prima rimosso dal contesto esistente, se ne esiste uno nel documento. Quindi viene mosso e non più copiato. Questo comportamento si attiene alle specifiche W3C. Se si desidera duplicare una grande parte di un documento XML, occorre utilizzare DomNode->clone_node() prima di accodare il nodo.
Nel seguente esempio si accoderà un nuovo nodo ad un documento e si imposterà l'attributo "align" a "left".
Esempio 3. Aggiunta di un nodo figlio
|
Vedere anche domnode_insert_before() e domnode_clone_node().
Questa funzione aggiunge un nodo di pari livello rispetto ad un nodo esistente. Il nodo figlio può essere creato con funzioni del tipo domdocument_create_element(), domdocument_create_text() ecc. oppure utilizzando un'altro nodo.
Prima dell'aggiunta come nuovo nodo fratello, il nodo viene duplicato. Quindi il nuovo nodo figlio è una nuova copia dell'originale e pertanto, può essere modificato senza modificare il nodo di partenza passato alla funzione. Se il nodo fornito, a sua volta, ha dei nodi figli, pure questi saranno duplicati, in questo modo è abbastanza semplice duplicare grandi parti di un documento XML. La funzione restituisce il nodo aggiunto. Se in seguito occorre modificare il nodo fratello che si è aggiunto, occorre utilizzare il nodo restituito.
Questa funzione è stata aggiunta per replicare il comportamento di domnode_append_child() che si ha fino alla versione 4.2 di PHP.
Vedere anche domnode_append_before().
(no version information, might be only in CVS)
DomNode->attributes -- Restituisce la lista degli attributiQuesta funzione restituisce la lista degli attributi se il nodo è di tipo XML_ELEMENT_NODE.
(PHP >= 4.3 solo) Se non si trovano attributi, la funzione restituisce NULL.
(no version information, might be only in CVS)
DomNode->child_nodes -- Restituisce i figli di un nodoRestituisce tutti i nodi figlio del nodo.
Vedere anche domnode_next_sibling() e domnode_previous_sibling().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche domdocument_dump_mem().
(no version information, might be only in CVS)
DomNode->first_child -- Restituisce il primo nodo figlioRestituisce il primo nodo figlio.
(PHP >= 4.3 solo) Se non si trova il primo figlio, si restituisce NULL.
Vedere anche domnode_last_child(), domnode_next_sibling() e domnode_previous_sibling().
(no version information, might be only in CVS)
DomNode->get_content -- Restituisce il contenuto del nodoQuesta funzione restituisce il contenuto del nodo
Esempio 1. Ottenere il contenuto di un nodo
|
(no version information, might be only in CVS)
DomNode->has_attributes -- Verifica se il nodo ha attributiQuesta funzione verifica se il nodo ha attributi.
Vedere anche domnode_has_child_nodes().
(no version information, might be only in CVS)
DomNode->has_child_nodes -- Verifica se esistono nodi figlioQuesta funzione verifica se il nodo ha nodi figlio.
Vedere anche domnode_child_nodes().
(no version information, might be only in CVS)
DomNode->insert_before -- Inserisce un nuovo nodo come figlioQuesta funzione inserisce il nuovo_nodo a destra rispetto al nodo_riferimento. La funzione restituisce il nodo inserito. Occorre utilizzare questo valore se si intende apportare nuove modifiche al nodo appena accodato.
(PHP >= 4.3 solo) Se nuovo_nodo è già parte del documento, prima questo verrà scollegato dal contesto esistente. Se nodo_riferimento vale NULL, allora nuovo_nodo sarà inserito alla fine della lista dei nodi figlio.
La funzione domnode_insert_before() è molto simile a domnode_append_child() come illustrato nel seguente esempio nel quale si ha lo stesso comportamento visto nell'esempio di domnode_append_child().
Esempio 1. Aggiunta di un nodo figlio
|
Vedere anche domnode_append_child().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomNode->last_child -- Restituisce l'ultimo nodo figlio del nodoRestituisce l'ultimo nodo figlio del nodo.
(PHP >= 4.3 solo) Se non si trova l'ultimo figlio, si restituisce NULL.
Vedere anche domnode_first_child(), domnode_next_sibling() e domnode_previous_sibling().
(no version information, might be only in CVS)
DomNode->next_sibling -- Restituisce il successivo fratello del nodoRestituisce il nodo di pari livello successivo al nodo corrente. Se non ci sono nodi successivi la funzione restituisce FALSE (< 4.3) oppure null (>= 4.3). Si può utilizzare questa funzione per passare in rassegna tutti i figli di un nodo, come illustrato nell'esempio.
Esempio 1. Rassegna dei nodi figlio
|
Vedere anche domnode_previous_sibling().
Restituisce il nome del nodo. Il nome ha diversi significati per i differenti tipi di nodi, come sarà illustrato nella tabella seguente.
Tabella 1. Significato dei valori
Tipo | Significato |
---|---|
DomAttribute | valori di attributo |
DomAttribute | |
DomCDataSection | #cdata-section |
DomComment | #comment |
DomDocument | #document |
DomDocumentType | nome del tipo documento |
DomElement | nome tag |
DomEntity | nome di entittà |
DomEntityReference | nome di entità di riferimento |
DomNotation | nome della notazione |
DomProcessingInstruction | target |
DomText | #text |
La funzione restituisce il tipo di nodo. L'elenco di tutti i tipi possibili sono elencati in una tabella nell'introduzione.
(no version information, might be only in CVS)
DomNode->node_value -- Restituisce il valore di un nodoLa funzione restituisce il valore di un nodo. Il valore ha diversi significati per i diversi tipi di nodi, come illustrato nella seguente tabella.
Tabella 1. Significato dei valori
Tipo | Significato |
---|---|
DomAttribute | valori di un attributo |
DomAttribute | |
DomCDataSection | contenuto |
DomComment | contenuto del commento |
DomDocument | null |
DomDocumentType | null |
DomElement | null |
DomEntity | null |
DomEntityReference | null |
DomNotation | null |
DomProcessingInstruction | l'intero contenuto senza destinatario |
DomText | contenuto del testo |
(no version information, might be only in CVS)
DomNode->owner_document -- Restituisce il documento a cui appartiene questo nodoQuesta funzione restituisce il documento a cui appartiene questo nodo.
L'esempio seguente produce due liste uguali di nodi figli.
Vedere anche domnode_insert_before().
(no version information, might be only in CVS)
DomNode->parent_node -- Restituisce il genitore del nodoQuesta funzione restituisce il genitore del nodo.
(PHP >= 4.3 solo) Se non si trova il nodo genitore, si restituisce NULL.
L'esempio seguente visualizza due liste simili di nodi figli.
(no version information, might be only in CVS)
DomNode->prefix -- Restituisce lo spazio dei nomi prefisso al nodo(no version information, might be only in CVS)
DomNode->previous_sibling -- Restituisce il nodo fratello precedenteQuesta funzione restituisce il nodo fratello precedente rispetto al nodo corrente. Se non vi sono nodi precedenti la funzione restituisce FALSE (< 4.3) oppure null (>= 4.3). Si può utilizzare questa funzione per attraversare tutti i nodi figli come illustrato nell'esempio.
Vedere anche domnode_next_sibling().
(no version information, might be only in CVS)
DomNode->remove_child -- Rimuove un nodo figlio dalla lista dei figliQuesta funzione rimuove un nodo figlio dalla lista dei figli. Se il nodo non può essere rimosso, oppure non è un nodo figlio la funzione restituisce FALSE. Se il nodo figlio può essere rimosso la funzione restituisce il vecchio nodo.
Esempio 1. Rimozione di un nodo figlio
|
Vedere anche domnode_append_child().
(PHP 4.2) Questa funzione sostituisce il nodo vecchio_nodo con il parametro nuovo_nodo. Se il nuovo nodo è già un figlio questo non verrà aggiunto una seconda volta. Se la funzione non riesce a trovare il vecchio nodo, restituisce FALSE. Se, invece, la sostituzione riesce, la funzione restituisce il vecchio nodo.
(PHP 4.3) Questa funzione sostituisce il nodo figlio vecchio_nodo con il parametro nuovo_nodo, anche se il nuovo nodo è già un figlio di DomNode. Se nuovo_nodo era già presente nel documento, prima questo viene rimosso dal contesto esistente. Se la funzione non riesce a trovare il vecchio nodo, restituisce FALSE. Se la sostituzione riesce, la funzione restituisce il vecchio nodo. (Questo comportamento rispecchia le specifiche W3C).
Vedere anche domnode_append_child()
(PHP 4.2) Questa funzione sostituisce il nodo esistente con il nodo passato nel parametro nuovo_nodo. Qualora nuovo_nodo abbia un genitore, il nodo viene copiato in modo da non inserire nel documento due volte un nodo già presente. In questo modo si costringe a fare tutte le modifiche al nodo prima della sostituzione o di riprendere il nodo inserito in una fase successiva con funzioni tipo domnode_first_child(), domnode_child_nodes() ecc..
(PHP 4.3) Questa funzione sostituisce il nodo con il nuovo nodo passato. Questo non viene più copiato. Se nuovo_nodo è già inserito nel documento, prima viene rimosso dal contesto esistente. Se la sostituzione riesce, la funzione restituisce il vecchio nodo.
Vedere anche domnode_append_child()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Imposta il nome del nodo.
Vedere anche domnode_node_name().
(no version information, might be only in CVS)
DomNode->set_namespace -- Imposta lo spazio dei nomi del nodoImposta lo spazio dei nomi del nodo a uri. Se esiste già uno spazio dei nomi impostato con il medesimo uri in uno dei nodi genitore, si utilizza il prefisso di questo, altrimenti si utilizza il prefisso passato con il parametro opzionale prefix, oppure se ne genera uno casuale.
Vedere anche domdocument_create_element_ns() e domnode_add_namespace()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomProcessingInstruction->data -- Restituisce i dati di un nodo PI
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomProcessingInstruction->target -- Restituisce il target di un nodo PI
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomXsltStylesheet->process -- Applica una trasformazione XSLT ad un oggetto DomDocumentAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche domxml_xslt_stylesheet(), domxml_xslt_stylesheet_file() e domxml_xslt_stylesheet_doc().
(no version information, might be only in CVS)
DomXsltStylesheet->result_dump_file -- Scarica il risultato di una trasformazione XSLT in un fileAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Questa funzione è disponibile solo a partire dalla versione 4.3 di PHP.
Poichè DomXsltStylesheet->process() restituisce sempre un documento XML ben formato, a prescindere da quale metodo di output sia specificato in <xsl:output> od in attributi/elementi simili, questa non è di grande utilità se si desidera ottenere in output un testo normale o HTML. Al contrario questa funzione rispetta <xsl:output method="html|text"> e le altre direttive di output. Vedere l'esempio per dettagli su come usare la funzione.
Vedere anche domxml_xslt_result_dump_mem() e domxml_xslt_process()
(no version information, might be only in CVS)
DomXsltStylesheet->result_dump_mem -- Scarica il risultato di una trasformazione XSLT in una stringaAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Questa funzione è disponibile solo a partire dalla versione 4.3 di PHP.
Poichè DomXsltStylesheet->process() restituisce sempre un documento XML ben formato, a prescindere da quale metodo di output sia specificato in <xsl:output> od in attributi/elementi simili, questa non è di grande utilità se si desidera ottenere in output un testo normale o HTML. Al contrario questa funzione rispetta <xsl:output method="html|text"> e le altre direttive di output. Vedere l'esempio per dettagli su come usare la funzione.
Vedere anche domxml_xslt_result_dump_file() e domxml_xslt_process()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Crea da zero un nuovo documento DOM e lo restituisce.
Vedere anche domdocument_add_root()
Questa funzione analizza il documento XML presente nel file nome_file e restituisce un oggetto della classe "Dom document", con le proprietà indicate. Il file viene aperto in modalità di sola lettura.
Vedere anche domxml_open_mem() e domxml_new_doc().
La funzione analizza il documento XML contenuto in str e restituisce un oggetto della classe "Dom document", avente le proprietà elencate. Queste funzioni, domxml_open_file() e domxml_new_doc(), devono essere richiamate prima di ogni altra funzione.
Vedere anche domxml_open_file() e domxml_new_doc().
Questa funzione restituisce la versione della libreria XML attualmente utilizzata.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Questa funzione analizza il documento XML contenuto nella stringa str e restituisce il documento analizzato come un albero di oggetti PHP. Questa funzione è isolata rispetto alle altre, ciò significa che non si può accedere all'albero utilizzando le altre funzioni. Modificare l'albero, ad esempio aggiungendovi un nodo, non ha senso poichè al momento non vi è modo di salvare il documento in un file XML. Tuttavia questa funzione può essere utile se si desidera leggere un file ed analizzarne il contenuto.
(PHP 4 >= 4.2.0)
domxml_xslt_stylesheet_doc -- Crea un oggetto DomXsltStylesheet da un oggetto DomDocument.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche domxsltstylesheet->process(), domxml_xslt_stylesheet() e domxml_xslt_stylesheet_file()
(PHP 4 >= 4.2.0)
domxml_xslt_stylesheet_file -- Crea un oggetto DomXsltStylesheet da un file con un documento XSLAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche domxsltstylesheet->process(), domxml_xslt_stylesheet() e domxml_xslt_stylesheet_doc().
(PHP 4 >= 4.2.0)
domxml_xslt_stylesheet -- Crea un oggetto DomXsltStylesheet da un documento XML contenuto in una stringaAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche domxsltstylesheet->process(), domxml_xslt_stylesheet_file() e domxml_xslt_stylesheet_doc()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Vedere anche xpath_eval().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Si può specificare il parametro opzionale contextnode per eseguire delle query XPath relative.
Vedere anche xpath_new_context().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Vedere anche xpath_eval().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Le seguenti sono le funzioni per la gestione degli errori ed il logging. Esse permettono di definire regole personalizzate per la gestione degli errori, e anche di modificarne la modalità della gestione stessa. Ciò permette di cambiare ed integrare i messaggi di errore adattandoli alle vostre esigenze.
Grazie alle funzioni di logging, è possibile inviare messaggi direttamente ad altre macchine, alla posta elettronica (o ad un gateway pager o di posta elettronica!), ai log di sistema, ecc., in modo da effettuare il log e controllare selettivamente le parti più importanti delle vostre applicazioni e siti web.
Le funzioni di restituzione dell'errore consentono la personalizzazione del livello e del tipo di errore, dal semplice avviso sino a funzioni personalizzate restituite durante gli errori.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Parametri di configurazione per la gestione degli errori e dei log
Nome | Default | Modificabile |
---|---|---|
error_reporting | E_ALL & ~E_NOTICE | PHP_INI_ALL |
display_errors | "1" | PHP_INI_ALL |
display_startup_errors | "0" | PHP_INI_ALL |
log_errors | "0" | PHP_INI_ALL |
log_errors_max_len | "1024" | PHP_INI_ALL |
ignore_repeated_errors | "0" | PHP_INI_ALL |
ignore_repeated_source | "0" | PHP_INI_ALL |
report_memleaks | "1" | PHP_INI_ALL |
track_errors | "0" | PHP_INI_ALL |
html_errors | "1" | PHP_INI_ALL |
docref_root | "" | PHP_INI_ALL |
docref_ext | "" | PHP_INI_ALL |
error_prepend_string | NULL | PHP_INI_ALL |
error_append_string | NULL | PHP_INI_ALL |
error_log | NULL | PHP_INI_ALL |
warn_plus_overloading | NULL | PHP_INI?? |
Breve descrizione dei parametri di configurazione.
Imposta il livello di errore da visualizzare. Il parametro è sia un intero rappresentante un campo di bit, o una costante nominale. I livelli ri report degli errori e le costanti previste sono descritte in Costanti Predefinite, e in php.ini. Per impostare il livello in fase di esecuzione utilizzare la funzione error_reporting(). Vedere anche il parametro display_errors.
In PHP 4 e PHP 5 il valore di default è E_ALL & ~E_NOTICE. Questa impostazione non visualizza gli errori di livello E_NOTICE. Tuttavia può essere comodo visualizzare questi messaggi in fase di sviluppo.
Nota: Abilitare E_NOTICE durante la fase di sviluppo ha dei benefici. Ad esempio per scopi di debug: i messaggi di tipo NOTICE avvisano su possibili bug nel codice. L'uso di variabili non assegnate, ad esempio, viene rilevato con questo livello di errore. Particolare che è molto utile per trovare errori di battitura e risparmiare tempo in fase di debug. I messaggi di tipo NOTICE segnalano il codice scritto con un cattivo stile. Ad esempio, $arr[item] è meglio che sia scritto come $arr['item'] poichè il PHP tenta di trattare "item" come costante. Se non esiste una simile costante, il PHP presume che si tratti dell'indice di una matrice.
Nota: Nel PHP 5 è stato introdotto un nuovo livello di errore E_STRICT. Come E_STRICT non viene incluso nel E_ALL e, pertanto, occorre abilitarlo in modo esplicito. Abilitare E_STRICT durante la fase di sviluppo porta alcuni benefici. Questa casistica di messaggi servono ad aiutare le più recenti, e consigliate, metodologie di programamzione, avvisando, ad esempio, sull'uso di funzioni deprecate.
In PHP 3 l'impostazione di default è (E_ERROR | E_WARNING | E_PARSE), che significa la medesima cosa. Occorre rilevare, tuttavia, che le costanti non sono supportate nel php3.ini del PHP 3, e pertanto occorre utilizzare la codifica numerica, che corrisponde a 7.
Questo parametro determina se gli errori devono essere visualizzati sullo schermo come parte dell'output o se devono essere nascosti all'utente.
Nota: Questa opzione è di supporto allo sviluppo, e non deve mai essere utilizzata nei sistemi di produzione (ad esempio collegati ad Internet).
Anche quando è abilitata la visualizzazione degli errori, gli errori che avvengono durante l'avvio del PHP non sono visualizzati. Si raccomanda di mantenere display_startup_errors impostato a off, tranne che nelle fasi di sviluppo.
Indica se i messaggi di errore debbano essere registrati nell'errorlog del server o in error_log. Questo opzione dipende dal server.
Nota: Sui siti di produzione si raccomanda di utilizzare la registrazione degli errori piuttosto che visualizzarli.
Imposta la massima lunghezza del log degli errori in byte. Nell'errorlog error_log viene indicata anche la fonte del messaggio. Il valore di default è 1024 e 0 indica di non applicare alcuna limitazione.
Do not log repeated messages. Repeated errors must occur in the same file on the same line until ignore_repeated_source is set true.
Ignore source of message when ignoring repeated messages. When this setting is On you will not log errors with repeated messages from different files or sourcelines.
If this parameter is set to Off, then memory leaks will not be shown (on stdout or in the log). This has only effect in a debug compile, and if error_reporting includes E_WARNING in the allowed list
If enabled, the last error message will always be present in the variable $php_errormsg.
Turn off HTML tags in error messages. The new format for HTML errors produces clickable messages that direct the user to a page describing the error or function in causing the error. These references are affected by docref_root and docref_ext.
The new error format contains a reference to a page describing the error or function 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).
See docref_root.
Nota: The value of docref_ext must begin with a dot '.'.
String to output before an error message.
String to output after an error message.
Name of the file where script errors should be logged. If the special value syslog is used, the errors are sent to the system logger instead. On Unix, this means syslog(3) and on Windows NT it means the event log. The system logger is not supported on Windows 95. See also: syslog().
If enabled, this option makes PHP output a warning when the plus (+) operator is used on strings. This is to make it easier to find scripts that need to be rewritten to using the string concatenator instead (.).
Le costanti qui elencate sono sempre disponibili in quanto parte del core di PHP.
Nota: Si possono utilizzare queste constanti in php.ini ma non all'esterno del PHP, tipo in in httpd.conf, dove occorre utilizzare in valori.
Tabella 2. Errori e log
Valore | Costante | Descrizione | Note |
---|---|---|---|
1 | E_ERROR (integer) | Errori fatali di esecuzione. Questi indicano errori che non si possono ignorare, come, ad esempio, errori di allocazione della memoria. L'esecuzione dello script è bloccata. | |
2 | E_WARNING (integer) | Warning di esecuzione (errori non fatali). L'esecuzione dello script non viene bloccata. | |
4 | E_PARSE (integer) | Errore di parsing in fase di compila. Essendo errori di parsing sono generati dal parser del codice PHP. | |
8 | E_NOTICE (integer) | Informazioni di esecuzione. Questo messaggio indica che lo script ha incontrato qualcosa che potrebbe indicare un errore, ma è una sitauzione che può accadere durante una normale esecuzione di uno script. | |
16 | E_CORE_ERROR (integer) | Errori fatali che accadono durante la fase di inizializzazione del PHP. Questo è come un E_ERROR, tranne che viene generato dall'interno del PHP. | dal PHP 4 |
32 | E_CORE_WARNING (integer) | Warning (errore non fatale) che accade durante la fase di inizializzazione del PHP. Questo è come un E_WARNING, tranne che viene generato dall'interno del PHP. | dal PHP 4 |
64 | E_COMPILE_ERROR (integer) | Errore fatale di compila. Questo è come E_ERROR, tranne che viene generato dal motore Zend. | dal PHP 4 |
128 | E_COMPILE_WARNING (integer) | Warning di compila (errore non fatale). Questo è come E_WARNING, tranne che viene generato dal motore Zend. | dal PHP 4 |
256 | E_USER_ERROR (integer) | Messaggio di errore generato dall'utente. Questo è come E_ERROR, tranne che viene generato dal codice PHP tramite la funzione trigger_error(). | dal PHP 4 |
512 | E_USER_WARNING (integer) | Messaggio di warning generato dall'utente. Questo è come E_WARNING,tranne che viene generato dal codice PHP tramite la funzione trigger_error(). | dal PHP 4 |
1024 | E_USER_NOTICE (integer) | Messaggio di informazione generato dall'utente. Questo è come E_NOTICE, tranne che viene generato dal codice PHP tramite la funzione trigger_error(). | dal PHP 4 |
2047 | E_ALL (integer) | Tutti gli errori ed i warning supportati tranne quelli di livello E_STRICT. | |
2048 | E_STRICT (integer) | Informazione di esecuzione. Abilitare questo messaggio per avere dal PHP suggerimenti sulle modifiche da apportare al codice per avere la migliore interoperabilità e compatibilità del codice. | dal PHP 5 |
I valori precedenti (sia numerici, sia simbolici) possono essere utilizzati per costruire delle maschere di bit che indichino quali errori visualizzare. Si può utilizzare gli operatori sui bit per combinare questi valori o per mascherare certi tipi di errori. Fare attenzione che soltanto '|', '~', '!', '^' e '&' sono compresi dal php.ini, e che nessun operatore sui bit è gestito dal php3.ini.
Di seguito sarà illustrato un esempio di utilizzo delle procedure di gestione dell'errore in PHP. Qui si definisce una funzione di gestione dell'errore che registra le informazioni in un file (in formato XML) e invia tramite e-mail allo sviluppare dei messaggi in caso di errori critici.
Esempio 1. Esempio dell'utilizzo di della gestione degli erorri in uno script
|
debug_backtrace() 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()
Name | Type | Description |
---|---|---|
function | string | The current function name. See also __FUNCTION__. |
line | integer | The current line number. See also __LINE__. |
file | string | The current file name. See also __FILE__. |
class | string | The current class name. See also __CLASS__ |
type | string | The current call type. If a method call, "->" is returned. If a static method call, "::" is returned. If a function call, nothing is returned. |
args | array | 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
Results when executing /tmp/b.php:
|
See also trigger_error() and debug_print_backtrace().
debug_print_backtrace() prints a PHP backtrace.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
See also debug_backtrace().
Invia un messaggio di errore la log del server web, ad una porta TCP o ad un file. Il primo parametro, messaggio, è il messaggio di errore che deve essere registrato. Il secondo parametro, tipo_messaggio indica la destinazione del messaggio:
Tabella 1. error_log() tipi di log
0 | messaggio è inviato al log di sistema di PHP, utilizzando il sistema di log del Sistema Operativo o un file, a seconda di come sia impostata la direttiva di configurazione error_log. |
1 | messaggio è inviato via posta elettronica all'indirizzo indicato nel parametro destinazione parameter. Questo è l'unico tipo di messaggio nel quale viene usato il quarto parametro, headers_extra. Questo tipo di messaggio utilizza la stessa funzione interna di mail(). |
2 | messaggio viene inviato attraverso la connessione di debug di PHP. Questa opzione è disponibile solo nel caso che il debug remoto sia stato abilitato. In questo caso, il parametro destinazione specifica il nome dell'host o l'indirizzo IP e opzionalmente, numero di porta, del socket che riceverà l'informazione di debug. |
3 | messaggio è aggiunto al file destinazione. |
Avvertimento |
Il debug remoto via TCP/IP è una caratteristica di PHP 3 non disponibile in PHP 4. |
Esempio 1. error_log() esempi
|
Definisce il livello di restituzione di errore di PHP e ritorna il vecchio livello. Il livello di restituzione dell'errore può essere una maschera di bit o una costante named. L'utilizzo delle costanti named è caldamente consigliato per assicurare la compatibilità con versioni future. All'aggiungere di livelli di errore, la gamma degli interi viene incrementata, perciò vecchi livelli di errore basati sull'intero non si comporteranno sempre come ci si aspetta.
Esempio 1. Error Integer changes
|
Tabella 1. error_reporting() valori dei bit
valore | costante |
---|---|
1 | E_ERROR |
2 | E_WARNING |
4 | E_PARSE |
8 | E_NOTICE |
16 | E_CORE_ERROR |
32 | E_CORE_WARNING |
64 | E_COMPILE_ERROR |
128 | E_COMPILE_WARNING |
256 | E_USER_ERROR |
512 | E_USER_WARNING |
1024 | E_USER_NOTICE |
2047 | E_ALL |
Esempio 2. esempi error_reporting()
|
(PHP 4 >= 4.0.1, PHP 5)
restore_error_handler -- Ripristina la precedente funzione di gestione dell'erroreUtilizzata dopo la modifica della funzione di gestione degli errori con set_error_handler(), per ripristinare la precedente modalità di gestione (che può essere quella di configurazione o una definita dall'utente).
Vedere anche error_reporting(), set_error_handler(), trigger_error(), user_error()
(PHP 4 >= 4.0.1, PHP 5)
set_error_handler -- Configura una funzione di gestione dell'errore definita dall'utente.Configura una funzione utente (error_handler per gestire gli errori in uno script. Restituisce, se esistente, il precedente gestore degli errori, o FALSE in caso di errore. Questa funzione può essere utilizzata per definire un sistema personalizzato di gestione degli errori durante l'esecuzione, per esempio in applicazioni dove sia necessario svuotare dati o file in caso di un determinato errore critico, o quando sia necessario, in determinate condizioni, attivare un errore (con trigger_error())
La funzione utente richiede 2 parametri: il codice errore e una stringa descrittiva dell'errore. Da PHP 4.0.2, è possibile opzionalmente fornire altri 3 parametri aggiuntivi: il nome del file, il numero di riga e il contesto dove è avvenuto l'errore (un array che punto alla tabella dei simboli attiva nel punto in cui è avvenuto l'errore).
L'esempio sottostante mostra la gestione delle eccezioni interne attivando gli errori e gestendoli tramite una funzione definita dall'utente:
Esempio 1. Gestione errori con set_error_handler() e trigger_error()
|
vector a Array ( [0] => 2 [1] => 3 [2] => foo [3] => 5.5 [4] => 43.3 [5] => 21.11 ) ---- vector b - a warning (b = log(PI) * a) <b>WARNING</b> [1024] Value at position 2 is not a number, using 0 (zero)<br> Array ( [0] => 2.2894597716988 [1] => 3.4341896575482 [2] => 0 [3] => 6.2960143721717 [4] => 49.566804057279 [5] => 24.165247890281 ) ---- vector c - an error <b>ERROR</b> [512] Incorrect input vector, array of values expected<br> NULL ---- vector d - fatal error <b>FATAL</b> [256] log(x) for x <= 0 is undefined, you used: scale = -2.5<br> Fatal error in line 36 of file trigger_error.php, PHP 4.0.2 (Linux)<br> Aborting...<br> |
E' importante ricordare che il gestore degli errori standard di PHP viene completamente saltato. La configurazione di error_reporting() non avrà effetto e il vostro gestore di errore sarà richiamato senza considerarla - in ogni caso sarà possibile leggere il valore corrente di error_reporting() ed agire di conseguenza. E' di particolare rilevanza il fatto che questo valore sarà 0 se la riga che causa l'errore viene precedura dall' operatore di controllo errore @.
Notare anche che è vostra responsabilità definire die() se necessario. Se la funzione di gestione dell'errore ritorna, lo script continerà l'esecuzione con la riga seguente a quella che ha causato l'errore.
Vedere anche error_reporting(), restore_error_handler(), trigger_error(), user_error()
(PHP 4 >= 4.0.1, PHP 5)
trigger_error -- Genera un messaggio a livello utente di errore/avviso/avvertimento messageUtilizzata per attivare una condizione di errore utente, può essere usata in congiunzione con il gestore di errore interno, o con una funzione definita dall'utente che sia configurata per essere il nuovo gestore di errore con (set_error_handler()). Funziona soltanto con la famiglia di costanti E_USER, e punta alla predefinita E_USER_NOTICE.
Questa funzione è utile quando sia necessario generare una particolare risposta ad un'eccezione durante l'esecuzione. Per esempio:
Nota: Vedere set_error_handler() per un esempio più esplicativo.
Vedere anche error_reporting(), set_error_handler(), restore_error_handler(), user_error()
Questo è un alias per la funzione trigger_error().
Vedere anche error_reporting(), set_error_handler(), restore_error_handler() e trigger_error()
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.
This extension uses the functions of the FAM library, devoloped by SGI. Therefore you have to download and install the FAM library.
To use PHP's FAM support you must compile PHP --with-fam[=DIR] where DIR is the location of the directory containing the lib and include directories.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 1. FAM event constants
Constant | Description |
---|---|
FAMChanged (integer) | Some value which can be obtained with fstat(1) changed for a file or directory. |
FAMDeleted (integer) | A file or directory was deleted or renamed. |
FAMStartExecuting (integer) | An executable file started executing. |
FAMStopExecuting (integer) | An executable file that was running finished. |
FAMCreated (integer) | A file was created in a directory. |
FAMMoved (integer) | This event never occurs. |
FAMAcknowledge (integer) | An event in response to fam_cancel_monitor(). |
FAMExists (integer) | An event upon request to monitor a file or directory. When a directory is monitored, an event for that directory and every file contained in that directory is issued. |
FAMEndExist (integer) | Event after the last FAMEExists event. |
fam_cancel_monitor() terminates monitoring on a resource previously requested using one of the fam_monitor_...(). In addition an FAMAcknowledge event occurs.
See also fam_monitor_file(), fam_monitor_directory(), fam_monitor_collection(), and fam_suspend_monitor()
fam_close() closes a connection to the FAM service previously opened using fam_open().
fam_monitor_collection() requests monitoring for a collection of files within a directory. The actual files to be monitored are specified by a directory path in dirname, the maximum search depth starting from this directory and a shell pattern mask restricting the file names to look for.
A FAM event will be generated whenever the status of the files change. The possible event codes are described in detail in the constants part of this section.
See also fam_monitor_file(), fam_monitor_directory(), fam_cancel_monitor(), fam_suspend_monitor(), and fam_resume_monitor().
fam_monitor_directory() requests monitoring for a directory and all contained files. A FAM event will be generated whenever the status of the directory (i.e. the result of function stat() on that directory) or its content (i.e. the results of readdir()) change.
The possible event codes are described in detail in the constants part of this section.
See also fam_monitor_file(), fam_monitor_collection(), fam_cancel_monitor(), fam_suspend_monitor(), and fam_resume_monitor().
fam_monitor_file() requests monitoring for a single file. A FAM event will be generated whenever the file status (i.e. the result of function stat() on that file) changes.
The possible event codes are described in detail in the constants part of this section.
See also fam_monitor_directory(), fam_monitor_collection(), fam_cancel_monitor(), fam_suspend_monitor(), and fam_resume_monitor().
fam_next_event() returns the next pending FAM event. The function will block until an event is available which can be checked for using fam_pending().
fam_next_event() will return an array that contains a FAM event code in element 'code', the path of the file this event applies to in element 'filename' and optionally a hostname in element 'hostname'.
The possible event codes are described in detail in the constants part of this section.
See also fam_pending().
fam_open() opens a connection to the FAM service daemon. The optional parameter appname should be set to a string identifying the application for logging reasons.
See also fam_close().
fam_pending() returns TRUE if events are available to be fetched using fam_next_event().
See also fam_next_event().
fam_resume_monitor() resumes monitoring of a resource previously suspend using fam_suspend_monitor().
See also fam_suspend_monitor().
fam_suspend_monitor() temporarily suspend monitoring of a resource previously requested using one of the fam_monitor_...() functions. Monitoring can later be continued using fam_resume_monitor() without the need of requesting a complete new monitor.
See also fam_resume_monitor(), and fam_cancel_monitor().
Queste funzioni permettono di accedere ai servers del database FrontBase. Maggiori informazioni su FrontBase: http://www.frontbase.com/.
Documentazione su FrontBase : http://www.frontbase.com/cgi-bin/WebObjects/FrontBase.woa/wa/productsPage?currentPage=Documentation.
Il supporto Frontbase è stato aggiunto dal PHP 4.0.6.
Per potere utilizzare queste funzioni occorre installare o il server FrontBase o, al limite, le librerie fbsql client. Si può ottenere FrontBase da http://www.frontbase.com/.
Affinché queste funzioni siano disponibili è necessario compilare php con il supporto fbsql usando l' opzione --with-fbsql[=DIR].Se si usa questa opzione senza specificare il percorso a fbsql, php cercherà le librerie client di fbsql nella cartella di default specificata nell'istallazione di FrontBase, a seconda del sistema operativo. Se si installa FrontBase in una cartella non standard è necessario specificare sempre il percorso a fbsql: --with-fbsql=/path/to/fbsql. In questo modo si forzerà php ad usare le librerie client installate da FrontBase, evitando ogni conflitto.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Opzioni di configurazione per FrontBase
Nome | Default | Modificabile |
---|---|---|
fbsql.allow_persistent | "1" | PHP_INI_SYSTEM |
fbsql.generate_warnings | "0" | PHP_INI_SYSTEM |
fbsql.autocommit | "1" | PHP_INI_SYSTEM |
fbsql.max_persistent | "-1" | PHP_INI_SYSTEM |
fbsql.max_links | "128" | PHP_INI_SYSTEM |
fbsql.max_connections | "128" | PHP_INI_SYSTEM |
fbsql.max_results | "128" | PHP_INI_SYSTEM |
fbsql.batchSize | "1000" | PHP_INI_SYSTEM |
fbsql.default_host | NULL | PHP_INI_SYSTEM |
fbsql.default_user | "_SYSTEM" | PHP_INI_SYSTEM |
fbsql.default_password | "" | PHP_INI_SYSTEM |
fbsql.default_database | "" | PHP_INI_SYSTEM |
fbsql.default_database_password | "" | PHP_INI_SYSTEM |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
(PHP 4 >= 4.0.6, PHP 5)
fbsql_affected_rows -- Restituisce il numero di righe (tuple) interessate nella precedente operazione di FrontBasefbsql_affected_rows() restituisce il numero di righe interessate dall'ultima query INSERT, UPDATE or DELETE associata al parametro link_identifier. Se tale parametro non è stato specificato, sarà usata l'ultima connessione aperta da fbsql_connect().
Nota: Se si stanno usando le transazioni, è necessario chiamare la funzione fbsql_affected_rows() dopo una query INSERT, UPDATE, or DELETE, non dopo la chiusura della transazione (commit).
Se l'ultima query è un istruzione DELETE senza clausola WHERE, tutte le righe verranno cancellate dalla tabella e la funzione restituirà il valore 0 (zero).
Nota: Se si utilizza l'istruzione UPDATE, FrontBase non aggiornerà le colonne in cui il valore nuovo è uguale a quello vecchio. Quindi esiste la possibilità che fbsql_affected_rows() sia diverso dal numero di righe realmente interessate dalla query.
Se l'ultima query fallisce la funzione restituisce -1.
Vedere anche: fbsql_num_rows().
fbsql_autocommit() restituisce lo stato corrente di autocommit. Se è stato specificato il parametro opzionale OnOff, lo stato di autocommit verrà cambiato. Impostando il parametro OnOff su TRUE ogni istruzione verrà eseguita automaticamente, in caso di assenza di errori. Impostandolo su FALSE l'utente dovrà eseguire la transazione richiamando le funzioni fbsql_commit() o fbsql_rollback().
Vedere anche: fbsql_commit() e fbsql_rollback()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
fbsql_change_user -- Cambia l'identità dell'utente connesso con una connessione attivafbsql_change_user() Cambia l'identità dell'utente connesso con una connessione attiva, o con la connessione specificata dal parametro opzionale link_identifier. Se è stato specificato un database, dopo che l'identità dell'utente sarà stata cambiata, questo diventerà il database attivo . Se l'autorizzazione del nuovo utente fallisce, rimarrà attiva l'identità dell'utente corrente.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce: TRUE in caso di successo, FALSE in caso di fallimento.
fbsql_close() chiude la connessione al server FrontBase associata ad uno specificato link identifier. Se il link_identifier non fosse specificato, verrebbe chiusa l'ultima connessione aperta.
Non è sempre necessario usare fbsql_close() nel caso di connessioni non permanenti, esse verranno chiuse automaticamente alla fine dell'esecuzione dello script.
Vedere anche: fbsql_connect() e fbsql_pconnect().
restituisce: TRUE in caso di successo, FALSE in caso di fallimento.
fbsql_commit() esegue la transazione corrente scrivendo tutti gli aggiornamenti pendenti, cancella il disco e sblocca tutte le righe della tabella bloccata dalla transazione. Questo comando è necessario solo nel caso in cui autocommit fosse impostato su false.
Vedere anche: fbsql_autocommit() e fbsql_rollback()
Restituisce un valore di link_identifier positivo in caso di successo, o un messaggio di errore in caso di fallimento.
fbsql_connect() Apre una connessione al Server FrontBase.Se i parametri opzionali non sono specificati verranno usati i valori seguenti come default: hostname = 'NULL', username = '_SYSTEM' e password = empty password.
Se si richiamasse, una seconda volta, la funzione fbsql_connect() con gli stessi argomenti, non si creerebbe una nuova connessione,ma verrebbe restituito il valore di link_identifier della connessione già aperta.
La connessione al server si chiuderà alla fine dello script, a meno che non venga chiusa in anticipo richiamando esplicitamente la funzione fbsql_close().
Vedere anche fbsql_pconnect() e fbsql_close().
Restituisce un handle al blob appena creato.
La funzione fbsql_create_blob() crea un campo blob a partire da blob_data. L'handle restituito può essere utilizzato con i comandi di inserimento e di aggiornamento dei blob nel database.
Esempio 1. Esempio di uso di fbsql_create_blob()
|
Vedere anche: fbsql_create_clob(), fbsql_read_blob(), fbsql_read_clob() e fbsql_set_lob_mode().
Restituisce un handle al CLOB appena creato.
La funzione fbsql_create_clob() crea un campo clob a partire da clob_data. L'handle restituito può essere utilizzato con i comandi di inserimento e di aggiornamento dei clob nel database.
Esempio 1. Esempio di uso di fbsql_create_clob()
|
Vedere anche: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob() e fbsql_set_lob_mode().
fbsql_create_db() crea un nuovo database FrontBase sul server, identificato dal parametro link_identifier.
Vedere anche fbsql_drop_db().
Restituisce: TRUE in caso di successo, FALSE in caso di fallimento.
fbsql_data_seek() sposta il puntatore interno al risultato FrontBase associato con uno specificato indice in modo che punti ad un numero di riga specificata . La chiamata successiva alla funzionefbsql_fetch_row() restituirà la riga richiesta.
row_number comincia a contare da 0.
Esempio 1. fbsql_data_seek()
|
(PHP 4 >= 4.0.6, PHP 5)
fbsql_database_password -- Imposta o ricerca la password di un database FrontBase.Restituisce: La password del database identificato dal parametro link_identifier.
fbsql_database_password() imposta e ricerca la password del database corrente. Se il secondo parametro, opzionale (database_password), è stato specificato la funzione imposta, sul server, il valore del parametro come password del database identificato dal parametro link_identifier. Se il link_identifier non è specificato, verrà utilizzata l'ultima connessione aperta. Se nessuna connessione è aperta, la funzione tenterà di aprirne una come se la funzione fbsql_connect() fosse chiamata, e userà quella.
Questa funzione non modifica la password nel database e neppure è in grado ti recuperare la password di un database.
Esempio 1. Esempio di fbsql_create_clob()
|
Vedere anche: fbsql_connect(), fbsql_pconnect() e fbsql_select_db().
(PHP 4 >= 4.0.6, PHP 5)
fbsql_database -- Imposta oppure ottiene il nome del database usato per la connessione
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce: un indice FrontBase positivo come risultato della query, o FALSE in caso di errore.
fbsql_db_query() seleziona un database ed esegue la query su di esso.Se il parametro opzionale link_identifier non è stato specificato, la funzione ne cercherà una già aperta nel FrontBase server, in caso non ne trovasse alcuna aprirà una nuova connessione come se la funzione fbsql_connect() fosse chiamta senza argomenti.
Vedere anche: fbsql_connect().
Restituisce: un valore intero con lo stato corrente.
fbsql_db_status() richiede lo stato corrente del database specificato da database_name. Se il link_identifier viene omesso verrà usato quello in uso.
Il valore restituito potrà essere uno delle seguenti costanti:
FALSE - L'exec handler del host era invalido. Questo errore si presenta quando la connessione avviene direttamente al database, tramite il link_identifier, usando un numero di porta. FBExec può essere disponibile sul server ma nessuna connessione è stata creata.
FBSQL_UNKNOWN - Lo stato è sconosciuto.
FBSQL_STOPPED - Il database non è attivo. Usare fbsql_start_db() per attivare il database.
FBSQL_STARTING - Il database è in fase di attivazione.
FBSQL_RUNNING - Il database è attivo e può essere usato per eseguire operazioni SQL.
FBSQL_STOPPING - Il database é in fase di disattivazione.
FBSQL_NOEXEC - FBExec non è attivo sul server quindi non è possibile conoscere lo stato del database.
Vedere anche: fbsql_start_db() e fbsql_stop_db().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
fbsql_drop_db() procede con l'eliminazione di un intero database dal server associato all'identificatore di link.
(PHP 4 >= 4.0.6, PHP 5)
fbsql_errno -- Ritorna il valore numerico del messaggio di errore emesso dalla precedente operazione FrontBase.Restituisce il numero di errore dell'ultima funzione fbsql, 0 (zero) se non ci sono stati errori.
Gli errori vengono restituiti dal database fbsql senza visualizzare i warnings. Usare fbsql_errno() per ricevere codice dell'errore. Da notare che questa funzione restituisce solamente il codice di errore proveniente dalla più recente esecuzione di una funzione fbsql (escludendo fbsql_error() e fbsql_errno()),così se si vuole usarla, assicurarsi di controllare il valore prima di richiamare un'altra funzione fbsql.
<?php fbsql_connect("marliesle"); echo fbsql_errno().": ".fbsql_error()."<BR>"; fbsql_select_db("nonexistentdb"); echo fbsql_errno().": ".fbsql_error()."<BR>"; $conn = fbsql_query("SELECT * FROM nonexistenttable;"); echo fbsql_errno().": ".fbsql_error()."<BR>"; ?> |
Vedere anche: fbsql_error() e fbsql_warnings().
(PHP 4 >= 4.0.6, PHP 5)
fbsql_error -- Ritorna il testo del messaggio di errore emesso dalla precedente operazione FrontBase.Restituisce il testo del messaggio di errore dell'ultima funzione fbsql, o '' (una stringa vuota) se non ci sono stati errori.
Gli errori vengono restituiti dal database fbsql senza visualizzare i warnings. Usare fbsql_errno() per ricevere codice dell'errore. Da notare che questa funzione restituisce solamente il codice di errore proveniente dalla più recente esecuzione di una funzione fbsql (escludendo fbsql_error() e fbsql_errno()),così se si vuole usarla, assicurarsi di controllare il valore prima di richiamare un'altra funzione fbsql.
<?php fbsql_connect("marliesle"); echo fbsql_errno().": ".fbsql_error()."<BR>"; fbsql_select_db("nonexistentdb"); echo fbsql_errno().": ".fbsql_error()."<BR>"; $conn = fbsql_query("SELECT * FROM nonexistenttable;"); echo fbsql_errno().": ".fbsql_error()."<BR>"; ?> |
Vedere anche: fbsql_errno() e fbsql_warnings().
(PHP 4 >= 4.0.6, PHP 5)
fbsql_fetch_array -- Restituisce una riga (tupla) di risultato in forma di Array associativo, Array enumerato o entrambiRestituisce un array che corrisponde alla riga di risultato, o FALSE se non ci sono righe successive.
fbsql_fetch_array() è una versione estesa di fbsql_fetch_row(). In aggiunta all'inserimento dei dati negli elementi dell'array con indice numerico, li inserisce anche in indici associativi, usando il nome dei campi come chiavi.
Se due o più colonne di risultato hanno lo stesso nome di campo , l'ultima colonna sovrascriverà la precedente con lo stesso nome. Per accedere alle altre colonne con lo stesso nome si deve usare l'indice numerico oppure fare un alias della colonna.
Una cosa importante da notare è che fbsql_fetch_array() NON è singnificativamente più lenta di fbsql_fetch_row(), mentre fornisce un significativo valore aggiunto.
Il secondo parametro opzionale, result_type in fbsql_fetch_array() è una costante che può assumere i seguenti valori: FBSQL_ASSOC, FBSQL_NUM, and FBSQL_BOTH.
Per ulteriori dettagli vedere anche fbsql_fetch_row() e fbsql_fetch_assoc().
Esempio 1. fbsql_fetch_array()
|
(PHP 4 >= 4.0.6, PHP 5)
fbsql_fetch_assoc -- Restituisce una riga (tupla) di risultato in forma di Array associativo.Restituisce un array associativo corrispondente alla riga di risultato, o FALSE se non ci sono righe successive.
fbsql_fetch_assoc() è equivalente ad una chiamata a fbsql_fetch_array() con FBSQL_ASSOC come parametro opzionale. Restituirà solo un array associativo. fbsql_fetch_array() originariamente lavora in questo modo. Se si vuole un indice numerico come pure quello associativo, usare fbsql_fetch_array().
Se due o più colonne di risultato hanno lo stesso nome di campo , l'ultima colonna sovrascriverà la precedente con lo stesso nome. Per accedere alle altre colonne con lo stesso nome si deve usare fbsql_fetch_array() che ritorna un indice numerico.
Una cosa importante da notare è che fbsql_fetch_assoc() NON è singnificativamente più lenta di fbsql_fetch_row(), mentre fornisce un significativo valore aggiunto.
Per maggiori dettagli, vedi anche fbsql_fetch_row() e fbsql_fetch_array().
(PHP 4 >= 4.0.6, PHP 5)
fbsql_fetch_field -- Ottiene informazioni su una colonna da un set di risultati come oggettoRestituisce un oggetto contenente le informazioni del campo.
La funzione fbsql_fetch_field() può essere utilizzata per ottenere informazioni sui campi da un set di risultati. Se non si specifica l'offset del campo, la funzione resituisce i le informazione sul campo successivo non ancora letto da fbsql_fetch_field().
Le proprietà dell'oggetto sono:
name - nome della colonna
table - nome della tabella da cui deriva la colonna
max_length - lunghezza massima della colonna
not_null - 1 se la colonna non può essere NULL
type - tipo di colonna
Esempio 1. Esempio di uso di fbsql_fetch_field()
|
Vedere anche fbsql_field_seek().
(PHP 4 >= 4.0.6, PHP 5)
fbsql_fetch_lengths -- Ottiene la lunghezza di ciascun output in un set di risultatiLa funzione restituisce un array contenente le lunghezze di ciascun campo nell'ultima riga letta da fbsql_fetch_row(), oppure FALSE se si verifica un errore.
fbsql_fetch_lengths() memorizza le lunghezze di ciascuna colonna dall'ultima riga letta da fbsql_fetch_row(), da fbsql_fetch_array() e da fbsql_fetch_object() in un vettore, partendo dall'offset 0.
Vedere anche fbsql_fetch_row().
La funzione restituisce un oggetto le cui properietà corrispondono lla riga letta, oppure FALSE se non vi sono più righe.
La funzione fbsql_fetch_object() è simile a fbsql_fetch_array(), con una differenza, resituisce un oggetto anzichè un array. Indirettamente ciò significa che si può accedere ai dati solo per nome dei campi e non per il loro offset (i numeri non sono nomi di proprietà validi).
Il parametro opzionale result_type è una costante e può assumere i seguenti valori: FBSQL_ASSOC, FBSQL_NUM, and FBSQL_BOTH.
Come performance la funzione è simile a fbsql_fetch_array(), e quasi veloce come fbsql_fetch_row() (le differenza è insignificante).
Vedere anche: fbsql_fetch_array() e fbsql_fetch_row().
Resituisce: una matrice corrispondente alla riga letta, oppure FALSE se non vi sono più righe.
La funzione fbsql_fetch_row() legge una riga del set di risultati indicato dal parametro result. La riga viene restituita come matrice. Ciascuna colonna è memorizzata in un indice della matrice. La matrice parte da 0.
Chiamate successive a fbsql_fetch_row() restituiscono la successiva riga dal set di risultati, oppure FALSE se non vi sono righe successive.
Vedere anche: fbsql_fetch_array(), fbsql_fetch_object(), fbsql_data_seek(), fbsql_fetch_lengths(), and fbsql_result().
La funzione fbsql_field_flags() restituisce i flag del campo indicato. I flag sono restituiti come parola singola per flag separata da spazi, in questo modo i valori restituiti possono essere suddivisi utilizzando explode().
La funzione fbsql_field_len() restituisce la lunghezza del campo indicato.
La funzione fbsql_field_name() restituisce il nome del campo indicato da field_index. Il parametro result deve essere un valido identificatore di un set di risultati e field_index l'indice del campo.
Nota: field_index parte da 0.
Esempio: l'indice del terzo campo sarà 2, l'indice del quarto sarà 3 e così via.
Esempio 1. Esempio di uso di fbsql_field_name()
L'esempio precedente visualizzerà:
|
(PHP 4 >= 4.0.6, PHP 5)
fbsql_field_seek -- Imposta il puntatore del set di risultati ad un specifico indice di campoSposta ad uno specifico indice di campo. Se la successiva chiamata a fbsql_fetch_field() non specifica alcun indice di campo, sarà restituito il campo il cui indice è impostato da fbsql_field_seek().
Vedere anche: fbsql_fetch_field().
Ottiene il nome della tabella in cui si trova il campo.
La funzione fbsql_field_type() è simile a fbsql_field_name(). Gli argomenti sono simili, ma restituisce il tipo di campo. I tipi restituiti saranno "int", "real", "string", "blob", e altri come specificato nella documentazione di FrontBase.
Esempio 1. Esempio di uso di fbsql_field_type()
|
La funzione fbsql_free_result() libera tutta la memoria associata al un set di risultati indicato da result.
Si dovrebbe richiamare la funzione fbsql_free_result() soltanto se si è preoccupati della quantità di memoria utilizzata per le query che restituiscono grosse quantità di dati. Tutta la memoria occupata dal set di risultati sarà liberata, in automatico, alla fine dell'esecuzione dello script.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.0.6, PHP 5)
fbsql_insert_id -- restituisce l'id generato dalla precedente operazione di INSERTLa funzione fbsql_insert_id() restituisce l'ID generato per una colonna definita come DEFAULT UNIQUE da una precedente query INSERT eseguita sulla connessione link_identifier. Se non si specifica link_identifier si assume l'ultimo link aperto.
fbsql_insert_id()restituisce 0 ise la precedente query non ha generato campo impostati a DEFAULT UNIQUE. Se si desidera salvare il valore per usi futuri, occorre essere sicuri di eseguire fbsql_insert_id() immediatamente dopo la query che genera il valore.
Nota: Il valore restituito dalla funzione fbsql_insert_id() di FrontBase SQL contiene sempre il più recente valore DEFAULT UNIQUE prodotto, e non viene azzerato tra le query.
La funzione fbsql_list_dbs() restituirà il puntatore ad un risultato contenente l'elenco dei databse disponibili dal corrente servizio fbsql. Utilizzare la funzione fbsql_tablename() per muoversi tra i risultati del puntatore
Nota: L'esempio precedente sarebbe semplice con fbsql_fetch_row() o altre funzioni simili.
fbsql_list_fields() recupera informazioni sulla tabella data. I parametri passati sono il nome del database ed il nome della tabella. La funzione resituisce un puntatore alle infomrazioni che può essere utilizzato con fbsql_field_flags(), fbsql_field_len(), fbsql_field_name() e fbsql_field_type().
Il valore restituito è un intero positivo. La funzione restituisce FALSE se si verifica un errore. In caso di errore, nel campo $phperrmsg si avrà un testo con la descrizione dell'errore, e, a meno che la funzione non sia richiamata come @fbsql() questo testo sarà visualizzato.
Esempio 1. Esempio di uso di fbsql_list_fields()
L'esempio precedente visualizzerà:
|
La funzione fbsql_list_tables() prende il nome del database e restituisce e restituisce un puntatore come la funzione fbsql_db_query(). A questo punto occorre utilizzare la funzione fbsql_tablename() per ottenere il nome delle tabelle dal puntatore ottenuto.
Quando si invia più di un comando SQL al server o si esegue una 'stored procedure' che generi più risultati, si spinge il server a generare più set di risultati. Questa funzione verifica la disponibilità di set aggiuntivi dal server. Se esiste un set di risultati aggiuntivo, la funzione libererà la memoria del set corrente e si prepare a scaricare il nuovo. La funzione restituisce TRUE se è disponibile un nuovo set di risultati, oppure FALSE se non ve ne sono.
Esempio 1. Esempio di uso di fbsql_next_result()
|
(PHP 4 >= 4.0.6, PHP 5)
fbsql_num_fields -- Ottiene il numero dei campi presenti in un set di risultatifbsql_num_fields() restituisce il numero dei campi in un set di risultati.
Vedere anche: fbsql_db_query(), fbsql_query(), fbsql_fetch_field() e fbsql_num_rows().
(PHP 4 >= 4.0.6, PHP 5)
fbsql_num_rows -- Restituisce il numero di righe presenti in un set di risultatifbsql_num_rows() restituisce il numero di righe presenti in un set di risultati. Questo comando vale solo per le SELECT. Per sapere il numero di righe coinvolte da un INSERT, UPDATE o DELETE, utilizzare fbsql_affected_rows().
Vedere anche: fbsql_affected_rows(), fbsql_connect(), fbsql_select_db() e fbsql_query().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce: un identificatore della connessione come numero positivo se la connessione riesce, oppure FALSE se la connessione non riesce.
La funzione fbsql_pconnect() stabilisce una connessione con un server FrontBase. I seguenti valori saranno usati come defualt per i parametri omessi: host = 'localhost', username = "_SYSTEM" e password = password vuota.
Per impostare il numero di porta del server FrontBase utilzzare fbsql_select_db().
fbsql_pconnect() agisce in modo simile a fbsql_connect() con due differenze.
Primo, durante la connessione la funzione prima tenta di trovare una connessione (persistente) per il medesimo server già aperta, con il medesimo utente e la medesima password. Se si trova una connessione verrà restituito l'identificatore di questa piuttosto che aprire una nuova connessione.
Secondo, la connessione al server SQL non verrà chiusa al termine dello script. Resterà, invece. aperta per usi futuri.
Questo tipo di connessione è, quindi, chiamata 'persistente'.
La funzione fbsql_query() invia una query al database al database attivo sul collegamento identificato da link_identifier. Se non si specifica link_identifier, si utilizzerà l'ultimo collegamento aperto. Se non vi sono collegamenti attivi la funzione tenta di stabilirne uno come se si chiamasse fbsql_connect() senza parametri.
Nota: Il testo della query deve terminare sempre con punto e virgola.
La funzione fbsql_query() restituisce TRUE (non-zero) oppure FALSE per indicare se la query ha avuto successo o meno. Un valore di ritorno pari a TRUE indica che la query è valida e può essere eseguita dal server. Il valore di ritorno non indica nulla su quante sono le righe coinvolte. Pertanto è possibile che una query abbia successo, ma non coinvolga alcuna riga.
La seguente query è errata, pertanto fbsql_query() fallirà e restituirà FALSE:
La seguente query è semanticamente errata se my_col non è una colonna della tabella my_tbl, pertanto fbsql_query() fallirà e restituirà FALSE:
Inoltre fbsql_query() fallirà e restituirà FALSE se non si hanno i permessi per accedere alle tabelle referenziate dalla query.
Quando la query ha successo, si può utilizzare fbsql_num_rows() per sapere quante righe saranno restituite da un'istruzione SELECT, oppure si può utilizzare fbsql_affected_rows() per sapere quante righe sono state toccate da un DELETE, INSERT, REPLACE o UPDATE.
Per i comandi SELECT, la funzione fbsql_query() restituisce l'identificatore ad un nuovo set dirsultati, che può essere passato a fbsql_result(). Quando si è completato il lavoro con un set di risultati, si può liberare le risorse occupate da questo chiamando fbsql_free_result(). Si ricorda, comunque, che la memoria verrà liberata automaticamente al termine dell'esecuzione dello script.
Vedere anche: fbsql_affected_rows(), fbsql_db_query(), fbsql_free_result(), fbsql_result(), fbsql_select_db() e fbsql_connect().
Restituisce: una stringa contenente il BLOB indicato da blob_handle.
La funzione fbsql_read_blob() legge un campo BLOB dal database. Se una istruzione select contiene colonne BLOB e/o CLOB FrontBase restituisce direttamente i dati quando è richiesta la riga. Questo è il comportamento di default, esso può essere variato tramite fbsql_set_lob_mode() in modo che le funzioni di lettura dei dati restituiscano un puntatore ai dati BLOB e CLOB. Se si ottiene il puntatore occorre eseguire fbsql_read_blob() per ottenere i dati BLOB dal database.
Esempio 1. Esempio di uso di fbsql_read_blob()
|
Vedere anche: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob() e fbsql_set_lob_mode().
Restituisce: una stringa contenente il CLOB indicato da clob_handle.
La funzione fbsql_read_clob() legge un campo CLOB dal database. Se una istruzione select contiene colonne BLOB e/o CLOB FrontBase restituisce direttamente i dati quando è richiesta la riga. Questo è il comportamento di default, esso può essere variato tramite fbsql_set_lob_mode() in modo che le funzioni di lettura dei dati restituiscano un puntatore ai dati BLOB e CLOB. Se si ottiene il puntatore occorre eseguire fbsql_read_clob() per ottenere i dati CLOB dal database.
Esempio 1. Esempio di uso di fbsql_read_clob()
|
Vedere anche: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob() e fbsql_set_lob_mode().
La funzione fbsql_result() restituisce il contenuto di una cella da un set di risultati di una query a FrontBase. L'argomento field può essere l'offset del campo, o il nome del campo, oppure nome della tabella del campo punto nome del campo (nometabella.nomecampo). Se il nome della colonna ha un alias ('select foo as bar from...'), usare l'alias al posto del nome della colonna.
Quando si lavora con grandi set di risultati, si può considerare l'utilizzo delle funzioni che restituiscono l'intera riga (elencate di seguito). Poichè queste restituiscono il contenuto di più celle con una singola chiamata, esse sono MOLTO più veloci che fbsql_result(). Occorre far notare, inoltre, che specificando l'offset numerico del campo si ottiene un'esecuzione più veloce rispetto alla specifica del nome del campo o di nometabella.nomecampo.
Le chiamate a fbsql_result() non dovrebbero essere mischiate con con chiamate ad altre funzioni che agiscano sul set di risultati.
Alternative più performanti raccomandate: fbsql_fetch_row(), fbsql_fetch_array() e fbsql_fetch_object().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione fbsql_rollback() termina la transazione corrente eseguendo il rollback di tutte le istruzioni dall'ultimo commit. Questo comando è necessario solo se autocommit è impostato a false.
Vedere anche: fbsql_autocommit() e fbsql_commit()
La funzione fbsql_select_db() attiva il database corrente sul server associato alla connessione specificata da link_identifier Se non si passa link_identifier, si considera l'ultima connessione aperta. Se non vi sono connessioni aperte, la funzione tenta di stabilirne una come se fosse eseguita la funzione fbsql_connect().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il client contatta FBExec per ottenere il numero diporta per stabilire la connessione al database. Se database_name è un numero il sistema userà quel numero come porta e non chiederà un numero di porta a FBExec. Il server FrontBase può essere avviato come FRontBase -FBExec=No -port=<port number> <database name>.
Ogni chiamata successiva a fbsql_query() sarà eseguita sul database attivo.
Se il database è protetto con una password, l'utente deve eseguire fbsql_database_password() prima di selezionare il database.
Vedere anche: fbsql_connect(), fbsql_pconnect(), fbsql_database_password() e fbsql_query().
(PHP 4 >= 4.2.0, PHP 5)
fbsql_set_lob_mode -- Imposta la modalità LOB in un set di risultati FrontBaseRestituisce: TRUE se ha successo, FALSE se si verifica un errore.
La funzione fbsql_set_lob_mode() la modalità per il recupero dei dati LOB dal database. Quando i dati BLOB e CLOB sono memorizzati in FrontBase questi possono essere memorizzati direttamente o indirettamente. I dati LOB archiviati direttamente sono sempre recuperati a prescindere dell'impostazione della modalità LOB. Se i dati LOB sono meno di 512 byte saranno sempre archiviati direttamente.
FBSQL_LOB_DIRECT - I dati LOB sono recuperati direttamente. Quando i dati sono ottenuti dal database con fbsql_fetch_row(), o altre funzioni per il recupero dei dati, tutte le colonne BLOB saranno restituite come colonne ordinarie. Questo è il valore di default in un nuovo set di risultati.
FBSQL_LOB_HANDLE - I dati LOB sono recuperati come puntatori ai dati. Quando si recupera le informazioni da un database con fbsql_fetch_row (), o altre funzioni per il recupero dei dati, i dati LOB saranno restituiti come handle ai dati, se questi sono stati memorizzati indirettamente o saranno restituiti direttamente i dati se questi sono memorizzati in modo diretto. Se la funzione restituisce un handle, questo sarà una stringa di 27 byte con il formato tipo "@'000000000000000000000000'".
Vedere anche: fbsql_create_blob(), fbsql_create_clob(), fbsql_read_blob() e fbsql_read_clob().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
fbsql_start_db()
Vedere anche: fbsql_db_status() e fbsql_stop_db().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
fbsql_stop_db()
Vedere anche: fbsql_db_status() e fbsql_start_db().
La funzione fbsql_tablename() utilizza il puntatore al risultato restituito da fbsql_list_tables() e restituisce il nome della tabella. Si può, inoltre, utilizzare la funzione fbsql_num_rows() per determinare il numero di tabelle presenti in un risultato.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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/.
Restituisce il numero di campi (colonne) di un database filePro aperto.
Vedere anche filepro().
Restituisce il nome del campo riferito all'indice inserito come parametro field_number.
Restituisce il tipo del campo riferito all'indice inserito come parametro field_number.
Restituisce la lunghezza del campo riferito all'indice inserito come parametro field_number.
Restituisce dei dati da una locazione specificata nel database.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Restituisce il numero di righe presenti in un database filePro.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Vedede anche filepro().
Questa funzione legge e verifica la mappa del file, immagazzinando l'indice del campo e le informazioni.
Non viene eseguito nessun locking, si dovrebbe evitare di modificare il database filePro mentre quest'ultimo potrebbe venire aperto in PHP.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Non sono richieste librerie esterne per compilare questo modulo, ma se si desidera avere il supporto per LFS (file di grandi dimensioni) su Linux, occorre avere una versione recente di glibc e occorre compilare il PHP con i seguenti parametri: -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Opzioni di configurazione per Filesystem e Streams
Nome | Default | Modificabile |
---|---|---|
allow_url_fopen | "1" | PHP_INI_SYSTEM |
user_agent | NULL | PHP_INI_ALL |
default_socket_timeout | "60" | PHP_INI_ALL |
from | NULL | ?? |
auto_detect_line_endings | "Off" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
Questa opzione abilita i wrapper URL per fopen, in modo da potere accedere ad oggetti URL come file. Per default sono forniti wrapper per accedere a file remoti usando il protocollo ftp o http, alcune estensioni, tipo zlib, possono registrarne altri.
Nota: Questa impostazione può essere impostata solamente nel php.ini per motivi di sicurezza.
Nota: Questa opzione è stata aggiunta subito dopo il rilascio di PHP 4.0.3. Per le versioni fino a 4.0.3 compresa si può disabilitare questa opzione solo al momento della compila utilizzando il parametro di configurazione --disable-url-fopen-wrapper.
Avvertimento |
Nelle versioni precedenti alla 4.3.0 per i sistemi Windows, le suguenti funzioni non supportano l'accesso a file remoti: include(), include_once(), require(), require_once() e le funzioni imagecreatefromXXX nel modulo Riferimento XLII, Funzioni per le immagini. |
Definisce un agente utente il PHP.
Timeout di default (in secondi) per gli stream sui socket.
Nota: Questa opzione di configurazione è stata inserita in PHP 4.3.0
Imposta la password per l'ftp anonimo (il tuo indirizzo di posta elettronica).
Quando è attivato, il PHP esamina i dati letti da fgets() e file() per vedere se si sta utilizzando le convezioni di Unix, MS-Dos o Macintosh.
Questo permette al PHP di operare con sistemi Macintosh, ma, per default, l'opzione è impostata a Off, poichè vi è una piccola penalizzazione di velocità nel cercare di individuare il tipo di EOL per la prima riga; e anche perchè in alcuni casi si è sperimentato che l'utilizzo del carriage-returns come separatore nei sistemi Unix ha generato comportamenti non compatibili con il passato.
Nota: Questa opzione è stata introdotta in PHP 4.3.0
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Vedere anche le sezioni Directory e Esecuzione di programmi.
Per avere un elenco e le spiegazioni sui vari wrapper URL che possono essere utilizzati sui file remoti, vedere Appendice L.
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 (/).
Nota: Il parametro suffix è stato aggiunto in PHP 4.1.0.
Vedere anche: dirname()
Tenta di cambiare il gruppo del file filename in group (specificato per nome o numero). Solo l'amministratore può cambiare arbitrariamente il gruppo di un file; gli altri utenti possono cambiare il gruppo dei file solo fra gruppi di cui sono membri.
Restituisce TRUE se ha successo; FALSE altrimenti.
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Tenta di cambiare le impostazioni del file filename in quelle date in mode.
Si osservi che mode non viene automaticamente assunto come valore ottale, per cui le stringhe (come "g+w") non verranno elaborate correttamente. Per ottenere l'operazione desiderata, è necessario far 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.
Tenta di cambiare il proprietario di un file filename in user (specificato per nome o numero). Solo l'amministratore può cambiare il proprietario di un file.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Vedere anche chown() e chmod().
Quando si eseguono le funzioni di sistema stat o lstat o una delle funzioni elencate nella lista delle funzioni coinvolte (vedi sotto), il PHP memorizza le informazioni restituite da queste funzioni in modo da fornire migliori performance. Esistono, tuttavia, casi in cui si desidera rimuovere le informazioni memorizzate. Ad esempio, nel caso in cui un file venga controllato più volte nel medesimo script ed il file si trova in situazioni in cui possa venire rimosso o possa essere variato durante l'esecuzione dello script; in questi casi si può volere cancellare le informazioni memorizzate. Per queste situazioni si può utilizzare la funzione clearstatcache() che cancella le informazioni memorizzate dal PHP sullo stato di un file.
Occorre notare che il PHP non memorizza informazioni su file inesistenti. Pertanto se si esegue la funzione file_exists() su un file che non esiste, questa restituisce FALSE fino a quando il file non viene creato. Un volta ccreato il file, la funzione restituisce TRUE anche se il file viene cancellato.
Nota: Queste funzioni memorizzano informazioni su specifici file, pertanto basta eseguire clearstatcache() nel caso di molteplici operazioni sul medesimo file oppure nel caso sia necessario non memorizzare informazioni su un dato file.
Tale valore viene memorizzato solo per la durata di una singola richiesta.
Le funzioni coinvolte sono stat(), lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype() e fileperms().
Copia il file source in dest. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Come da PHP 4.3.0, sia source che dest potrebbero essere URL se "fopen wrappers" è stato abilitato. Vedere fopen() per ulteriori dettagli. Se il parametro dest punta ad un URL, l'operazione di copia potrebbe fallire se il wrapper non supporta la sovrascrittura di file esistenti.
Avvertimento |
Se il file di destinazione già esiste, esso verrà sovrascritto. |
Vedere anche move_uploaded_file(), rename(), e la sezione del manuale riguardo handling file uploads.
Questa funzione non esiste, la sua presenza nel manuale vuole essere utile a coloro che cercano nel posto sbagliato le funzioni unlink() o unset().
Vedere anche: unlink() per cancellare file, unset() per eliminare variabili.
Data una stringa contenente il percorso di un file, questa funzione restituirà il nome della directory.
Su windows sia gli slash (/) che i backslash (\) vengono utilizzati come caratteri di separazione nei percorsi. In altri ambienti, c'è solo lo slash in avanti (/).
Nota: In PHP 4.0.3, la funzione dirname() è stata modificata per essere conforme alle specifiche POSIX. Essenzialmente ciò significa che non ci sono slash nel parametro path , viene restituito un punto ('.') per indicare la directory corrente. In altro modo, la stringa restituita è path senza alcun /component. Occorre notare che ciò implica che spesso dalla funzione dirname() si ottiene uno slash od un punto nei casi in cui la vecchia versione avrebbe restituito una stringa vuota.
Vedere anche: basename(), pathinfo() e realpath().
Data una stringa contenente una directory, questa funzione restituirà il numero di byte disponibili nel corrispondente filesystem o nella partizione corrispondente.
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
Vedere anche disk_total_space()
Data una stringa contenente una directory, questa funzione restituirà il numero totale di byte del filesystem o della partizione corrispondente.
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
Vedere anche disk_free_space()
Chiude il file puntato da handle.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il puntatore al file deve essere valido e deve puntare ad un file aperto correttamente da fopen() o da fsockopen().
Restituisce TRUE se il puntatore al file ha raggiunto la fine del file (EOF) o si è verificato un errore (anche in caso 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().
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().
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. |
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Vedere anche fread(), fopen(), popen(), fsockopen() e fgets().
(PHP 3>= 3.0.8, PHP 4 , PHP 5)
fgetcsv -- Prende una riga da un puntatore a file e l'analizza in cerca di campi CSVSimile 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.
|
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:
Nota: Il parametro length è diventato opzionale a partire da PHP 4.2.0, se omesso, si assume come lunghezza della linea 1024. A partire dalla versione 4.3, l'omissione del parametro length comporta la lettura del flusso d'ingresso sino al raggiungimento della fine della linea. Se la maggior parte delle righe lette dal file hanno dimensione superiore a 8KB, è più efficiente specificare la lunghezza massima della linea.
Nota: A partire da PHP 4.3 questa funzione è 'binary safe'. Le versioni precedenti non lo sono.
Nota: Se il PHP ha dei problemi a riconoscere la fine riga nella lettura di file su o creati da computer Macintosh, si può abilitare il parametro di configurazione auto_detect_line_endings.
Vedere anche fread(), fgetc(), stream_get_line(), fopen(), popen(), fsockopen() e stream_set_timeout().
Identica a fgets(), eccetto per il fatto che fgetss tenta di eliminare tutti i tag HTML e PHP dal testo che legge.
Puoi utilizzare il terzo parametro (opzionale) per specificare quali tag non devono essere eliminati.
Nota: Il parametro allowable_tags è stato aggiunto in PHP 3.0.13, 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().
Restituisce TRUE se il file o la directory specificata da filename esiste; FALSE altrimenti.
Sui sistemi Windows utlizzare //computername/share/filename oppure \\computername\share\filename per verificare file su dischi condivisi.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice L per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche is_readable(), is_writable(), is_file() e file().
Simile alla funzione file(), tranne che file_get_contents() restituisce il file in una stringa. 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().
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().
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().
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().
Vedere anche filemtime(), fileinode() e date().
Restituisce l'ora in cui il file è stato cambiato l'ultima volta o FALSE in caso d'errore. L'ora viene restituita come un timestamp di Unix.
Nota: In molti filesystem Unix, si considera un file modificato, quando il suo inode viene cambiato; cioè quando i permessi, il proprietario, il gruppo o altri metadata dell'inode vengono aggiornati. Vedere anche filemtime() (che è ciò che ti serve se vuoi inserire la scritta "Ultima modifica: " nel piede delle tue pagine web) e fileatime().
Sappi anche che in alcuni testi su Unix si fa riferimento al ctime di un file come l'ora di creazione dello stesso. E' sbagliato. Nella maggioranza dei filesystem Unix non esiste un oa di creazione.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice L per la lista di quali wrappers supportano le funzioni della famiglia stat().
Esempio 1. Esempio di uso di fileatime()
|
Vedere anche filemtime().
Restituisce il l'ID del gruppo del file, o FALSE in caso d'errore. L'ID del gruppo viene restituito in formato numerico: usa posix_getgrgid() per trasformarlo nel nome del gruppo. In caso di errore la funzione restituisce FALSE accompagnato da un errore di di livello E_WARNING.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice L per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche: fileowner() e safe_mode_gid.
Restituisce il numero di inode del file, o FALSE in caso d'errore.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice L per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche stat().
Restituisce l'ora dell'ultima modifica al file o FALSE in caso d'errore. L'ora viene restituita come un timestamp di Unix.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice 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.
Vedere anche filectime(), stat(), touch() e getlastmod().
Restituisce l'ID dell'utente proprietario del file, o FALSE in caso di errore. L'ID dell'utente viene restituito in formato numerico, usa posix_getpwuid() per trasformarlo nel nome dell'utente stesso.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice L per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche stat()
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().
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().
Vedere anche file_exists()
Restituisce il tipo del file. Sono valori possibili fifo, char, dir, block, link, file e unknown.
Restituisce FALSE se si verifica un errore. Inoltre la funzione filetype() genera un errore di livello E_NOTICE se fallisce la chiamata a stat o se il tipo è sconosciuto.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice L per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche: is_dir(), is_file(), is_link(), file_exists(), stat() e mime_content_type().
Il PHP supporta un tecnologia portabile per bloccare file completi in modalità advisory (tutti i programmi che vi accedono, devono usare lo stesso tipo di bloccaggio o non funzionerà).
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.
Nota: Poiché flock() richiede il puntatore ad un file, può occorre utilizzare un speciale file di lock per proteggere l'accesso a eventuali file che si desidera azzerare attraverso l'apertura in modalità di scrittura (usando "w" o "w+" come argomento di fopen()).
Avvertimento |
La funzione flock() non funzione con NFS e con diversi altri file system di rete. Verificare sulla documentazione del proprio sistema operativo. Su molti sistemi operativi flock() è implementato a livello di processo. Usando un server API multithread quale ISAPI non potrai basarti su flock() per proteggere i file da altri script PHP che girino in thread paralleli della stessa istanza del server! La funzione flock() non è supportata su file system antiquati tipo FAT e i suoi derivati e pertanto in tali ambienti restituirà sempre FALSE (questo è vero soprattutto per gli utenti di Windows 98). |
fnmatch() checks if the passed string would match the given shell wildcard pattern.
This is especially useful for filenames, but may also be used on regular strings. The average user may be used to shell patterns or at least in their simplest form to '?' and '*' wildcards so using fnmatch() instead of ereg() or preg_match() for frontend search expression input may be way more convenient for non-programming users.
Avvertimento |
For now this function is not available on Windows or other non-POSIX compliant systems. |
See also glob(), ereg(), preg_match() and the Unix manpage on fnmatch(3) for flag names (as long as they are not documented here ).
La funzione fopen() apre un collegamneto tra una risorsa, indicata dal parametro filename, ed un flusso. Se il parametro filename è del tipo "scheme://...", si assume essere un URL ed il PHP cercherà il modulo di gestione del protocollo (detto anche wrapper) per quello schema. Se non vi sono wrapper registrati per il protocollo richiesto, il PHP genererà un messaggio per aiutare a trovare potenziali problemi nello script e quindi procede considerando filename come un file regolare.
Se il PHP ha stabilito che filename indica un file locale, tenterà di aprire detto file come stream. Il file in oggetto dovrà esere accessibile dal PHP, occorre, pertanto, assicurasi che i permessi di accesso del file lo consentano. Se si è attivato il 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
mode | Descrizione |
---|---|
'r' | Apre in sola lettura; posiziona il puntatore all'inizio del file. |
'r+' | Apre in lettura e scrittura; posiziona il puntatore all'inizio del file. |
'w' | Apre il file in sola scrittura; posiziona il puntatore all'inizio del file e tronca il file alla lunghezza zero. Se il file non esiste, tenta di crearlo. |
'w+' | Apre in lettura e scrittura; posiziona il puntatore all'inizio del file e tronce il file alla lunghezza zero. Se il file non esiste, tenta di crearlo. |
'a' | Apre in sola scrittura; posiziona il puntatore alla fine del file. Se il file non esiste, tenta di crearlo. |
'a+' | Apre in lettura e scrittura; posiziona il puntatore alla fine del file. Se il file non esiste, tenta di crearlo. |
'x' | Crea ed apre il file in sola scrittura; posiziona il puntatore all'inizio del file. Se il file esiste già la chiamata a fopen() fallirà restituendo FALSE e verrà generato un errore di lievllo E_WARNING. Se il file non esiste si tenterà di crearlo. Questo equivale a specificare i flag O_EXCL|O_CREAT nella sottostante chiamata a open(2) . Questa opzione è supportata a partire dalla versione 4.3.2 di PHP, e funziona solo con i file locali. |
'x+' | Crea ed apre il file in lettura e scrittura; posiziona il puntatore all'inizio del file. Se il file esiste già la chiamata a fopen() fallirà restituendo FALSE e verrà generato un errore di lievllo E_WARNING. Se il file non esiste si tenterà di crearlo. Questo equivale a specificare i flag O_EXCL|O_CREAT nella sottostante chiamata a open(2) . Questa opzione è supportata a partire dalla versione 4.3.2 di PHP, e funziona solo con i file locali. |
Nota: Differenti famiglie di file system hanno differenti tipi di terminatori di riga. Quando si scrive un file di testo e si desidera inserire una interruzione di linea, occorre utilizzare il terminatore appropriato per il sistema operativo utilizzato. I sistemi basati su Unix utilizzano \n come terminatore di riga, i sistemi basati su Windows utilizzano \r\n mentre i sistemi Macintosh utilizzano \r.
Se si utilizza un errato terminatore di riga quando si scrivono i file, si può verificare che altre applicazioni accedendo a questi file abbiano comportamenti bizzarri.
Windows ha un flag di traduzione della modalità testo ('t') che in modo trasparente converte \n in \r\n mentre si lavora sul file. Ovviamente si ha anche il flag 'b' per forzare una modalità binaria, nella quale non si ha la conversione dei dati. Se si usano questi flag, 'b' oppure 't', devono essere posizionati come ultimo carattere del parametro mode.
La modalità di conversione di default dipende dalla SAPI e dalla versione di PHP che si sta utlizzando, pertanto si incoraggia l'uso dei flag appropriati per aumentare la portabilità degli script. Si dovrebbe utilizzare 't' se si lavora con dei file di testo, e si utilizza \n per indicare il fine linea, e ci si aspetta che che altre applicazioni, tipo notepad, leggano il file prodotto. In tutti gli altri casi si dovrebbe utilizzare 'b'
Se non si specifica il flag 'b' quando si lavora con file binari, si possono avere situazioni anomale nei dati, tipo immagini corrotte, e situazioni anomale con i caratteri \r\n.
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.
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 '/'.
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().
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
|
Vedere anche readfile(), fopen(), popen() e fsockopen()
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().
La funzione fscanf() è simile a sscanf(), ma prende il proprio input da un file associato con handle e interpreta l'input in accordo con il parametro format, che viene descritto nella documentazione della funzione sprintf(). Se vengono passati solo due parametri a questa funzione, i valori esaminati verranno restituiti in un vettore. Altrimenti, se vengono passati i parametri opzionali, la funzione restituirà il numero dei valori assegnati. I parametri opzionali devono essere passati da reference.
Ogni spazio nella stringa di formato identifica uno spazio nel flusso di input. Questo significa che anche i tab \t presenti nella stringa di formato possono identiicare uno spazio nel flusso di input.
Nota: Nelle versioni di PHP precedenti alla 4.3.0, il numero massimo di caratteri letti da un file era di 512 (o fino al primo \n, dipende da quale si incontra prima). Dal PHP 4.3.0 si possono esaminare linee di lunghezza arbitraria.
Vedere anche fread(), fgets(), fgetss(), sscanf(), printf() e sprintf().
Imposta l'indicatore di posizione del file riferito da handle. La nuova posizione, misurata in byte dall'inizio del file, 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.
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.
(PHP 4 , PHP 5)
fstat -- Restituisce le informazioni riguardanti un file attraverso un puntatore al file apertoRestituisce le statistiche del file aperto dal puntatore handle. Questa funzione è simile a stat() eccetto per il fatto che opera su un puntatore a file aperto invece che su un nome di file.
Restituisce un vettore con le statistiche del file con il formato del vettore è descritto nella pagina di stat().
Esempio 1. Esempio di uso di fstat()
l'esempio visualizzerà :
|
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
Restituisce la posizione del puntatore al file indicato da handle; cioè, il suo offset all'interno del flusso del file.
Se si verifica un errore, restituisce FALSE.
Il puntatore al file deve essere valido e deve puntare ad un file aperto correttamente da fopen() o da popen().
Prende il puntatore al file handle e tronca il file alla lunghezza indicata da size. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
fwrite() scrive il contenuto di string nel flusso del file puntato da handle. Se l'argomento length è specificato la scrittura si arresterà dopo aver scritto length byte o alla fine di string se si verificasse prima.
fwrite() returns the number of bytes written, or FALSE on error.
Nota che se il parametro length viene specificato, allora l'opzione di configurazione magic_quotes_runtime verrà ignorata e nessuno slash verrà skippato da string.
Nota: Su sistemi che differenzino fra file binari e di testo (come Windows) il file deve essere aperto includendo 'b' nel paramentro mode di fopen().
Esempio 1. Un semplice esempio di fwrite
|
Vedere anche fread(), fopen(), fsockopen(), popen() e fputs().
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.
Output will look something like:
|
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
See also opendir(), readdir(), closedir(), and fnmatch().
Restituisce TRUE se il nome file esiste ed è una directory. Se filename è un nome file relativo, verrà controllato relativamente alla directory di lavoro in uso.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice L per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche chdir(), dir, opendir(), is_file() e is_link().
Restituisce TRUE se il filename esiste ed è un eseguibile.
La funzione is_executable() sarà disponibile sui sistemi Windows a partire dalla versione 5.0.0 di PHP.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice L per la lista di quali wrappers supportano le funzioni della famiglia stat().
Restituisce TRUE se il filename esiste ed è un file regolare.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice L per la lista di quali wrappers supportano le funzioni della famiglia stat().
Restituisce TRUE se il filename esiste ed è un link simbolico.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice L per la lista di quali wrappers supportano le funzioni della famiglia stat().
Restituisce TRUE se filename esiste ed è leggibile.
Ricorda che PHP può accedere al file come l'utente che è rappresentato dal server (spesso 'nobody'). Non sono prese in conto limitazione di sicurezza.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice L per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche is_writable(), file_exists() e fgets().
(PHP 3>= 3.0.17, PHP 4 >= 4.0.3, PHP 5)
is_uploaded_file -- Dice se un file fù caricato via HTTP POST.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.
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().
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() 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.
Vedere anche symlink(), link() e readlink().
Raccoglie le statistiche del file o del link simbolico chiamato filename.. Questa funzione è identica alla funzione stat() eccetto che se il paramametro filename è un link simbolico valido, viene restituito lo stato del link simbolico, non lo stato del file puntato dal link simbolico.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice L per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche stat().
Tenta di creare la directory specificata da pathname.
Nota che probabilmente vuoi specificare mode come un ottale, per cui deve iniziare con uno zero. La modalità è anche modificata dall'umask corrente, che puoi cambiare con umask().
Nota: Il parametro mode è ignorato sui sistemi Windows, ed è opzionale dal PHP 4.2.0.
Il parametro mode viene impostato a 0777 per default; ciò significa dare i maggiori accessi possibili. Per maggiori dettagli sui valori di mode, leggere le pagine relative a chmod().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: A partire da PHP 5.0.0 la funzione mkdir() può anche essere utilizzata con alcuni wrapper URL. Fare riferimento a Appendice 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().
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.
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 2. Esempio di uso di parse_ini_file()
L'esempio produrrà:
|
pathinfo() restituisce un vettore associativo contenente informazioni riguardo path. Nel vettore vegono riportati i seguenti elementi: dirname, basename e extension.
Nota: Per maggiori dettagli sul recupero del percorso corrente, leggere la sezione variabili predefinite riservate.
Vedere anche dirname(), basename(), parse_url() e realpath().
Chiude un puntatore ad una pipe aperto da popen().
Il puntatore deve essere valido e deve essere stato restituito da un chiamata a popen() terminata con successo.
Restituisce lo stato di terminazione del processo che stava girando.
Vedere anche popen().
Apre una pipe ad un processo eseguito forzando il comando dato da command.
Restituisce un puntatore a file identico a quello restituito da fopen(), eccetto che per il fatto che è unidirezionale (può solo essere usato per la lettura o la scrittura) e deve essere chiudo con pclose(). Questo puntatore può essere usato con fgets(), fgetss() e fputs().
Se si verifica un errore, restituisce FALSE.
Nota: Se si sta cercando un supporto bi-direzionale (2 vie), utilizzare proc_open().
Se il comando che deve essere eseguito non è trovato, la funzione restituisce una risorsa valida. Questo sembra strano, ma ha un senso; esso permette di accedere ai messaggi di erore restituiti dalla shell:
<?php error_reporting(E_ALL); /* Aggiunge una redirezione, così possiamo ottenere stderr. */ $handle = popen('/path/to/spooge 2>&1', 'r'); echo "'$handle'; " . gettype($handle) . "\n"; $read = fread($handle, 2096); echo $read; pclose($handle); ?> |
Nota: Quando è 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().
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() si comporta analogamente alla funzione readlink di C e restituisce i conenuti del link simbolico path oppure FALSE in caso d'errore.
Vedere anche symlink(), readlink() e linkinfo().
realpath() espande tutti i link simbolici e risolve i riferimenti a '/./', '/../' ed altri caratteri '/' nell'input path e restituisce il percorso assoluto canonizzato. Il percorso risultante non avrà link simbolici, '/./' o '/../'.
realpath() restituisce FALSE in caso di fallimento, per esempio se il file non esiste.
Vedere anche: basename(), dirname() e pathinfo().
Tenta di rinominare oldname in newname.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Nelle versioni di PHP precedenti alla 4.3.3, la funzione rename() non può rinominare file attraverso partizioni nei sistemi *nix.
Nota: Dal PHP 5.0.0 rename() può anche essere utilizzata con qualche wrapper URL. Fare riferimento a Appendice 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().
Pone l'indicatore alla posizione del file per handle all'inizio del flusso del file.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il puntatore al file deve essere valido e deve puntare ad un file aperto con successo da fopen().
Nota: If you have opened the file in append ("a") mode, any data you write to the file will always be appended, regardless of the file position.
Tenta di cancellare la directory indiata da pathname. La directory deve essere vuota e i permessi concessi devono permetterlo. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Dal PHP 5.0.0 rmdir() può anche essere utilizzata con qualche wrapper URL. Fare riferimento a Appendice 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.
Restituisce una serie di informazioni a riguardo del file filename. Se il parametro filename è un link simbolico, le informazioni riguardano il file stesso, e non il file puntato dal link. La funzione lstat() è identica a stat() tranne che dovrebbe restituire il file puntato dal link.
In caso di errore stat() restituisce FALSE. Inoltre genera un warning.
La funzione restituisce un vettore con le informazioni sul file contenente i seguenti elementi. Il vettore parte dall'indice zero. Oltre agli indici numerici il vettore contiene indici associativi, come sarà indicato per ciascun parametro; questo è disponibile dal PHP versione 4.0.6.
Tabella 1. Formato del vettore restituito da stat() e fstat()
Indice numerico | Associativo (da PHP 4.0.6) | Descrizione |
---|---|---|
0 | dev | device |
1 | ino | inode |
2 | mode | modalità di protezione dell'inode |
3 | nlink | numero di link |
4 | uid | ID utente del proprietario |
5 | gid | ID del gruppo del proprietario |
6 | rdev | tipo di device con l'inode device * |
7 | size | dimensione in byte |
8 | atime | ora dell'ultimo accesso (Unix timestamp) |
9 | mtime | ora del'ultima modifica (Unix timestamp) |
10 | ctime | ora dell'ultimo cambiamento (Unix timestamp) |
11 | blksize | dimensione del blocco per l'I/O di filesystem * |
12 | blocks | numero dei blocchi allocati |
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice L per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche lstat(), fstat(), filemtime() e filegroup().
symlink() crea un link simbolico dal target esistente con il nome specificato da link.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche link() per creare hard link, e readlink() con linkinfo().
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.
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.
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.
Vedere anche tempnam().
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.
umask() imposta l'umask di PHP a mask & 0777 e restituisce il vecchio umask. Quando PHP è utilizzato come modulo server, l'umask viene ripristinato quando ciascuna richiesta è finita.
umask() senza argomenti restituisce semplicemente l'umask corrente.
Cancella filename. Simile alla funzione C di Unix unlink(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Dal PHP 5.0.0 unlink() potrà essere utilizzata anche con qualche wrapper URL. Fare riferimento a Appendice 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.
Il Forms Data Format (FDF) è un formato per la gestione di form all'interno di documenti PDF. Si dovrebbe leggere la documentazione al link http://partners.adobe.com/asn/acrobat/forms.jsp per avere maggiori informazioni su cosa sia FDF e su come usarlo in generale.
L'idea di base è che FDF sia simile ai form HTML. Fondamentalmente la differenza consiste nel formato con cui i dati sono inviati al server quando viene premuto il bottone di sottomissione del form (che, ovviamente, è in Form Data Format) e il formato del form stesso (che è il Portable Document Format, PDF). L'elaborazione dei dati FDF è una delle caratteristiche delle funzioni fdf.Ma ve ne sono altre. Una di queste consiste nel prendere un form PDF e compilarne i campi senza modificare il form . In questo caso si dovrebbe creare il documento FDF (fdf_create()) impostare i valori per ciascun campo (fdf_set_value()) e associarlo al form PDF (fdf_set_file()). Infine viene inviato al browser browser con MimeType application/vnd.fdf. Acrobat Reader riconosce il MimeType, legge il form PDF associato e completa i campi con i dati dal documento FDF.
Se si apre un documento FDF con un editor di testo si troveranno degli oggetti con nome FDF. Tali oggetti possono contenere diversi campi tipo Fields, F, Status etc.. I campi più comuni sono Fields che puntano alla lista dei campi di input, e F che contiene il nome del file PDF a cui appartengono questi dati. Questi campi sono definiti dalla documentazione FDF come chiave /F (/F-Key) e chiave /Status (/Status-Key) Le modifiche a questi chiavi posso essere svolte con funzioni tipo fdf_set_file() e fdf_set_status(). I campi sono modificati dalle funzioni fdf_set_value(), fdf_set_opt() etc..
Occorre avere disponibile il toolkit FDF SDK, scaricabile da http://partners.adobe.com/asn/acrobat/forms.jsp. Dal PHP 4.3 occorre avere almeno l'SDK versione 5.0. Le librerie FDF sono disponibili in formato binario solo per le piattaforme supportate da Adobe quali Win32, Linux, Solaris e AIX.
Occorre compilare il PHP con --with-fdftk[=DIR].
Nota: Se si hanno problemi nella configurazione del PHP con supporto fdftk, verificare che i file fdftk.h e libfdftk.so siano nel posto corretto. Lo script di configurazione supporta sia la struttura delle directory della distribuzione FDFSDK, sia l'usuale struttura DIR/include / DIR/lib, pertanto si può puntare o direttamente alla directory della distribuzione decompressa o posizionare il file con l'header e la libreria appropriata per la piattaforma, ad es. /usr/local/include e /usr/local/lib ed eseguire configure con --with-fdftk=/usr/local.
Nota per gli utenti Win32: Per potere abilitare questo modulo sui sistemi Windows, occorre copiare fdftk.dll dalla cartella DLL del rilascio PHP7Win32 alla cartella SYSTEM32 della macchina Windows. (Es. C:\WINNT\SYSTEM32 oppure C:\WINDOWS\SYSTEM32).
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
La maggior parte delle funzioni richiedono una risorsa fdf come primo parametro. La risorsa fdf è un puntatore al file fdf aperto. Le risorse fdf possono essere ottenute dalle funzioni fdf_create(), fdf_open() e fdf_open_string().
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Il seguente esempio illustra l'elaborazione dei dati di un form.
Esempio 1. Elaborazione di un documento FDF
|
Aggiunge degli script al documento FDF, che in seguito Acrobat aggiungerà agli script del documento una volta che l'FDF è importato. Su consiglia di utilizzare '\r' come separatore di riga nel script_code.
Esempio 1. Aggiunta di codice JavaScript ad un documento FDF
Sarà creato un documento come il seguente:
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione fdf_close() chiude un documento FDF.
Vedere anche fdf_open().
La funzione fdf_create() crea un nuovo documento FDF. Questa funzione è necessaria se si desidera compilare dei campi di input di un documento PDF.
Esempio 1. Compila di un documento PDF
|
Vedere anche fdf_close(), fdf_save() e fdf_open().
(PHP 4 >= 4.3.0, PHP 5)
fdf_enum_values -- Richiama una funzione definita dall'utente per ciascun valore del documento
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione fdf_errno() il codice di erore impostato dall'ultima funzione fdf_...() eseguita. Questo può valere zero se è stata eseguita con successo, o diverso da zero in caso di errore. Una descrizione testuale dell'errore può essere ottenuta usando la funzione fdf_error().
Vedere anche fdf_error().
fdf_error() restituisce la descrizione testuale per il codice di errore passato in error_code. Qualora non si fornisca error_code, la funzione utilizzerà il codice di errore interno impostato dall'ultima operazione, in questo modo fdf_error() si presenta come una scorciatoia per fdf_error(fdf_errno()).
Vedere anche fdf_errno().
La funzione fdf_get_ap() ottiene informazioni sul campo field (per es. il valore della chiave /AP) e le memorizza in un file. I possibili valori per face sono FDFNormalAP, FDFRolloverAP e FDFDownAP. Il formato è memorizzato in nel file filename.
La funzione estrae un file indicato dal "selettore di file" fieldname e lo memorizza in savepath. Il parametro savepath può essere il nome di file o una directory esistente nella quale verrà creato il file con il suo nome originale. Eventuali file con il medesimo nome saranno sovrascritti.
Nota: Sembra che non ci sia altro metodo per risalire al nome originale del file se non quello di scaricare il file nella directory indicata da savepath e rilevare il nome con cui viene scritto.
La matrice restituita contiene i seguenti indici:
path - percorso in cui viene archiviato il file
size - dimensione del file in bytes
type - mimetype se dato nel FDF
La funzione fdf_get_encoding() restituisce il valore della chiave /Encoding. Resituisce una stringa vuota se non viene utilizzato lo schema PDFDocEncoding/Unicode.
Vedere anche fdf_set_encoding().
La funzione fdf_set_file() restituisce il valore della chiave /F.
Vedere anche fdf_set_file().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione fdf_get_status() restituisce il valore per la chiave /STATUS.
Vedere anche fdf_set_status().
La funzione fdf_get_value() restituisce il valore per il campo fieldname richiesto.
Gli elementi di una matrice di campi possono essere recuperati passando il parametro opzionale which, iniziando da zero. Per i campi non matrice il parametro which viene ignorato.
Nota: Il supporto delle matrici ed il campo opzionale which sono stati aggiunti in PHP 4.3.
Vedere anche fdf_set_value().
(PHP 4 >= 4.3.0, PHP 5)
fdf_get_version -- Restituisce il numero di versione per le API FDF o un fileQuesta funzione restituisce il numero i versione FDF per il dato documento fdf_document, o il numero di versione per il toolkit API, se il parametro viene omesso.
Per il corrente toolkit FDF 5.0 il numero di versione delle API è il '5.0' e il numero di versione del documento può essere '1.2', '1.3' oppure '1.4'.
Vedere anche fdf_set_version().
Questa è una funzione di comodità per impostare le intestazioni HTTP per inviare documenti FDF. La funzione imposta il campo Content-type: a application/vnd.fdf.
La funzione fdf_next_field_name() restituisce il nome del campo successivo al campo indicato in fieldname o il nome del primo campo se è impostato a NULL.
Vedere anche fdf_enum_fields() e fdf_get_value().
La funzione fdf_open_string() ricava i dati di un form da un stringa. Il parametro fdf_data deve contenere dati restituiti da un form PDF o creati dalle funzioni fdf_create() e fdf_save_string().
Si può usare fdf_open_string() insieme a $HTTP_FDF_DATA per elaborare input in un form fdf da un client remoto.
Vedere anche fdf_open(), fdf_close(), fdf_create() e fdf_save_string().
La funzione fdf_open() apre un documento con i dati del form. Il file deve contenere i dati restituiti da un form PDF o creati tramite le funzioni fdf_create() e fdf_save().
Si può processare i risultati del POST di un form PDF scrivento i dati ricevuti da $HTTP_FDF_DATA in un file e aprendolo con fdf_open(). A partire da PHP 4.3 si può anche utilizzare la funzione fdf_open_string(), la quale utilizza un file temporaneo (che poi viene rimosso).
Vedere anche fdf_open_string(), fdf_close(), fdf_create() e fdf_save().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione fdf_save_string() restituisce il documento FDF come una stringa.
Esempio 1. Recupero di un documento FDF come stringa
Visualizzerà qualcosa tipo
|
Vedere anche: fdf_save(), fdf_open_string(), fdf_create() e fdf_close().
La funzione fdf_save() salva un documento FDF. Il risultante documento FDF sarà scritto in filename. Se si omette il parametro filename, la funzione fdf_save() scriverà il documento FDF nel default output di PHP.
Vedere anche: fdf_save_string(), fdf_create() e fdf_close().
La funzione fdf_set_ap() imposta l'apparire di un campo (per es. il valore della chiave /AP). I possibili valori per face sono FDFNormalAP, FDFRolloverAP e FDFDownAP.
La funzione fdf_set_encoding() imposta la codifica dei caratteri per il documento FDF fdf_document. Il parametro encoding deve essere il nome di un codifica valida. I valori attualmente ammessi sono: "Shift-JIS", "UHC", "GBK","BigFive". Una stringa vuota re-imposta la codifica al valore di default PDFDocEncoding/Unicode.
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
fdf_set_file -- Imposta un documento PDF per visualizzare i dati FDF presentiLa funzione fdf_set_file() selezione un differente documento PDF nel quale visualizzare i dati di un form originati da un'altro. Il parametro url deve essere un URL assoluto.
Il frame nel quale visualizzare il documento può essere impostato tramite il parametro target_frame o tramite la funzione fdf_set_target_frame().
Esempio 1. Passaggio di dati FDF a un secondo form
|
Vedere anche fdf_get_file() e fdf_set_target_frame().
La funzione fdf_set_flags() imposta i flag del campo fieldname passato
Vedere anche fdf_set_opt().
La funzione fdf_set_javascript_action() imposta una azione javascript per il campo fieldname passato.
Vedere anche fdf_set_submit_form_action().
La funzione fdf_set_opt() imposta le opzioni del campo fieldname dato.
Vedere anche fdf_set_flags().
La funzione fdf_set_status() imposta il valore per la chiave /STATUS. Quando un client riceve un documento FDF con lo 'status' impostato, ne visualizzerà il valore in una finestra.
Vedere anche fdf_get_status().
(PHP 4 >= 4.0.2, PHP 5)
fdf_set_submit_form_action -- Imposta un'azione per un campo nell'invio di un formLa funzione fdf_set_submit_form_action() imposta un'azione da eseguire nell'invio del form per il campo fieldname.
Vedere anche fdf_set_javascript_action().
Imposta il frame in cui visualizzare il PDF risultante da fdf_save_file().
Vedere anche fdf_save_file().
La funzione fdf_set_value() imposta il campo fieldname al valore value. Il parametro value sarà memorizzato come stringa a meno che non si tratti di una matrice. In questo caso tutti gli elementi della matrice saranno memorizzati in una matrice di valori.
Nota: Nella vecchia versione del toolkit fdf l'ultimo parametro determinava se il valore del campo doveva essere convertito in un PDF Name (isName = 1) o in una stringa PDF (isName = 0). Questo campo non viene più utilizzato con l'attuale versione 5.0. Per motivi di compatibilità è ancora supportato come parametro opzionale a partire da PHP 4.3, ma viene ignorato.
Il supporto per value come matrice è stato aggiunto in PHP 4.3.
Vedere anche fdf_get_value() e fdf_remove_item().
Questa funzione imposta il numero di versione del file FDF fdf_document a version. Alcune caratteristiche supportate da questo modulo sono soltatnto disponibili nelle più recenti versioni di fdf. L'attuale toolkit FDF (5.0) accetta come versione i valori '1.2', '1.3' or '1.4'.
Vedere anche fdf_get_version().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Le funzioni in questa estensione implementano l'accesso client ad un file server utilizzando il File Transfer Protocol (FTP) come definito in http://www.faqs.org/rfcs/rfc959.html.
Usando il modulo FTP vengono definite le seguenti costanti: FTP_ASCII e FTP_BINARY.
Per l'utilizzo delle funzioni FTP con la vostra configurazione PHP, dovrete aggiungere l'opzione --enable-ftp durante l'installazione PHP 4, e --with-ftp nell'installazione di PHP 3.
Esempio 1. FTP
|
Sends an ALLO command to the remote FTP server to allocate 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
|
See also: ftp_put(), and ftp_fput().
Passa alla directory superiore.
Esempio 1. ftp_cdup() example
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedi anche ftp_chdir().
Passa dalla directory corrente alla directory specificata.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. esempio ftp_chdir()
|
Vedi anche ftp_cdup().
Sets the permissions on the remote file specified by filename to mode given as an octal value.
Esempio 1. ftp_chmod() example
|
Returns the new file permissions on success or FALSE on error.
See also chmod().
ftp_close() chiude ftp_stream e rilascia la risorsa. Dopo aver chiamato questa funzione, non e' piu' possibile usare la connessione FTP ed e' necessario crearne una nuova con ftp_connect().
Esempio 1. esempio di funzione ftp_close()
|
Vedere anche ftp_connect()
Restituisce un flusso FTP stream in caso di successo, FALSE in caso di errore.
La funzione ftp_connect() apre una connessione FTP all' host specificato. host non deve essere seguito da barre e non deve essere precedeuto da ftp://. Il parametro port specifica una porta alternativa cui connettersi. Se e' omesso o impostato a zero verra' usata la porta 21, default di FTP.
Il parametro timeout specifica il timeout per tutte le successive operazioni di rete. Se omesso il valore predefinito e' di 90 secondi. Il timeout puo' essere modificato o interrogato in qualsiasi momento con ftp_set_option() e ftp_get_option().
Nota: Il parametro timeout e' disponibile a partire dalla release PHP 4.2.0.
Vedere anche ftp_close(), e ftp_ssl_connect().
ftp_delete() cancella il file specificato da path dal server FTP.
Esempio 1. Esempio di funzione ftp_delete()
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Invia una richiesta SITE EXEC command al server FTP. Restituisce TRUE se il comando viene eseguito correttamente (codice di risposta: 200 da parte del server); altrimenti restituisce FALSE.
Esempio 1. Esempio di funzione ftp_exec()
|
Vedere anche ftp_raw().
(PHP 3>= 3.0.13, PHP 4 , PHP 5)
ftp_fget -- Scarica un file dal server FTP e lo salva in un file apertoftp_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() 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.
(PHP 4 >= 4.2.0, PHP 5)
ftp_get_option -- Richiama vari comportamenti runtime dello stream FTP attualmente in usoNota: 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_SEC | Restituisce l'attuale timeout usato per le operazioni relative alla rete. |
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().
Esegue il login in un dato stream FTP.
Restituisce TRUE se a buon fine, FALSE in caso di errore.
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.
Crea la directory specificata.
Restituisce il nome della directory appena creata se a buon fine, FALSE in caso di errore.
Continues retrieving/sending a file non-blocking.
Esempio 1. ftp_nb_continue() example
|
Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.
(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)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
|
Returns FTP_FAILED, FTP_FINISHED, or FTP_MOREDATA.
See also ftp_nb_get(), ftp_nb_continue(), ftp_fget(), and ftp_get().
(PHP 4 >= 4.3.0, PHP 5)
ftp_nb_fput -- Stores a file from an open file to the FTP server (non-blocking)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
|
Returns FTP_FAILED, FTP_FINISHED, or FTP_MOREDATA.
See also ftp_nb_put(), ftp_nb_continue(), ftp_put() and ftp_fput().
(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)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
|
Esempio 2. Resuming a download with ftp_nb_get()
|
Esempio 3. Resuming a download at position 100 to a new file with ftp_nb_get()
|
In the example above, "newfile" is 100 bytes smaller than "README" on the FTP server because we started reading at offset 100. If we have not have disabled FTP_AUTOSEEK, the first 100 bytes of "newfile" will be '\0'.
See also ftp_nb_fget(), ftp_nb_continue(), ftp_get(), and ftp_fget().
ftp_nb_put() stores local_file on the FTP server, as remote_file. The transfer mode specified must be either FTP_ASCII or FTP_BINARY. The difference between this function and the ftp_put() is that this function uploads the file asynchronously, so your program can perform other operations while the file is being uploaded.
Returns FTP_FAILED, FTP_FINISHED, or FTP_MOREDATA.
Esempio 1. ftp_nb_put() example
|
Esempio 2. Resuming an upload with ftp_nb_put()
|
See also ftp_nb_fput(), ftp_nb_continue(), ftp_put(), and ftp_fput().
Restituisce una array di nomi di file se a buon fine, FALSE in caso di errore.
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() 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.
Restituisce il nome della directory corrente, oppure FALSE in caso di errore.
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.
See Also: ftp_exec()
(PHP 3>= 3.0.13, PHP 4 , PHP 5)
ftp_rawlist -- Restituisce l'elenco dettagliato dei file in una data directoryftp_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() 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.
Elimina la directory specificata.
Restituisce TRUE in caso di successo, FALSE in caso di errore.
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_SEC | Cambia 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. |
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() 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.
Returns a SSL-FTP stream on success or FALSE on error.
ftp_ssl_connect() opens a SSL-FTP connection to the specified host. The port parameter specifies an alternate port to connect to. If it's omitted or set to zero then the default FTP port 21 will be used.
The timeout parameter specifies the timeout for all subsequent network operations. If omitted, the default value is 90 seconds. The timeout can be changed and queried at any time with ftp_set_option() and ftp_get_option().
Why this function may not exist: ftp_ssl_connect() is only available if OpenSSL support is enabled into your version of PHP. If it's undefined and you've compiled FTP support then this is why. For Windows you must compile your own PHP binaries to support this function.
See also ftp_connect().
These functions all handle various operations involved in working with functions.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
(PHP 4 >= 4.0.4, PHP 5)
call_user_func_array -- Call a user function given with an array of parametersCall a user defined function given by function, with the parameters in param_arr. For example:
Esempio 1. call_user_func_array() example
|
See also call_user_func().
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()
Creates an anonymous function from the parameters passed, and returns a unique name for it. Usually the args will be passed as a single quote delimited string, and this is also recommended for the code. The reason for using single quoted strings, is to protect the variable names from parsing, otherwise, if you use double quotes there will be a need to escape the variable names, e.g. \$avar.
You can use this function, to (for example) create a function from information gathered at run time:
Esempio 1. Creating an anonymous function with create_function()
|
Or, perhaps to have general handler function that can apply a set of operations to a list of parameters:
Esempio 2. Making a general processing function with create_function()
and when you run the code above, the output will be:
|
But perhaps the most common use for of lambda-style (anonymous) functions is to create callback functions, for example when using array_walk() or usort()
Esempio 3. Using anonymous functions as callback functions
outputs:
an array of strings ordered from shorter to longer
outputs:
sort it from longer to shorter
outputs:
|
Returns the argument which is at the arg_num'th offset into a user-defined function's argument list. Function arguments are counted starting from zero. func_get_arg() will generate a warning if called from outside of a function definition.
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.
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.
Returns the number of arguments passed into the current user-defined function. func_num_args() will generate a warning if called from outside of a user-defined function.
<?php function foo() { $numargs = func_num_args(); echo "Number of arguments: $numargs\n"; } foo(1, 2, 3); // Prints 'Number of arguments: 3' ?> |
func_num_args() may be used in conjunction with func_get_arg() and func_get_args() to allow user-defined functions to accept variable-length argument lists.
Checks the list of defined functions, both built-in (internal) and user-defined, for function_name. 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().
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().
(PHP 3>= 3.0.4, PHP 4 , PHP 5)
register_shutdown_function -- Register a function for execution on shutdownRegisters the function named by function to be executed when script processing is complete.
Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called.
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.
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.
See also declare() and unregister_tick_function().
(PHP 4 >= 4.0.3, PHP 5)
unregister_tick_function -- De-register a function for execution on each tickDe-registers the function named by function_name so it is no longer executed when a tick is called.
The gettext functions implement an NLS (Native Language Support) API which can be used to internationalize your PHP applications. Please see the gettext documentation for your system for a thorough explanation of these functions or view the docs at http://www.gnu.org/software/gettext/manual/gettext.html.
To use these functions you must download and install the GNU gettext package from http://www.gnu.org/software/gettext/gettext.html
To include GNU gettext support in your PHP build you must add the option --with-gettext[=DIR] where DIR is the gettext install directory, defaults to /usr/local.
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.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
(PHP 4 >= 4.2.0, PHP 5)
bind_textdomain_codeset -- Specify the character encoding in which the messages from the DOMAIN message catalog will be returnedWith bind_textdomain_codeset(), you can set in which encoding will be messages from domain returned by gettext() and similar functions.
The bindtextdomain() function sets the path for a domain. It returns the full pathname for the domain currently being set.
This function allows you to override the current domain for a single message lookup. It also allows you to specify a category.
See also gettext().
This function allows you to override the current domain for a single plural message lookup. It also allows you to specify a category.
See also ngettext().
The dgettext() function allows you to override the current domain for a single message lookup.
See also gettext().
The dngettext() function allows you to override the current domain for a single plural message lookup.
See also ngettext().
This function returns a translated string if one is found in the translation table, or the submitted message if not found. You may use the underscore character '_' as an alias to this function.
Esempio 1. gettext()-check
|
See also setlocale().
ngettext() returns correct plural form of message identified by msgid1 and msgid2 for count n. Some languages have more than one form for plural messages dependent on the count.
This function sets the domain to search within when calls are made to gettext(), usually the named after an application. The previous default domain is returned. Call it with NULL as parameter to get the current setting without changing it.
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. |
Questo calcolerà il fattoriale di 1000 (numero abbastanza grande) molto velocemente.
Somma due numeri GMP. Il risultato, sarà un numero GMP che rappresenta la somma degli argomenti.
Restituisce un valore positivo se a > b, zero se a = b e negativo se a < b.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Divide a per b e restituisce un numero intero. L'arrotondamento del risultato, è definito dal round, che può avere i seguenti valori:
GMP_ROUND_ZERO: Il risultato è troncato verso 0.
GMP_ROUND_PLUSINF: Il risultato è arrotondato verso +infinito.
GMP_ROUND_MINUSINF: Il risultato è arrotondato verso -infinito.
Questa funzione può anche essere richiamata come gmp_div().
Vedere anche gmp_div_r(), gmp_div_qr()
Questa funzione, esegue la divisione tra n e d , restituendo un array, il primo elemento è, [n/d] (il risultato intero della divisione) il secondo è (n - [n/d] * d) (cioè il resto della divisone).
Vedere la funzione gmp_div_q() per la descrizione dell'argomento round.
Vedere anche gmp_div_q(), gmp_div_r().
Calcola il resto di una divisione intera fra n e d. Se non è zero, il resto ha il segno dell'argomento n.
Vedi la funzione gmp_div_q() per la descrizione dell'argomento round.
Vedere anche gmp_div_q(), gmp_div_qr()
Divide n per d, usando un algoritmo di "esatta divisione". Questa funzione, restituisce un valore corretto solo quando è noto a priori che d divide n.
Calcola il massimo comune divisore (MCD) di a e b. Il risultato è sempre positivo, anche se uno o entrambi gli operatori sono negativi.
Calcola g, s e t, in questo modo a*s + b*t = g = gcd(a,b), dove MCD è il massimo comune divisore. Restituisce un array con i rispettivi argomenti, cioè, g, s e t.
Restituisce la distanza di hamming tra a e b. Entrambe gli operandi dovrebbero essere non-negativi.
Crea un numero GMP partendo da un intero o da una stringa. La stringa può essere decimale o esadecimale. Nell'ultimo caso, la stringa dovrebbe iniziare con 0x.
Nota: Non è necessario chiamare uesta funzione se si vogliono usare interi o stringhe al posto di numeri GMP nelle funzioni GMP, come gmp_add(). Se se questa conversione è possibile e necessaria, gli argomenti delle funzioni vengono automaticamente convertiti in numeri GMP, usando le stesse regole di gmp_init().
Questa funzione converte un numero GMP in un intero.
Avvertimento |
Questa funzione restituisce un risultato utile, solo se il numero attualmente fornito al PHP è un intero (per esempio, un tipo signed long). Se desideri solo stampare il numero GMP, usa gmp_strval(). |
Calcola l'inverso di a modulo b. Restituisce un valore FALSE se l'inversione non esiste.
Calcola il simbolo di Jacobi di a e p. p p potrebbe essere dispari e deve essere positivo.
Calcolo del Legendre symbol di a e p. p potrebbe essere dispari e deve essere positivo.
Calcola il modulo di n rispetto a d. Il risultato è sempre non-negativo, il segno di d viene ignorato.
Moltiplica a per b e restituisce il risultato.
Restituisce un valore vero TRUE se a è un quadrato perfetto,falso FALSE se non lo è.
Vedere anche: gmp_sqrt(), gmp_sqrtrm().
Eleva la base base ad una potenza exp. Nel caso di 0^0 il risultato sarà 1. L'argomento exp non può essere negativo.
Calcola il (base elevato a potenza exp) modulo mod. Se exp è negativo, il risultato sarà indefinito.
Se questa funzione da come risultato 0, a non è primo. Se sarà 1, allora a è "probabilmente" primo. Invece se il risultato è 2, allora a sarà sicuramente primo. I valori "attendibili" di reps possono variare da 5 a 10 (di default 10); un valore più alto fa diminuire la probabilità che un numero non primo passi come "probabile" primo.
La funzione usa il test probabilistico di Miller-Rabin.
Genera un numero casuale. Il numero, sarà lungo un numero di WORD (2 byte) non superiore all'argomento limiter. Se l'argomento limiter è negativo, il numero generato sarà anch'esso negativo.
Cerca in a, partendo dal bit startverso i bit più significativi, fermandosi sul primo bit nullo, di cui restituisce l'indice.
Cerca in a, partendo dal bit start, verso i bit più significativi, fermandosi sul primo bit nullo, di cui restituisce l'indice.
Sets bit index in a. set_clear definisce se il bit è settato su 0 o su 1. Di default il bit è settato a 1.
Restituisce il segno di a : 1 se a è positivo e -1 se è negativo.
Restituisce un array con due valori, il primo è la radice quadrata (fornita come intero) di a (vedere anche gmp_sqrt()), e il secondo è il resto (cioè, la differenza tra a e il primo elemento al quadrato).
Converte un numero GMP in una stringa rappresentato in base base. La base di default è 10. Le basi consentite variano dal 2 al 36.
Queste funzioni permettono di modificare l'output inviato verso un browser attraverso manipolazioni a livello di protocollo HTTP.
header() si utilizza per inviare header HTTP. Per maggiorni informazioni riguardanti gli header HTTP si veda la risorsa HTTP 1.1 specification.
L'argomento opzionale replace indica se l'header inviato deve sostituirne uno simile spedito precedentemente, o accodarsi al primo dello stesso tipo. Per default la funzione sostituisce l'header precedente, ma se viene passato FALSE come secondo argomento vengono forzate intestazioni multiple. Per esempio:
Ci sono due casi speciali di chiamate di header. Il primo è "Location". Location non trasmette solo un header al browser, ma anche un REDIRECT con codice di stato (302).
header("Location: http://www.php.net/"); /* Ridireziona il browser al sito di PHP */ exit; /* Assicura che il codice sottostante non sia eseguito dopo il redirezionamento. */ |
Nota: HTTP/1.1 richiede un URI assoluto come argomento di Location: composto da schema, hostname, e path assoluto, ma alcuni clients possono accettare anche URIs relativi. E' possibile usare $HTTP_SERVER_VARS['HTTP_HOST'], $HTTP_SERVER_VARS['PHP_SELF'] e dirname() per creare URI assoluti da URI relativi in modo automatico:
Il secondo caso speciale è esemplificato dalle intestazioni che iniziano con la stringa, "HTTP/" (le maiuscole non sono discriminanti), che è usato per inviare codici di stato HTTP. Per esempio, se si è configurato Apache per usare script PHP per la manipolazione di richieste fallite (usando la direttiva ErrorDocument), potete desiderare di assicurarvi che il vostro script generi il codice adeguato.
Nota: In PHP 3, questo funziona solo se PHP è compilato come modulo Apache. Potete ottenere lo stesso effetto usando l'header Status.
Spesso gli scrit PHP generano contenuti dinamici, se volete evitare che i contenuti vengano mantenuti nella cache di browser o proxy, potete forzare il loro comportamento con questa direttiva:
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Data passata header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // sempre modificato header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1 header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); // HTTP/1.0 |
Nota: E' possibile che alcune pagine rimangano in chache anche dopo l'uso degli header descritti sopra. Ci sono delle opzioni che l'utente può settare dal browser, capaci di modificare i comportamenti di default del caching. Per trasmettere efficacemente gli header descritti, bisogna che sia inattiva ogni regolazione che può forzare comportamenti contrari.
Inoltre, session_cache_limiter() e e la configurazione session.cache_limiter possono essere usate per generare automaticamente i corretti header relativi al caching durante l'uso delle sessioni.
Bisogna ricordare che la funzioneheader() va chiamata prima di qualsiasi output HTML o PHP (anche righe o spazi vuoti). E' un errore comune leggere files con funzioni include(), o require() (o altre funzioni capaci di accedere a files), che possano emettere in output spazi o linee vuote prima di una chiamata della funzione header(). Lo stesso problema esiste nell'utilizzare file PHP/HTML.
<?php require("user_logging.inc") ?> <?php header ("Content-type: audio/x-pn-realaudio"); ?> // Non funziona, notate le linee vuote sopra |
Nota: In PHP 4, potete usare il buffering dell'output per aggirare questo problema, evitando ogni output al browser trattenedolo al server fino a che non gli si impone l'invio. Si può fare questa operazione chiamando ob_start() e ob_end_flush() nello script, o settando la direttiva di configurazione output_buffering nel file php.ini o nel file di configurazione del server.
Se desiderate che l'utente sia spinto a salvare i dati trasmessi per esempio utilizzando un file PDF, potete usare l'header Content-Disposition, che vi permette di dare un nome al file e forzare il browser a mostrare la finestra di dialogo save.
<?php header("Content-type: application/pdf"); header("Content-Disposition: attachment; filename=downloaded.pdf"); /* ... manda in output un file pdf ... */ |
Nota: Per un bug di Microsoft Internet Explorer 4.01 qusto sistema non funziona. Non ci sono soluzioni. C'è un altro bug in Microsoft Internet Explorer 5.5 che impedisce il giusto funzionamento, ma è possibile risolverlo con l'upgrade del Service Pack 2 o superiore.
Vedi anche headers_sent(), setcookie(), e la sezione Autenticazione HTTP usando PHP.
headers_list() will return a numerically indexed array of headers to be sent to the browser / client. To determine whether or not these headers have been sent yet, use headers_sent().
Esempio 1. Examples using headers_list()
this will output :
|
See Also: headers_sent(), header(), and setcookie().
Questa funzione restituisce TRUE se gli header HTTP sono stati spedite correttamente, FALSE in caso contrario.
Vedi anche header()
setcookie() definisce un cookie da inviare insieme alle altre informazioni di header. I cookie devono essere spediti prima di qualsiasi altra intestazione (questa è una restrizione dei cookies, non di PHP). E' necessario perciò chiamare la funzione setcookie() prima di qualsiasi tags, anche <html> o <head>.
Tutti gli argomenti della funzione eccetto name sono opzionali. Se viene passato alla funzione solo l'argomento name, il cookie registrato con quel nome verrà cancellato dal client su cui è archiviato. E' possibile sostituire gli argomenti che non si intende specificare utitlizzando una stringa vuota (""). Gli argomenti expire e secure che richiedono numeri interi, non possono essere omessi inserendo una stringa vuota, per questo scopo si usa (0). L'argomento expire è un normale intero Unix Timestamp ottenibile grazie alle funzioni time() o mktime(). secure sta ad indicare che il cookie dovrebbe essere trasmesso soltanto attraverso un collegamento sicuro di tipo HTTPS.
Errori comuni:
I cookie diventano disponibili soltanto dalla pagina successiva a quella che li ha generati, o dopo il ricaricamento di questa.
I cookie devono essere cancellati specificando gli stessi parametri con cui sono stati creati.
In PHP 3, chiamate successive di setcookie() nello stesso script sono eseguite in ordine inverso. Se state provando a cancellare un cookie prima dell' inserimento di un altro cookie, dovete creare il secondo prima della cancellazione del primo. In PHP 4, chiamate successive di setcookie() invece, sono eseguite secondo l'ordine di chiamata.
Alcuni esempi sul modo di spedire cookie:
Gli esempi mostrano come cancellare i cookie introdotti nell'esempio precedente:
Si noti che i valori salvati nei cookies sono automaticamente codificati per la trasmissione via URL (urlencoded) quando il cookie viene inviato, e che al momento del richiamo sono automaticamente decodificati e assegnati ad una variabile che ha lo stesso nome del cookie. Per vedere il contenuto di un cookie in uno script, si usa una di queste due sintassi:
Potete registrare array in un cookie usando la notazione degli array al posto del nome del cookie. Questo equivale alla spedizione di tanti cookie quanti sono gli elementi dell'array, ma si ha un vantaggio: quando il cookie è ricevuto, tutti i suoi valori sono ordinati in un singolo array che ha per nome il nome del cookie:
setcookie ("cookie[three]", "cookiethree"); setcookie ("cookie[two]", "cookietwo"); setcookie ("cookie[one]", "cookieone"); if (isset ($cookie)) { while (list ($name, $value) = each ($cookie)) { echo "$name == $value<br>\n"; } } |
Per saperne di più sui cookies, Netscape's cookie specification è la risorsa giusta http://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() is exactly the same as setcookie() except that the cookie value will not be automatically urlencoded when sent to the browser.
See also header(), setcookie() and the cookies section.
Hyperwave has been developed at IICM in Graz. It started with the name Hyper-G and changed to Hyperwave when it was commercialised (in 1996).
Hyperwave is not free software. The current version, 5.5 is available at http://www.hyperwave.com/. A time limited version can be ordered for free (30 days).
See also the Hyperwave API module.
Hyperwave is an information system similar to a database (HIS, Hyperwave Information Server). Its focus is the storage and management of documents. A document can be any possible piece of data that may as well be stored in file. Each document is accompanied by its object record. The object record contains meta data for the document. The meta data is a list of attributes which can be extended by the user. Certain attributes are always set by the Hyperwave server, other may be modified by the user. An attribute is a name/value pair of the form name=value. The complete object record contains as many of those pairs as the user likes. The name of an attribute does not have to be unique, e.g. a title may appear several times within an object record. This makes sense if you want to specify a title in several languages. In such a case there is a convention, that each title value is preceded by the two letter language abbreviation followed by a colon, e.g. 'en:Title in English' or 'ge:Titel in deutsch'. Other attributes like a description or keywords are potential candidates. You may also replace the language abbreviation by any other string as long as it separated by colon from the rest of the attribute value.
Each object record has native a string representation with each name/value pair separated by a newline. The Hyperwave extension also knows a second representation which is an associated array with the attribute name being the key. Multilingual attribute values itself form another associated array with the key being the language abbreviation. Actually any multiple attribute forms an associated array with the string left to the colon in the attribute value being the key. (This is not fully implemented. Only the attributes Title, Description and Keyword are treated properly yet.)
Besides the documents, all hyper links contained in a document are stored as object records as well. Hyper links which are in a document will be removed from it and stored as individual objects, when the document is inserted into the database. The object record of the link contains information about where it starts and where it ends. In order to gain the original document you will have to retrieve the plain document without the links and the list of links and reinsert them. The functions hw_pipedocument() and hw_gettext() do this for you. The advantage of separating links from the document is obvious. Once a document to which a link is pointing to changes its name, the link can easily be modified accordingly. The document containing the link is not affected at all. You may even add a link to a document without modifying the document itself.
Saying that hw_pipedocument() and hw_gettext() do the link insertion automatically is not as simple as it sounds. Inserting links implies a certain hierarchy of the documents. On a web server this is given by the file system, but Hyperwave has its own hierarchy and names do not reflect the position of an object in that hierarchy. Therefore creation of links first of all requires a mapping from the Hyperwave hierarchy and namespace into a web hierarchy respective web namespace. The fundamental difference between Hyperwave and the web is the clear distinction between names and hierarchy in Hyperwave. The name does not contain any information about the objects position in the hierarchy. In the web the name also contains the information on where the object is located in the hierarchy. This leads to two possibles ways of mapping. Either the Hyperwave hierarchy and name of the Hyperwave object is reflected in the URL or the name only. To make things simple the second approach is used. Hyperwave object with name my_object is mapped to http://host/my_object disregarding where it resides in the Hyperwave hierarchy. An object with name parent/my_object could be the child of my_object in the Hyperwave hierarchy, though in a web namespace it appears to be just the opposite and the user might get confused. This can only be prevented by selecting reasonable object names.
Having made this decision a second problem arises. How do you involve PHP? The URL http://host/my_object will not call any PHP script unless you tell your web server to rewrite it to e.g. http://host/php_script/my_object and the script php_script evaluates the $PATH_INFO variable and retrieves the object with name my_object from the Hyperwave server. Their is just one little drawback which can be fixed easily. Rewriting any URL would not allow any access to other document on the web server. A PHP script for searching in the Hyperwave server would be impossible. Therefore you will need at least a second rewriting rule to exclude certain URLs like all e.g. starting with http://host/Hyperwave This is basically sharing of a namespace by the web and Hyperwave server.
Based on the above mechanism links are insert into documents.
It gets more complicated if PHP is not run as a server module or CGI script but as a standalone application e.g. to dump the content of the Hyperwave server on a CD-ROM. In such a case it makes sense to retain the Hyperwave hierarchy and map in onto the file system. This conflicts with the object names if they reflect its own hierarchy (e.g. by choosing names including '/'). Therefore '/' has to be replaced by another character, e.g. '_'.
The network protocol to communicate with the Hyperwave server is called HG-CSP (Hyper-G Client/Server Protocol). It is based on messages to initiate certain actions, e.g. get object record. In early versions of the Hyperwave Server two native clients (Harmony, Amadeus) were provided for communication with the server. Those two disappeared when Hyperwave was commercialised. As a replacement a so called wavemaster was provided. The wavemaster is like a protocol converter from HTTP to HG-CSP. The idea is to do all the administration of the database and visualisation of documents by a web interface. The wavemaster implements a set of placeholders for certain actions to customise the interface. This set of placeholders is called the PLACE Language. PLACE lacks a lot of features of a real programming language and any extension to it only enlarges the list of placeholders. This has led to the use of JavaScript which IMO does not make life easier.
Adding Hyperwave support to PHP should fill in the gap of a missing programming language for interface customisation. It implements all the messages as defined by the HG-CSP but also provides more powerful commands to e.g. retrieve complete documents.
Hyperwave has its own terminology to name certain pieces of information. This has widely been taken over and extended. Almost all functions operate on one of the following data types.
object ID: An unique integer value for each object in the Hyperwave server. It is also one of the attributes of the object record (ObjectID). Object ids are often used as an input parameter to specify an object.
object record: A string with attribute-value pairs of the form attribute=value. The pairs are separated by a carriage return from each other. An object record can easily be converted into an object array with hw_object2array(). Several functions return object records. The names of those functions end with obj.
object array: An associative array with all attributes of an object. The keys are the attribute names. If an attribute occurs more than once in an object record it will result in another indexed or associative array. Attributes which are language depended (like the title, keyword, description) will form an associative array with the keys set to the language abbreviations. All other multiple attributes will form an indexed array. PHP functions never return object arrays.
hw_document: This is a complete new data type which holds the actual document, e.g. HTML, PDF etc. It is somewhat optimized for HTML documents but may be used for any format.
Several functions which return an array of object records do also return an associative array with statistical information about them. The array is the last element of the object record array. The statistical array contains the following entries:
Number of object records with attribute PresentationHints set to Hidden.
Number of object records with attribute PresentationHints set to CollectionHead.
Number of object records with attribute PresentationHints set to FullCollectionHead.
Index in array of object records with attribute PresentationHints set to CollectionHead.
Index in array of object records with attribute PresentationHints set to FullCollectionHead.
Total: Number of object records.
The Hyperwave extension is best used when PHP is compiled as an Apache module. In such a case the underlying Hyperwave server can be hidden from users almost completely if Apache uses its rewriting engine. The following instructions will explain this.
Since PHP with Hyperwave support built into Apache is intended to replace the native Hyperwave solution based on Wavemaster, we will assume that the Apache server will only serve as a Hyperwave web interface for these examples. This is not necessary but it simplifies the configuration. The concept is quite simple. First of all you need a PHP script which evaluates the $_ENV['PATH_INFO'] variable and treats its value as the name of a Hyperwave object. Let's call this script 'Hyperwave'. The URL http://your.hostname/Hyperwave/name_of_object would than return the Hyperwave object with the name 'name_of_object'. Depending on the type of the object the script has to react accordingly. If it is a collection, it will probably return a list of children. If it is a document it will return the mime type and the content. A slight improvement can be achieved if the Apache rewriting engine is used. From the users point of view it would be more straight forward if the URL http://your.hostname/name_of_object would return the object. The rewriting rule is quite easy:
Now every URL relates to an object in the Hyperwave server. This causes a simple to solve problem. There is no way to execute a different script, e.g. for searching, than the 'Hyperwave' script. This can be fixed with another rewriting rule like the following: This will reserve the directory /usr/local/apache/htdocs/hw for additional scripts and other files. Just make sure this rule is evaluated before the one above. There is just a little drawback: all Hyperwave objects whose name starts with 'hw/' will be shadowed. So, make sure you don't use such names. If you need more directories, e.g. for images just add more rules or place them all in one directory. Before you put those instructions, don't forget to turn on the rewriting engine with You will need scripts:to return the object itself
to allow searching
to identify yourself
to set your profile
one for each additional function like to show the object attributes, to show information about users, to show the status of the server, etc.
As an alternative to the Rewrite Engine, you can also consider using the Apache ErrorDocument directive, but be aware, that ErrorDocument redirected pages cannot receive POST data.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Hyperwave configuration options
Name | Default | Changeable |
---|---|---|
hyperwave.allow_persistent | "0" | PHP_INI_SYSTEM |
hyperwave.default_port | "418" | PHP_INI_ALL |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
There are still some things to do:
The hw_InsertDocument has to be split into hw_insertobject() and hw_putdocument().
The names of several functions are not fixed, yet.
Most functions require the current connection as its first parameter. This leads to a lot of typing, which is quite often not necessary if there is just one open connection. A default connection will improve this.
Conversion form object record into object array needs to handle any multiple attribute.
Converts an object_array into an object record. Multiple attributes like 'Title' in different languages are treated properly.
See also hw_objrec2array().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Returns an array of object ids. Each id belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.
Returns an array of object records. Each object record belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.
Returns FALSE if connection is not a valid connection index, otherwise TRUE. Closes down the connection to a Hyperwave server with the given connection index.
Opens a connection to a Hyperwave server and returns a connection index on success, or FALSE if the connection could not be made. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple connections open at once. Keep in mind, that the password is not encrypted.
See also hw_pconnect().
(PHP 3>= 3.0.3, PHP 4 )
hw_connection_info -- Prints information about the connection to Hyperwave server
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Copies the objects with object ids as specified in the second parameter to the collection with the id destination id.
The value return is the number of copied objects.
See also hw_mv().
Deletes the object with the given object id in the second parameter. It will delete all instances of the object.
Returns TRUE if no error occurs otherwise FALSE.
See also hw_mv().
Returns an th object id of the document to which anchorID belongs.
Returns an th object record of the document to which anchorID belongs.
Returns the object record of the document.
For backward compatibility, hw_documentattributes() is also accepted. This is deprecated, however.
See also hw_document_bodytag(), and hw_document_size().
Returns the BODY tag of the document. If the document is an HTML document the BODY tag should be printed before the document.
See also hw_document_attributes(), and hw_document_size().
For backward compatibility, hw_documentbodytag() is also accepted. This is deprecated, however.
Returns the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record.
See also hw_document_attributes(), hw_document_size(), and hw_document_setcontent().
Sets or replaces the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record. If you provide this information in the content of the document too, the Hyperwave server will change the object record accordingly when the document is inserted. Probably not a very good idea. If this functions fails the document will retain its old content.
See also hw_document_attributes(), hw_document_size(), and hw_document_content().
Returns the size in bytes of the document.
See also hw_document_bodytag(), and hw_document_attributes().
For backward compatibility, hw_documentsize() is also accepted. This is deprecated, however.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Uploads the text document to the server. The object record of the document may not be modified while the document is edited. This function will only works for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.
See also hw_pipedocument(), hw_free_document(), hw_document_bodytag(), hw_document_size(), hw_output_document(), and hw_gettext().
Returns the last error number. If the return value is 0 no error has occurred. The error relates to the last command.
Returns a string containing the last error message or 'No Error'. If FALSE is returned, this function failed. The message relates to the last command.
Frees the memory occupied by the Hyperwave document.
Returns an array of object ids with anchors of the document with object ID objectID.
Returns an array of object records with anchors of the document with object ID objectID.
Returns the object record for the object with ID objectID. It will also lock the object, so other users cannot access it until it is unlocked.
See also hw_unlock(), and hw_getobject().
Returns an array of object ids. Each object ID belongs to a child collection of the collection with ID objectID. The function will not return child documents.
See also hw_children(), and hw_getchilddoccoll().
Returns an array of object records. Each object records belongs to a child collection of the collection with ID objectID. The function will not return child documents.
See also hw_childrenobj(), and hw_getchilddoccollobj().
Returns array of object ids for child documents of a collection.
See also hw_children(), and hw_getchildcoll().
Returns an array of object records for child documents of a collection.
See also hw_childrenobj(), and hw_getchildcollobj().
Returns the object record for the object with ID objectID if the second parameter is an integer. If the second parameter is an array of integer the function will return an array of object records. In such a case the last parameter is also evaluated which is a query string.
The query string has the following syntax:
<expr> ::= "(" <expr> ")" |
"!" <expr> | /* NOT */
<expr> "||" <expr> | /* OR */
<expr> "&&" <expr> | /* AND */
<attribute> <operator> <value>
<attribute> ::= /* any attribute name (Title, Author, DocumentType ...) */
<operator> ::= "=" | /* equal */
"<" | /* less than (string compare) */
">" | /* greater than (string compare) */
"~" /* regular expression matching */
The query allows to further select certain objects from the list of given objects. Unlike the other query functions, this query may use not indexed attributes. How many object records are returned depends on the query and if access to the object is allowed.
See also hw_getandlock(), and hw_getobjectbyquery().
Searches for objects on the whole server and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.
The query will only work with indexed attributes.
See also hw_getobjectbyqueryobj().
Searches for objects in collection with ID objectID and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.
The query will only work with indexed attributes.
See also hw_getobjectbyquerycollobj().
Searches for objects in collection with ID objectID and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.
The query will only work with indexed attributes.
See also hw_getobjectbyquerycoll().
Searches for objects on the whole server and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.
The query will only work with indexed attributes.
See also hw_getobjectbyquery().
Returns an indexed array of object ids. Each object id belongs to a parent of the object with ID objectID.
Returns an indexed array of object records plus an associated array with statistical information about the object records. The associated array is the last entry of the returned array. Each object record belongs to a parent of the object with ID objectID.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Returns a remote document. Remote documents in Hyperwave notation are documents retrieved from an external source. Common remote documents are for example external web pages or queries in a database. In order to be able to access external sources through remote documents Hyperwave introduces the HGI (Hyperwave Gateway Interface) which is similar to the CGI. Currently, only ftp, http-servers and some databases can be accessed by the HGI. Calling hw_getremote() returns the document from the external source. If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.
See also hw_getremotechildren().
Returns the children of a remote document. Children of a remote document are remote documents itself. This makes sense if a database query has to be narrowed and is explained in Hyperwave Programmers' Guide. If the number of children is 1 the function will return the document itself 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().
Returns the object records of all anchors pointing to the object with ID objectID. The object can either be a document or an anchor of type destination.
See also hw_getanchors().
Returns the document with object ID objectID. If the document has anchors which can be inserted, they will be inserted already. The optional parameter rootID/prefix can be a string or an integer. If it is an integer it determines how links are inserted into the document. The default is 0 and will result in links that are constructed from the name of the link's destination object. This is useful for web applications. If a link points to an object with name 'internet_movie' the HTML link will be <A HREF="/internet_movie">. The actual location of the source and destination object in the document hierarchy is disregarded. You will have to set up your web browser, to rewrite that URL to for example '/my_script.php3/internet_movie'. 'my_script.php3' will have to evaluate $PATH_INFO and retrieve the document. All links will have the prefix '/my_script.php3/'. If you do not want this you can set the optional parameter rootID/prefix to any prefix which is used instead. Is this case it has to be a string.
If rootID/prefix is an integer and unequal to 0 the link is constructed from all the names starting at the object with the id rootID/prefix separated by a slash relative to the current object. If for example the above document 'internet_movie' is located at 'a-b-c-internet_movie' with '-' being the separator between hierarchy levels on the Hyperwave server and the source document is located at 'a-b-d-source' the resulting HTML link would be: <A HREF="../c/internet_movie">. This is useful if you want to download the whole server content onto disk and map the document hierarchy onto the file system.
This function will only work for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.
See also hw_pipedocument(), hw_free_document(), hw_document_bodytag(), hw_document_size(), and hw_output_document().
Identifies as user with username and password. Identification is only valid for the current session. I do not thing this function will be needed very often. In most cases it will be easier to identify with the opening of the connection.
See also hw_connect().
Checks whether a set of objects (documents or collections) specified by the object_id_array is part of the collections listed in collection_id_array. When the fourth parameter return_collections is 0, the subset of object ids that is part of the collections (i.e., the documents or collections that are children of one or more collections of collection ids or their subcollections, recursively) is returned as an array. When the fourth parameter is 1, however, the set of collections that have one or more objects of this subset as children are returned as an array. This option allows a client to, e.g., highlight the part of the collection hierarchy that contains the matches of a previous query, in a graphical overview.
Returns information about the current connection. The returned string has the following format: <Serverstring>, <Host>, <Port>, <Username>, <Port of Client>, <Byte swapping>
Inserts a new collection with attributes as in object_array into collection with object ID objectID.
Inserts a new document with attributes as in object_record into collection with object ID parentID. This function inserts either an object record only or an object record and a pure ascii text in text if text is given. If you want to insert a general document of any kind use hw_insertdocument() instead.
See also hw_insertdocument(), and hw_inscoll().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Uploads a document into the collection with parent_id. The document has to be created before with hw_new_document(). Make sure that the object record of the new document contains at least the attributes: Type, DocumentType, Title and Name. Possibly you also want to set the MimeType. The functions returns the object id of the new document or FALSE.
See also hw_pipedocument().
Inserts an object into the server. The object can be any valid hyperwave object. See the HG-CSP documentation for a detailed information on how the parameters have to be.
Note: If you want to insert an Anchor, the attribute Position has always been set either to a start/end value or to 'invisible'. Invisible positions are needed if the annotation has no corresponding link in the annotation text.
See also hw_pipedocument(), hw_insertdocument(), hw_insdoc(), and hw_inscoll().
Maps a global object id on any hyperwave server, even those you did not connect to with hw_connect(), onto a virtual object id. This virtual object id can then be used as any other object id, e.g. to obtain the object record with hw_getobject(). The server id is the first part of the global object id (GOid) of the object which is actually the IP number as an integer.
Note: In order to use this function you will have to set the F_DISTRIBUTED flag, which can currently only be set at compile time in hg_comm.c. It is not set by default. Read the comment at the beginning of hg_comm.c
This command allows to remove, add, or modify individual attributes of an object record. The object is specified by the Object ID object_to_change. The first array remove is a list of attributes to remove. The second array add is a list of attributes to add. In order to modify an attribute one will have to remove the old one and add a new one. hw_modifyobject() will always remove the attributes before it adds attributes unless the value of the attribute to remove is not a string or array.
The last parameter determines if the modification is performed recursively. 1 means recursive modification. If some of the objects cannot be modified they will be skipped without notice. hw_error() may not indicate an error though some of the objects could not be modified.
The keys of both arrays are the attributes name. The value of each array element can either be an array, a string or anything else. If it is an array each attribute value is constructed by the key of each element plus a colon and the value of each element. If it is a string it is taken as the attribute value. An empty string will result in a complete removal of that attribute. If the value is neither a string nor an array but something else, e.g. an integer, no operation at all will be performed on the attribute. This is necessary if you want to to add a completely new attribute not just a new value for an existing attribute. If the remove array contained an empty string for that attribute, the attribute would be tried to be removed which would fail since it doesn't exist. The following addition of a new value for that attribute would also fail. Setting the value for that attribute to e.g. 0 would not even try to remove it and the addition will work.
If you would like to change the attribute 'Name' with the current value 'books' into 'articles' you will have to create two arrays and call hw_modifyobject().
Nota: Multilingual attributes, e.g. 'Title', can be modified in two ways. Either by providing the attributes value in its native form 'language':'title' or by providing an array with elements for each language as described above. The above example would than be:
Nota: This will remove all attributes with the name 'Title' and adds a new 'Title' attribute. This comes in handy if you want to remove attributes recursively.
Nota: If you need to delete all attributes with a certain name you will have to pass an empty string as the attribute value.
Nota: Only the attributes 'Title', 'Description' and 'Keyword' will properly handle the language prefix. If those attributes don't carry a language prefix, the prefix 'xx' will be assigned.
Nota: The 'Name' attribute is somewhat special. In some cases it cannot be complete removed. You will get an error message 'Change of base attribute' (not clear when this happens). Therefore you will always have to add a new Name first and than remove the old one.
Nota: You may not surround this function by calls to hw_getandlock() and hw_unlock(). hw_modifyobject() does this internally.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Moves the objects with object ids as specified in the second parameter from the collection with id source_id to the collection with the id destination_id. If the destination id is 0 the objects will be unlinked from the source collection. If this is the last instance of that object it will be deleted. If you want to delete all instances at once, use hw_deleteobject().
The value returned is the number of moved objects.
See also hw_cp(), and hw_deleteobject().
Returns a new Hyperwave document with document data set to document_data and object record set to object_record. The length of the document_data has to passed in document_sizeThis function does not insert the document into the Hyperwave server.
See also hw_free_document(), hw_document_size(), hw_document_bodytag(), hw_output_document(), and hw_insertdocument().
Converts an object_record into an object array. The keys of the resulting array are the attributes names. Multi-value attributes like 'Title' in different languages form its own array. The keys of this array are the left part to the colon of the attribute value. This left part must be two characters long. Other multi-value attributes without a prefix form an indexed array. If the optional parameter is missing the attributes 'Title', 'Description' and 'Keyword' are treated as language attributes and the attributes 'Group', 'Parent' and 'HtmlAttr' as non-prefixed multi-value attributes. By passing an array holding the type for each attribute you can alter this behaviour. The array is an associated array with the attribute name as its key and the value being one of HW_ATTR_LANG or HW_ATTR_NONE.
See also hw_array2objrec().
Prints the document without the BODY tag.
For backward compatibility, hw_outputdocument() is also accepted. This is deprecated, however.
Returns a connection index on success, or FALSE if the connection could not be made. Opens a persistent connection to a Hyperwave server. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple persistent connections open at once.
See also hw_connect().
Returns the Hyperwave document with object ID objectID. If the document has anchors which can be inserted, they will have been inserted already. The document will be transferred via a special data connection which does not block the control connection.
See also hw_gettext() for more on link insertion, hw_free_document(), hw_document_size(), hw_document_bodytag(), and hw_output_document().
Returns the object ID of the hyperroot collection. Currently this is always 0. The child collection of the hyperroot is the root collection of the connected server.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Unlocks a document, so other users regain access.
See also hw_getandlock().
Returns an array of users currently logged into the Hyperwave server. Each entry in this array is an array itself containing the elements id, name, system, onSinceDate, onSinceTime, TotalTime and self. 'self' is 1 if this entry belongs to the user who initiated the request.
Hyperwave has been developed at IICM in Graz. It started with the name Hyper-G and changed to Hyperwave when it was commercialised (in 1996).
Hyperwave is not free software. The current version, 5.5, is available at http://www.hyperwave.com/. A time limited version can be ordered for free (30 days).
See also the Hyperwave module.
Hyperwave is an information system similar to a database (HIS, Hyperwave Information Server). Its focus is the storage and management of documents. A document can be any possible piece of data that may as well be stored in file. Each document is accompanied by its object record. The object record contains meta data for the document. The meta data is a list of attributes which can be extended by the user. Certain attributes are always set by the Hyperwave server, other may be modified by the user.
Since 2001 there is a Hyperwave SDK available. It supports Java, JavaScript and C++. This PHP Extension is based on the C++ interface. In order to activate the hwapi support in PHP you will have to install the Hyperwave SDK first.
The integration with Apache and possible other servers is already described in the Hyperwave module which has been the first extension to connect a Hyperwave Server.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Hyperwave API configuration options
Name | Default | Changeable |
---|---|---|
hwapi.allow_persistent | "0" | PHP_INI_SYSTEM |
The API provided by the HW_API extension is fully object oriented. It is very similar to the C++ interface of the Hyperwave SDK. It consist of the following classes.
HW_API
HW_API_Object
HW_API_Attribute
HW_API_Error
HW_API_Content
HW_API_Reason
Each class has certain method, whose names are identical to its counterparts in the Hyperwave SDK. Passing arguments to this function differs from all the other PHP extensions but is close to the C++ API of the HW SDK. Instead of passing several parameters they are all put into an associated array and passed as one parameter. The names of the keys are identical to those documented in the HW SDK. The common parameters are listed below. If other parameters are required they will be documented if needed.
objectIdentifier The name or id of an object, e.g. "rootcollection", "0x873A8768 0x00000002".
parentIdentifier The name or id of an object which is considered to be a parent.
object An instance of class HW_API_Object.
parameters An instance of class HW_API_Object.
version The version of an object.
mode An integer value determine the way an operation is executed.
attributeSelector Any array of strings, each containing a name of an attribute. This is used if you retrieve the object record and want to include certain attributes.
objectQuery A query to select certain object out of a list of objects. This is used to reduce the number of objects which was delivered by a function like hw_api->children() or hw_api->find().
(no version information, might be only in CVS)
hw_api_attribute->langdepvalue -- Returns value for a given languageReturns the value in the given language of the attribute.
See also hwapi_attribute_value().
(no version information, might be only in CVS)
hw_api_attribute->value -- Returns value of the attributeReturns the value of the attribute.
See also hwapi_attribute_key(), hwapi_attribute_values().
(no version information, might be only in CVS)
hw_api_attribute->values -- Returns all values of the attributeReturns all values of the attribute as an array of strings.
See also hwapi_attribute_value().
(no version information, might be only in CVS)
hw_api_attribute -- Creates instance of class hw_api_attributeCreates a new instance of hw_api_attribute with the given name and value.
This function checks in an object or a whole hiearchie of objects. The parameters array contains the required element 'objectIdentifier' and the optional element 'version', 'comment', 'mode' and 'objectQuery'. 'version' sets the version of the object. It consists of the major and minor version separated by a period. If the version is not set, the minor version is incremented. 'mode' can be one of the following values:
Checks in and commits the object. The object must be a document.
If the object to check in is a collection, all children will be checked in recursively if they are documents. Trying to check in a collection would result in an error.
Checks in an object even if it is not under version control.
Check if the new version is different from the last version. Unless this is the case the object will be checked in.
Keeps the time modified from the most recent object.
The object is not automatically committed on check-in.
See also hwapi_checkout().
This function checks out an object or a whole hiearchie of objects. The parameters array contains the required element 'objectIdentifier' and the optional element 'version', 'mode' and 'objectQuery'. 'mode' can be one of the following values:
Checks out an object. The object must be a document.
If the object to check out is a collection, all children will be checked out recursively if they are documents. Trying to check out a collection would result in an error.
See also hwapi_checkin().
Retrieves the children of a collection or the attributes of a document. The children can be further filtered by specifying an object query. The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.
The return value is an array of objects of type HW_API_Object or HW_API_Error.
See also hwapi_parents().
Reads len bytes from the content into the given buffer.
This function returns the content of a document as an object of type hw_api_content. The parameter array contains the required elements 'objectidentifier' and the optional element 'mode'. The mode can be one of the constants HW_API_CONTENT_ALLLINKS, HW_API_CONTENT_REACHABLELINKS or HW_API_CONTENT_PLAIN. HW_API_CONTENT_ALLLINKS means to insert all anchors even if the destination is not reachable. HW_API_CONTENT_REACHABLELINKS tells hw_api_content() to insert only reachable links and HW_API_CONTENT_PLAIN will lead to document without any links.
This function will make a physical copy including the content if it exists and returns the new object or an error object. The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. The optional parameter is 'attributeSelector'`
See also hwapi_move(), hwapi_link().
(no version information, might be only in CVS)
hw_api->dbstat -- Returns statistics about database server
See also hwapi_dcstat(), hwapi_hwstat(), hwapi_ftstat().
(no version information, might be only in CVS)
hw_api->dcstat -- Returns statistics about document cache server
See also hwapi_hwstat(), hwapi_dbstat(), hwapi_ftstat().
(no version information, might be only in CVS)
hw_api->dstanchors -- Returns a list of all destination anchorsRetrieves all destination anchors of an object. The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.
See also hwapi_srcanchors().
(no version information, might be only in CVS)
hw_api->dstofsrcanchors -- Returns destination of a source anchorRetrieves the destination object pointed by the specified source anchors. The destination object can either be a destination anchor or a whole document. The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.
See also hwapi_srcanchors(), hwapi_dstanchors(), hwapi_objectbyanchor().
This functions searches for objects either by executing a key or/and full text query. The found objects can further be filtered by an optional object query. They are sorted by their importance. The second search operation is relatively slow and its result can be limited to a certain number of hits. This allows to perform an incremental search, each returning just a subset of all found documents, starting at a given index. The parameter array contains the 'keyquery' or/and 'fulltextquery' depending on who you would like to search. Optional parameters are 'objectquery', 'scope', 'languages' and 'attributeselector'. In case of an incremental search the optional parameters 'startIndex', numberOfObjectsToGet' and 'exactMatchUnit' can be passed.
(no version information, might be only in CVS)
hw_api->ftstat -- Returns statistics about fulltext server
See also hwapi_dcstat(), hwapi_dbstat(), hwapi_hwstat().
Opens a connection to the Hyperwave server on host hostname. The protocol used is HGCSP. If you do not pass a port number, 418 is used.
See also hwapi_hwtp().
(no version information, might be only in CVS)
hw_api->hwstat -- Returns statistics about Hyperwave server
See also hwapi_dcstat(), hwapi_dbstat(), hwapi_ftstat().
Logs into the Hyperwave Server. The parameter array must contain the elements 'username' and 'password'.
The return value will be an object of type HW_API_Error if identification failed or TRUE if it was successful.
(no version information, might be only in CVS)
hw_api->info -- Returns information about server configuration
See also hwapi_dcstat(), hwapi_dbstat(), hwapi_ftstat(), hwapi_hwstat().
Insert a new object. The object type can be user, group, document or anchor. Depending on the type other object attributes has to be set. The parameter array contains the required elements 'object' and 'content' (if the object is a document) and the optional parameters 'parameters', 'mode' and 'attributeSelector'. The 'object' must contain all attributes of the object. 'parameters' is an object as well holding further attributes like the destination (attribute key is 'Parent'). 'content' is the content of the document. 'mode' can be a combination of the following flags:
The object in inserted into the server.
See also hwapi_replace().
(no version information, might be only in CVS)
hw_api->insertanchor -- Inserts a new object of type anchorThis function is a shortcut for hwapi_insert(). It inserts an object of type anchor and sets some of the attributes required for an anchor. The parameter array contains the required elements 'object' and 'documentIdentifier' and the optional elements 'destinationIdentifier', 'parameter', 'hint' and 'attributeSelector'. The 'documentIdentifier' specifies the document where the anchor shall be inserted. The target of the anchor is set in 'destinationIdentifier' if it already exists. If the target does not exists the element 'hint' has to be set to the name of object which is supposed to be inserted later. Once it is inserted the anchor target is resolved automatically.
See also hwapi_insertdocument(), hwapi_insertcollection(), hwapi_insert().
(no version information, might be only in CVS)
hw_api->insertcollection -- Inserts a new object of type collectionThis function is a shortcut for hwapi_insert(). It inserts an object of type collection and sets some of the attributes required for a collection. The parameter array contains the required elements 'object' and 'parentIdentifier' and the optional elements 'parameter' and 'attributeSelector'. See hwapi_insert() for the meaning of each element.
See also hwapi_insertdocument(), hwapi_insertanchor(), hwapi_insert().
(no version information, might be only in CVS)
hw_api->insertdocument -- Inserts a new object of type documentThis function is a shortcut for hwapi_insert(). It inserts an object with content and sets some of the attributes required for a document. The parameter array contains the required elements 'object', 'parentIdentifier' and 'content' and the optional elements 'mode', 'parameter' and 'attributeSelector'. See hwapi_insert() for the meaning of each element.
See also hwapi_insert() hwapi_insertanchor(), hwapi_insertcollection().
Creates a link to an object. Accessing this link is like accessing the object to links points to. The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. 'destinationParentIdentifier' is the target collection.
The function returns TRUE on success or an error object.
See also hwapi_copy().
Locks an object for exclusive editing by the user calling this function. The object can be only unlocked by this user or the system user. The parameter array contains the required element 'objectIdentifier' and the optional parameters 'mode' and 'objectquery'. 'mode' determines how an object is locked. HW_API_LOCK_NORMAL means, an object is locked until it is unlocked. HW_API_LOCK_RECURSIVE is only valid for collection and locks all objects within the collection and possible subcollections. HW_API_LOCK_SESSION means, an object is locked only as long as the session is valid.
See also hwapi_unlock().
(no version information, might be only in CVS)
hw_api_content -- Create new instance of class hw_api_contentCreates a new content object from the string content. The mimetype is set to mimetype.
(no version information, might be only in CVS)
hw_api_object->attreditable -- Checks whether an attribute is editableAdds an attribute to the object. Returns TRUE on success and otherwise FALSE.
See also hwapi_object_remove().
(no version information, might be only in CVS)
hw_api_object -- Creates a new instance of class hw_api_objectRemoves the attribute with the given name. Returns TRUE on success and otherwise FALSE.
See also hwapi_object_insert().
Returns the value of the attribute with the given name or FALSE if an error occurred.
This function retrieves the attribute information of an object of any version. It will not return the document content. The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'version'.
The returned object is an instance of class HW_API_Object on success or HW_API_Error if an error occurred.
This simple example retrieves an object and checks for errors.
Esempio 1. Retrieve an object
|
See also hwapi_content().
(no version information, might be only in CVS)
hw_api->objectbyanchor -- Returns the object an anchor belongs toThis function retrieves an object the specified anchor belongs to. The parameter array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.
See also hwapi_dstofsrcanchor(), hwapi_srcanchors(), hwapi_dstanchors().
Retrieves the parents of an object. The parents can be further filtered by specifying an object query. The parameter array contains the required elements 'objectidentifier' and the optional elements 'attributeselector' and 'objectquery'.
The return value is an array of objects of type HW_API_Object or HW_API_Error.
See also hwapi_children().
(no version information, might be only in CVS)
hw_api_reason->description -- Returns description of reasonRemoves an object from the specified parent. Collections will be removed recursively. You can pass an optional object query to remove only those objects which match the query. An object will be deleted physically if it is the last instance. The parameter array contains the required elements 'objectidentifier' and 'parentidentifier'. If you want to remove a user or group 'parentidentifier' can be skipped. The optional parameter 'mode' determines how the deletion is performed. In normal mode the object will not be removed physically until all instances are removed. In physical mode all instances of the object will be deleted immediately. In removelinks mode all references to and from the objects will be deleted as well. In nonrecursive the deletion is not performed recursive. Removing a collection which is not empty will cause an error.
See also hwapi_move().
Replaces the attributes and the content of an object The parameter array contains the required elements 'objectIdentifier' and 'object' and the optional parameters 'content', 'parameters', 'mode' and 'attributeSelector'. 'objectIdentifier' contains the object to be replaced. 'object' contains the new object. 'content' contains the new content. 'parameters' contain extra information for HTML documents. HTML_Language is the letter abbreviation of the language of the title. HTML_Base sets the base attribute of the HTML document. 'mode' can be a combination of the following flags:
The object on the server is replace with the object passed.
See also hwapi_insert().
(no version information, might be only in CVS)
hw_api->setcommitedversion -- Commits version other than last versionCommits a version of a document. The committed version is the one which is visible to users with read access. By default the last version is the committed version.
See also hwapi_checkin(), hwapi_checkout(), hwapi_revert().
(no version information, might be only in CVS)
hw_api->srcanchors -- Returns a list of all source anchorsRetrieves all source anchors of an object. The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.
See also hwapi_dstanchors().
(no version information, might be only in CVS)
hw_api->srcsofdst -- Returns source of a destination objectRetrieves all the source anchors pointing to the specified destination. The destination object can either be a destination anchor or a whole document. The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector' and 'objectQuery'. The function returns an array of objects or an error.
See also hwapi_dstofsrcanchor().
Unlocks a locked object. Only the user who has locked the object and the system user may unlock an object. The parameter array contains the required element 'objectIdentifier' and the optional parameters 'mode' and 'objectquery'. The meaning of 'mode' is the same as in function hwapi_lock().
Returns TRUE on success or an object of class HW_API_Error.
See also hwapi_lock().
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.
(PHP 4 >= 4.0.5, PHP 5)
iconv_get_encoding -- Visualizza l'attuale impostazione per la conversione dei caratteri codificatiRestituisce l'attuale impostazione di ob_iconv_handler() come array o FALSE in caso di insuccesso.
Vedere anche: iconv_set_encoding() e ob_iconv_handler().
Returns an associative array that holds a whole set of MIME header fields specified by encoded_headers on success, or FALSE if an error occurs during the decoding.
Each key of the return value represents an individual field name and the corresponding element represents a field value. If more than one field of the same name are present, iconv_mime_decode_headers() automatically incorporates them into a numerically indexed array in the order of occurrence.
mode determines the behaviour in the event iconv_mime_decode_headers() encounters a malformed MIME header field. You can specify any combination of the following bitmasks.
Tabella 1. Bitmasks acceptable to iconv_mime_decode_headers()
Value | Constant | Description |
---|---|---|
1 | ICONV_MIME_DECODE_STRICT | If set, the given header is decoded in full conformance with the standards defined in RFC2047. This option is disabled by default because there are a lot of broken mail user agents that don't follow the specification and don't produce correct MIME headers. |
2 | ICONV_MIME_DECODE_CONTINUE_ON_ERROR | If set, iconv_mime_decode_headers() attempts to ignore any grammatical errors and continue to process a given header. |
The optional charset parameter specifies the character set to represent the result by. If omitted, iconv.internal_charset will be used.
Esempio 1. iconv_mime_decode_headers() example
The output of this script should look like:
|
See also iconv_mime_decode(), mb_decode_mimeheader(), imap_mime_header_decode(), imap_base64() and imap_qprint().
Returns a decoded MIME field on success, or FALSE if an error occurs during the decoding.
mode determines the behaviour in the event iconv_mime_decode() encounters a malformed MIME header field. You can specify any combination of the following bitmasks.
Tabella 1. Bitmasks acceptable to iconv_mime_decode()
Value | Constant | Description |
---|---|---|
1 | ICONV_MIME_DECODE_STRICT | If set, the given header is decoded in full conformance with the standards defined in RFC2047. This option is disabled by default because there are a lot of broken mail user agents that don't follow the specification and don't produce correct MIME headers. |
2 | ICONV_MIME_DECODE_CONTINUE_ON_ERROR | If set, iconv_mime_decode() attempts to continue to process the given header even though an error occurs. |
The optional charset parameter specifies the character set to represent the result by. If omitted, iconv.internal_charset will be used.
See also iconv_mime_decode_headers(), mb_decode_mimeheader(), imap_mime_header_decode(), imap_base64() and imap_qprint().
Composes and returns a string that represents a valid MIME header field, which looks like the following:
Subject: =?ISO-8859-1?Q?Pr=FCfung_f=FCr?= Entwerfen von einer MIME kopfzeile |
You can control the behaviour of iconv_mime_encode() by specifying an associative array that contains configuration items to the optional third parameter preferences. The items supported by iconv_mime_encode() are listed below. Note that item names are treated case-sensitive.
Tabella 1. Configuration items supported by iconv_mime_encode()
Item | Type | Description | Default value | Example |
---|---|---|---|---|
scheme | boolean | Specifies the method to encode a field value by. The value of this item may be either "B" or "Q", where "B" stands for base64 encoding scheme and "Q" stands for quoted-printable encoding scheme. | B | B |
input-charset | string | Specifies the character set in which the first parameter field_name and the second parameter field_value are presented. If not given, iconv_mime_encode() assumes those parameters are presented to it in the iconv.internal_charset ini setting. | iconv.internal_charset | ISO-8859-1 |
output-charset | string | Specifies the character set to use to compose the MIME header. If not given, the same value as input-charset will be used. | the same value as input-charset | UTF-8 |
line-length | integer | Specifies the maximum length of the header lines. The resulting header is "folded" to a set of multiple lines in case the resulting header field would be longer than the value of this parameter, according to RFC2822 - Internet Message Format. If not given, the length will be limited to 76 characters. | 76 | 996 |
line-break-chars | string | Specifies the sequence of characters to append to each line as an end-of-line sign when "folding" is performed on a long header field. If not given, this defaults to "\r\n" (CR LF). Note that this parameter is always treated as an ASCII string regardless of the value of input-charset. | \r\n | \n |
Esempio 1. iconv_mime_encode() example:
|
See also imap_binary(), mb_encode_mimeheader() and imap_8bit().
(PHP 4 >= 4.0.5, PHP 5)
iconv_set_encoding -- Setta l'attuale impostazione per la conversione dei caratteri codificatiCambia il valore di type in charset e restituisc TRUE in caso di successo o FALSE in caso di fallimento.
Vedere anche: iconv_get_encoding() e ob_iconv_handler().
Returns the character count of str.
In contrast to strlen(), iconv_strlen() counts the occurrences of characters in the given byte sequence str on the basis of the specified character set, the result of which is not necessarily identical to the length of the string in byte.
If charset parameter is omitted, str is assumed to be encoded in iconv.internal_charset.
See also strlen() and mb_strlen().
Returns the numeric position of the first occurrence of needle in haystack.
The optional offset parameter specifies the position from which the search should be performed.
If needle is not found, iconv_strpos() will return FALSE.
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
If haystack or needle is not a string, it is converted to a string and applied as the ordinal value of a character.
In contrast to strpos(), the return value of iconv_strpos() is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found. The characters are counted on the basis of the specified character set charset.
If charset parameter is omitted, string are assumed to be encoded in iconv.internal_charset.
See also strpos(), iconv_strrpos() and mb_strpos().
(PHP 5)
iconv_strrpos -- Finds the last occurrence of a needle within the specified range of haystack.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().
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().
Converte la stringa codificata nel parametro stringa in in_charset nella stringa codificata in out_charset. Restituisce la stringa convertita o FALSE, se fallisce.
(PHP 4 >= 4.0.5, PHP 5)
ob_iconv_handler -- Converte caratteri codificati come un output buffer handlerConverte la stringa codificata del parametro internal_encoding in output_encoding.
internal_encoding e output_encoding dovrebbero essere definite da iconv_set_encoding() o nel file di configurazione.
Vedere anche: iconv_get_encoding() e iconv_set_encoding().
In PHP puoi usare delle funzioni specifiche per sapere la dimensione di un'immagine JPEG, GIF, PNG, SWF, TIFF e JPEG2000.
Se hai installato le librerie GD (scaricabili su http://www.boutell.com/gd/) sarai anche in grado di creare immagini al volo e di modificarle.
I formati delle immagini sulle quali potrai agire dipendono dalla versione delle librerie GD che hai installato, e dalle altre librerie di cui GD può aver bisogno per accedere a quei formati di immagine. Versioni precedenti alla gd-1.6 supportano il formato GIF ma non quello PNG, mentre versioni superiori alla gd-1.6 supportano il formato PNG ma non il GIF.
Se hai compilato PHP con l'opzione --enable-exif sarai in grado di lavorare con le informazioni memorizzate negli header delle immagini JPEG e TIFF. Queste funzioni non richiedono le librerie GD.
Per leggere e scrivere immagini in formato JPEG avrai bisogno di installare jpeg-6b (scaricabile da ftp://ftp.uu.net/graphics/jpeg/) e quindi ricompilare le librerie GD in modo che usino jpeg-6b. Dovrai anche compilare PHP con l'opzione --with-jpeg-dir=/percorso/per/jpeg-6b.
Per aggiungere il supporto per i Font Type 1 dovrai installare t1lib (scaricabile su ftp://sunsite.unc.edu/pub/Linux/libs/graphics/), e quindi aggiungere l'opzione --with-t1lib[=dir].
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
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().
(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.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.
FILE | FileName, FileSize, FileDateTime, SectionsFound |
COMPUTED | html, Width, Height, IsColor and some more if available. |
ANY_TAG | Any information that has a Tag e.g. IFD0, EXIF, ... |
IFD0 | All tagged data of IFD0. In normal imagefiles this contains image size and so forth. |
THUMBNAIL | A file is supposed to contain a thumbnail if it has a second IFD. All tagged information about the embedded thumbnail is stored in this section. |
COMMENT | Comment headers of JPEG images. |
EXIF | The EXIF section is a sub section of IFD0. It contains more detailed information about an image. Most of these entries are digital camera related. |
arrays specifies whether or not each section becomes an array. The sections 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
The first call fails because the image has no header information.
|
Nota: If the image contains any IFD0 data then COMPUTED contains the entry ByteOrderMotorola which is 0 for little-endian (intel) and 1 for big-endian (motorola) byte order. This was added in PHP 4.3.
When an Exif header contains a Copyright note this itself can contain two values. As the solution is 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() 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
|
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().
Returns an associative array describing the version and capabilities of the installed GD library.
Tabella 1. Elements of array returned by gd_info()
Attribute | Meaning |
---|---|
GD Version | string value describing the installed libgd version. |
Freetype Support | boolean value. TRUE if Freetype Support is installed. |
Freetype Linkage | string value describing the way in which Freetype was linked. Expected values are: 'with freetype', 'with TTF library', and 'with unknown library'. This element will only be defined if Freetype Support evaluated to TRUE. |
T1Lib Support | boolean value. TRUE if T1Lib support is included. |
GIF Read Support | boolean value. TRUE if support for reading GIF images is included. |
GIF Create Support | boolean value. TRUE if support for creating GIF images is included. |
JPG Support | boolean value. TRUE if JPG support is included. |
PNG Support | boolean value. TRUE if PNG support is included. |
WBMP Support | boolean value. TRUE if WBMP support is included. |
XBM Support | boolean value. TRUE if XBM support is included. |
Esempio 1. Using gd_info()
The typical output is :
|
See also imagepng(), imagejpeg(), imagegif(), imagewbmp(), and imagetypes().
The getimagesize() function will determine the size of any GIF, JPG, PNG, SWF, SWC, PSD, TIFF, BMP, IFF, JP2, JPX, JB2, JPC, XBM, or WBMP image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML IMG tag.
If accessing the filename image is impossible, or if it isn't a valid picture, getimagesize() will return FALSE and generate an error of level E_WARNING.
Nota: Support for JPC, JP2, JPX, JB2, XBM, and WBMP became available in PHP 4.3.2. Support for SWC exists as of PHP 4.3.0 and TIFF support was added in PHP 4.2.0
Nota: JPEG 2000 support was added in PHP 4.3.2. Note that JPC and JP2 are capable of having components with different bit depths. In this case, the value for "bits" is the highest bit depth encountered. Also, JP2 files may contain multiple JPEG 2000 codestreams. In this case, getimagesize() returns the values for the first codestream it encounters in the root of the file.
Nota: The getimagesize() function does not require the GD image library.
Returns an array with 4 elements. Index 0 contains the width of the image in pixels. Index 1 contains the height. Index 2 is a flag indicating the type of the image: 1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(intel byte order), 8 = TIFF(motorola byte order), 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC, 14 = IFF, 15 = WBMP, 16 = XBM. These values correspond to the IMAGETYPE constants that were added in PHP 4.3.0. Index 3 is a text string with the correct height="yyy" width="xxx" string that can be used directly in an IMG tag.
URL support was added in PHP 4.0.5
With JPG images, two extra indexes are returned: channels and bits. channels will be 3 for RGB pictures and 4 for CMYK pictures. bits is the number of bits for each color.
Beginning with PHP 4.3.0, bits and channels are present for other image types, too. However, the presence of these values can be a bit confusing. As an example, GIF always uses 3 channels per pixel, but the number of bits per pixel cannot be calculated for an animated GIF with a global color table.
Some formats may contain no image or may contain multiple images. In these cases, getimagesize() might not be able to properly determine the image size. getimagesize() will return zero for width and height in these cases.
Beginning with PHP 4.3.0, getimagesize() also returns an additional parameter, mime, that corresponds with the MIME type of the image. This information can be used to deliver images with correct HTTP Content-type headers:
The optional imageinfo parameter allows you to extract some extended information from the image file. Currently, this will return the different JPG APP markers as an associative array. Some programs use these APP markers to embed text information in images. A very common one is to embed IPTC http://www.iptc.org/ information in the APP13 marker. You can use the iptcparse() function to parse the binary APP13 marker into something readable.
See also image_type_to_mime_type(), exif_imagetype(), exif_read_data() and exif_thumbnail().
(no version information, might be only in CVS)
image_type_to_extension -- Get file extension for image typeAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
image_type_to_mime_type -- Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetypeThe image_type_to_mime_type() function will determine the Mime-Type for an IMAGETYPE constant.
The returned values are as follows
Tabella 1. Returned values Constants
imagetype | Returned value |
---|---|
IMAGETYPE_GIF | image/gif |
IMAGETYPE_JPEG | image/jpeg |
IMAGETYPE_PNG | image/png |
IMAGETYPE_SWF | application/x-shockwave-flash |
IMAGETYPE_PSD | image/psd |
IMAGETYPE_BMP | image/bmp |
IMAGETYPE_TIFF_II (intel byte order) | image/tiff |
IMAGETYPE_TIFF_MM (motorola byte order) | image/tiff |
IMAGETYPE_JPC | application/octet-stream |
IMAGETYPE_JP2 | image/jp2 |
IMAGETYPE_JPX | application/octet-stream |
IMAGETYPE_JB2 | application/octet-stream |
IMAGETYPE_SWC | application/x-shockwave-flash |
IMAGETYPE_IFF | image/iff |
IMAGETYPE_WBMP | image/vnd.wap.wbmp |
IMAGETYPE_XBM | image/xbm |
Nota: This function does not require the GD image library.
See also getimagesize(), exif_imagetype(), exif_read_data() and exif_thumbnail().
(PHP 4 >= 4.0.5, PHP 5)
image2wbmp -- Rende disponibile l'immagine per il browser o la salva in un fileimage2wbmp() crea un file WBMP dall'immagine specificata nel parametro image. L'argomento image è quello ritornato dalla funzione imagecreate().
L'argomento filename è opzionale, e può essere omesso. Puoi creare uno script PHP che ha direttamente un'immagine WBMP come output inviando image/vnd.wap.wbmp insieme alla funzione header().
Nota: Il supporto per WBMP è disponibile solo se PHP è compilato assieme a GD-1.8 o superiori.
Vedere anche imagewbmp().
imagealphablending() allows for two different modes of drawing on truecolor images. In blending mode, the alpha channel component of the color supplied to all drawing function, such as imagesetpixel() determines how much of the underlying color should be allowed to shine through. As a result, gd automatically blends the existing color at that point with the drawing color, and stores the result in the image. The resulting pixel is opaque. In non-blending mode, the drawing color is copied literally with its alpha channel information, replacing the destination pixel. Blending mode is not available when drawing on palette images. If blendmode is TRUE, then blending mode is enabled, otherwise disabled. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: This function requires GD 2.0.1 or later.
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() draws a partial ellipse centered at cx, cy (top left is 0, 0) in the image represented by image. W and h specifies the ellipse's width and height respectively while the start and end points are specified in degrees indicated by the s and e arguments. 0° is located at the three-o'clock position, and the arc is drawn clockwise.
Esempio 1. Drawing a circle with imagearc()
|
See also imageellipse(), imagefilledellipse(), and imagefilledarc().
imagechar() draws the first character of c in the image identified by image with its upper-left at x,y (top left is 0, 0) with the color color. If font is 1, 2, 3, 4 or 5, a built-in font is used (with higher numbers corresponding to larger fonts).
Esempio 1. imagechar() example
|
See also imagecharup() and imageloadfont().
imagecharup() draws the character c vertically in the image identified by image at coordinates x, y (top left is 0, 0) with the color color. If font is 1, 2, 3, 4 or 5, a built-in font is used.
Esempio 1. imagecharup() example
|
See also imagechar() and imageloadfont().
imagecolorallocate() returns a color identifier representing the color composed of the given RGB components. The image argument is the return from the 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() behaves identically to imagecolorallocate() with the addition of the transparency parameter alpha which may have a value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.
Returns FALSE if the allocation failed.
Esempio 1. Example of using imagecolorallocatealpha()
|
Nota: This function requires GD 2.0.1 or later.
See also imagecolorallocate() and imagecolordeallocate().
Returns the index of the color of the pixel at the specified location in the image specified by image.
If PHP is compiled against GD library 2.0 or higher and the image is a truecolor image, this function returns the RGB value of that pixel as integer. Use bitshifting and masking to access the distinct red, green and blue component values:
See also imagecolorset() and imagecolorsforindex().
(PHP 3, PHP 4 , PHP 5)
imagecolorclosest -- Get the index of the closest color to the specified colorReturns the index of the color in the palette of the image which is "closest" to the specified RGB value.
The "distance" between the desired color and each color in the palette is calculated as if the RGB values represented points in three-dimensional space.
See also imagecolorexact().
(PHP 4 >= 4.0.6, PHP 5)
imagecolorclosestalpha -- Get the index of the closest color to the specified color + alphaReturns the index of the color in the palette of the image which is "closest" to the specified RGB value and alpha level.
Nota: This function requires GD 2.0.1 or later.
See also imagecolorexactalpha().
(PHP 4 >= 4.0.1, PHP 5)
imagecolorclosesthwb -- Get the index of the color which has the hue, white and blackness nearest to the given color
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
The imagecolordeallocate() function de-allocates a color previously allocated with imagecolorallocate() or imagecolorallocatealpha().
See also imagecolorallocate() and imagecolorallocatealpha().
Returns the index of the specified color in the palette of the image.
If the color does not exist in the image's palette, -1 is returned.
See also imagecolorclosest().
Returns the index of the specified color+alpha in the palette of the image.
If the color does not exist in the image's palette, -1 is returned.
Nota: This function requires GD 2.0.1 or later.
See also imagecolorclosestalpha().
(PHP 4 >= 4.3.0, PHP 5)
imagecolormatch -- Makes the colors of the palette version of an image more closely match the true color versionAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
image1 must be Truecolor, image2 must be Palette, and both image1 and image2 must be the same size.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.
Nota: This function requires GD 2.0.1 or later.
See also imagecreatetruecolor().
(PHP 3>= 3.0.2, PHP 4 , PHP 5)
imagecolorresolve -- Get the index of the specified color or its closest possible alternativeThis function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.
See also imagecolorclosest().
(PHP 4 >= 4.0.6, PHP 5)
imagecolorresolvealpha -- Get the index of the specified color + alpha or its closest possible alternativeThis function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.
Nota: This function requires GD 2.0.1 or later.
See also imagecolorclosestalpha().
This sets the specified index in the palette to the specified color. This is useful for creating flood-fill-like effects in palleted images without the overhead of performing the actual flood-fill.
See also imagecolorat().
This returns an associative array with red, green, blue and alpha keys that contain the appropriate values for the specified color index.
Esempio 1. imagecolorsforindex() example
This example will output :
|
See also imagecolorat() and imagecolorexact().
This returns the number of colors in the specified image's palette.
See also imagecolorat() and imagecolorsforindex().
imagecolortransparent() sets the transparent color in the image image to color. image is the image identifier returned by imagecreate() and color is a color identifier returned by imagecolorallocate().
Nota: The transparent color is a property of the image, transparency is not a property of the color. Once you have a set a color to be the transparent color, any regions of the image in that color that were drawn previously will be transparent.
The identifier of the new (or current, if none is specified) transparent color is returned.
Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y.
Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y. The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to imagecopy().
Nota: This function was added in PHP 4.0.6
imagecopymergegray() copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y. The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to imagecopy().
This function is identical to imagecopymerge() except that when merging it preserves the hue of the source by converting the destination pixels to gray scale before the copy operation.
Nota: This function was added in PHP 4.0.6
imagecopyresampled() copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. dst_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() copies a rectangular portion of one image to another image. Dst_im is the destination image, src_im is the source image identifier. If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_im is the same as src_im) but if the regions overlap the results will be unpredictable.
Nota: There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().
See also imagecopyresampled().
imagecreate() returns an image identifier representing a blank image of size x_size by y_size.
We recommend the use of imagecreatetruecolor().
Esempio 1. Creating a new GD image stream and outputting an image.
|
See also imagedestroy() and imagecreatetruecolor().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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. |
(PHP 4 >= 4.1.0, PHP 5)
imagecreatefromgd2part -- Create a new image from a given part of GD2 file or URL
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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. |
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() 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)
|
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() 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 )
|
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() 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)
|
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. |
(PHP 4 >= 4.0.4, PHP 5)
imagecreatefromstring -- Create a new image from the image stream in the stringimagecreatefromstring() returns an image identifier representing the image obtained from the given string.
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)
|
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() 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() 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() 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.
|
Nota: This function requires GD 2.0.1 or later.
Nota: This function will not work with GIF file formats.
See also imagedestroy() and imagecreate().
This function is deprecated. Use combination of imagesetstyle() and imageline() instead.
imagedestroy() frees any memory associated with image image. image is the image identifier returned by the imagecreate() function.
imageellipse() draws an ellipse centered at cx, cy (top left is 0, 0) in the image represented by image. W and h specifies the ellipse's width and height respectively. The color of the ellipse is specified by color.
Nota: This function was added in PHP 4.0.6 and requires GD 2.0.2 or later which can be obtained at http://www.boutell.com/gd/
Esempio 1. imageellipse() example
|
See also imagefilledellipse() and imagearc().
imagefill() performs a flood fill starting at coordinate x, y (top left is 0, 0) with color color in the image image.
imagefilledarc() draws a partial ellipse centered at cx, cy (top left is 0, 0) in the image represented by image. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. W and h specifies the ellipse's width and height respectively while the start and end points are specified in degrees indicated by the s and e arguments. style is a bitwise OR of the following possibilities:
IMG_ARC_PIE
IMG_ARC_CHORD
IMG_ARC_NOFILL
IMG_ARC_EDGED
Esempio 1. Creating a 3D looking pie
|
Nota: This function requires GD 2.0.1 or later.
imagefilledellipse() draws an ellipse centered at cx, cy (top left is 0, 0) in the image represented by image. W and h specifies the ellipse's width and height respectively. The ellipse is filled using color. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later
Esempio 1. imagefilledellipse() example
|
Nota: This function requires GD 2.0.1 or later.
See also imageellipse() and imagefilledarc().
imagefilledpolygon() creates a filled polygon in image image. points is 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
|
imagefilledrectangle() creates a filled rectangle of color color in image image starting at upper left coordinates x1, y1 and ending at bottom right coordinates x2, y2. 0, 0 is the top left corner of the image.
imagefilltoborder() performs a flood fill whose border color is defined by border. The starting point for the fill is x, y (top left is 0, 0) and the region is filled with color color.
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.
Returns the pixel height of a character in the specified font.
See also imagefontwidth() and imageloadfont().
Returns the pixel width of a character in font.
See also imagefontheight() and imageloadfont().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: This function requires GD 2.0.1 or later.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: This function requires GD 2.0.1 or later.
The imagegammacorrect() function applies gamma correction to a gd image stream (image) given an input gamma, the parameter inputgamma and an output gamma, the parameter outputgamma.
imagegd2() outputs 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.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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:
See also imagepng(), imagewbmp(), imagejpeg() and imagetypes().
imageinterlace() turns the interlace bit on or off. If interlace is 1 the image will be interlaced, and if interlace is 0 the interlace bit is turned off.
If the interlace bit is set and the image is used as a JPEG image, the image is created as a progressive JPEG.
This function returns whether the interlace bit is set for the image.
imageistruecolor() finds whether the image image is a truecolor image.
Nota: This function requires GD 2.0.1 or later.
See also imagecreatetruecolor().
imagejpeg() creates the JPEG file in filename from the image image. The image argument is the return from the 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().
(PHP 4 >= 4.3.0, PHP 5)
imagelayereffect -- Set the alpha blending flag to use the bundled libgd layering effectsAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.
Nota: This function requires GD 2.0.1 or later.
imageline() draws a line from x1, y1 to x2, y2 (top left is 0, 0) in image image of color color.
Esempio 1. Drawing a thick line
|
See also imagecreate() and imagecolorallocate().
imageloadfont() loads a user-defined bitmap font and returns an identifier for the font (that is always greater than 5, so it will not conflict with the built-in fonts).
The font file format is currently binary and architecture dependent. This means you should generate the font files on the same type of CPU as the machine you are running PHP on.
Tabella 1. Font file format
byte position | C data type | description |
---|---|---|
byte 0-3 | int | number of characters in the font |
byte 4-7 | int | value of first character in the font (often 32 for space) |
byte 8-11 | int | pixel width of each character |
byte 12-15 | int | pixel height of each character |
byte 16- | char | array with character data, one byte per pixel in each character, for a total of (nchars*width*height) bytes. |
See also imagefontwidth() and imagefontheight().
imagepalettecopy() copies the palette from the source image to the destination image.
The imagepng() outputs a GD image stream (image) in PNG format to standard output (usually the browser) or, if a filename is given by the filename it outputs the image to the file.
See also imagegif(), imagewbmp(), imagejpeg(), imagetypes().
imagepolygon() creates a polygon in image id. points is a PHP array containing the polygon's vertices, i.e. points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, etc. num_points is the total number of points (vertices).
Esempio 1. imagepolygon() example
|
See also imagecreate() and imagecreatetruecolor().
(PHP 3>= 3.0.9, PHP 4 , PHP 5)
imagepsbbox -- Give the bounding box of a text rectangle using PostScript Type1 fontssize is expressed in pixels.
space allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative.
tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative.
angle is in degrees.
Parameters space and tightness are expressed in character space units, where 1 unit is 1/1000th of an em-square.
Parameters space, tightness, and angle are optional.
The bounding box is calculated using information available from character metrics, and unfortunately tends to differ slightly from the results achieved by actually rasterizing the text. If the angle is 0 degrees, you can expect the text to need 1 pixel more to every direction.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --enable-t1lib.
This function returns an array containing the following elements:
See also imagepstext().
(PHP 3>= 3.0.9, PHP 4 , PHP 5)
imagepscopyfont -- Make a copy of an already loaded font for further modificationUse this function if you need make further modifications to the font, for example extending/condensing, slanting it or changing its character encoding vector, but need to keep the original along as well. Note that the font you want to copy must be one obtained using imagepsloadfont(), not a font that is itself a copied one. You can although make modifications to it before copying.
If you use this function, you must free the fonts obtained this way yourself and in reverse order. Otherwise your script will hang.
In the case everything went right, a valid font index will be returned and can be used for further purposes. Otherwise the function returns FALSE and prints a message describing what went wrong.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --enable-t1lib.
See also imagepsloadfont().
Loads a character encoding vector from a file and changes the fonts encoding vector to it. As a PostScript fonts default vector lacks most of the character positions above 127, you'll definitely want to change this if you use an other language than English. The exact format of this file is described in T1libs documentation. T1lib comes with two ready-to-use files, IsoLatin1.enc and IsoLatin2.enc.
If you find yourself using this function all the time, a much better way to define the encoding is to set ps.default_encoding in the configuration file to point to the right encoding file and all fonts you load will automatically have the right encoding.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --enable-t1lib.
Extend or condense a font (font_index), if the value of the extend parameter is less than one you will be condensing the font.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --enable-t1lib.
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().
In the case everything went right, a valid font index will be returned and can be used for further purposes. Otherwise the function returns FALSE and prints a message describing what went wrong, which you cannot read directly, while the output type is image.
Esempio 1. imagepsloadfont() example
|
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --enable-t1lib.
See also imagepsfreefont().
Slant a font given by the font_index parameter with a slant of the value of the slant parameter.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --enable-t1lib.
(PHP 3>= 3.0.9, PHP 4 , PHP 5)
imagepstext -- To draw a text string over an image using PostScript Type1 fontsforeground is the color in which the text will be painted. Background is the color to which the text will try to fade in with antialiasing. No pixels with the color background are actually painted, so the background image does not need to be of solid color.
The coordinates given by x, y will define the origin (or reference point) of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where x, y define the upper-right corner of the first character. Refer to PostScript documentation about fonts and their measuring system if you have trouble understanding how this works.
space allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative.
tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative.
angle is in degrees.
size is expressed in pixels.
antialias_steps allows you to control the number of colours used for antialiasing text. Allowed values are 4 and 16. The higher value is recommended for text sizes lower than 20, where the effect in text quality is quite visible. With bigger sizes, use 4. It's less computationally intensive.
Parameters space and tightness are expressed in character space units, where 1 unit is 1/1000th of an em-square.
Parameters space, tightness, angle and antialias_steps are optional.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --enable-t1lib.
This function returns an array containing the following elements:
See also imagepsbbox().
imagerectangle() creates a rectangle of color col in image image starting at upper left coordinate x1, y1 and ending at bottom right coordinate x2, y2. 0, 0 is the top left corner of the image.
Rotates the src_im image using a given angle in 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.
(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.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() sets the brush image to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special colors IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED.
Nota: You need not take special action when you are finished with a brush, but if you destroy the brush image, you must not use the IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED colors until you have set a new brush image!
Nota: This function was added in PHP 4.0.6
imagesetpixel() draws a pixel at x, y (top left is 0, 0) in image image of color color.
See also imagecreate() and imagecolorallocate().
imagesetstyle() sets the style to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special color IMG_COLOR_STYLED or lines of images with color IMG_COLOR_STYLEDBRUSHED. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The style parameter is an array of pixels. Following example script draws a dashed line from upper left to lower right corner of the canvas:
Esempio 1. imagesetstyle() example
|
See also imagesetbrush(), imageline().
Nota: This function was added in PHP 4.0.6
imagesetthickness() sets the thickness of the lines drawn when drawing rectangles, polygons, ellipses etc. etc. to thickness pixels. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: This function requires GD 2.0.1 or later.
imagesettile() sets the tile image to be used by all region filling functions (such as imagefill() and imagefilledpolygon()) when filling with the special color IMG_COLOR_TILED.
A tile is an image used to fill an area with a repeated pattern. Any GD image can be used as a tile, and by setting the transparent color index of the tile image with imagecolortransparent(), a tile allows certain parts of the underlying area to shine through can be created.
Nota: You need not take special action when you are finished with a tile, but if you destroy the tile image, you must not use the IMG_COLOR_TILED color until you have set a new tile image!
imagestring() draws the string s in the image identified by image at coordinates x, y (top left is 0, 0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.
Esempio 1. imagestring() example
|
See also imageloadfont().
imagestringup() draws the string s vertically in the image identified by image at coordinates x, y (top left is 0, 0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.
See also imageloadfont().
imagesx() returns the width of the image identified by image.
See also imagecreate(), getimagesize() and imagesy().
imagesy() returns the height of the image identified by image.
See also imagecreate(), getimagesize() and imagesx().
imagetruecolortopalette() converts a truecolor image to a palette image. The code for this function was originally drawn from the Independent JPEG Group library code, which is excellent. The code has been modified to preserve as much alpha channel information as possible in the resulting palette, in addition to preserving colors as well as possible. This does not work as well as might be hoped. It is usually best to simply produce a truecolor output image instead, which guarantees the highest output quality.
dither indicates if the image should be dithered - if it is TRUE then dithering will be used which will result in a more speckled image but with better color approximation.
ncolors sets the maximum number of colors that should be retained in the palette.
Nota: This function requires GD 2.0.1 or later.
This function calculates and returns the bounding box in pixels for a TrueType text.
The string to be measured.
The font size in pixels.
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 in degrees in which text will be measured.
0 | lower left corner, X position |
1 | lower left corner, Y position |
2 | lower right corner, X position |
3 | lower right corner, Y position |
4 | upper right corner, X position |
5 | upper right corner, Y position |
6 | upper left corner, X position |
7 | upper left corner, Y position |
This function requires both the GD library and the FreeType library.
See also imagettftext().
imagettftext() draws the string text in the image identified by image, starting at coordinates x, y (top left is 0, 0), at an angle of angle in color 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: {) 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
|
This function requires both the GD library and the FreeType library.
See also imagettfbbox().
(PHP 3 CVS only, PHP 4 >= 4.0.2, PHP 5)
imagetypes -- Return the image types supported by this PHP buildThis function returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP. The following bits are returned, IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM. To check for PNG support, for example, do this:
imagewbmp() creates the WBMP file in filename from the image image. The image argument is the return from the 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().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
iptcparse -- Parse a binary IPTC http://www.iptc.org/ block into single tags.This function parses a binary IPTC block into its single tags. It returns an array using the tagmarker as an index and the value as the value. It returns FALSE on error or if no IPTC data was found. See getimagesize() for a sample.
Converts the jpegname JPEG file to WBMP format, and saves it as wbmpname. With the d_height and d_width you specify the height and width of the destination image.
Nota: WBMP support is only available if PHP was compiled against GD-1.8 or later.
See also png2wbmp().
Converts the pngname PNG file to WBMP format, and saves it as wbmpname. With the d_height and d_width you specify the height and width of the destination image.
Nota: WBMP support is only available if PHP was compiled against GD-1.8 or later.
See also jpeg2wbmp().
These functions are not limited to the IMAP protocol, despite their name. The underlying c-client library also supports NNTP, POP3 and local mailbox access methods.
This extension requires the c-client library to be installed. Grab the latest version from ftp://ftp.cac.washington.edu/imap/ and compile it.
It's important that you do not copy the IMAP source files directly into the system include directory as there may be conflicts. Instead, create a new directory inside the system include directory, such as /usr/local/imap-2000b/ (location and name depend on your setup and IMAP version), and inside this new directory create additional directories named lib/ and include/. From the c-client directory from your IMAP source tree, copy all the *.h files into include/ and all the *.c files into lib/. Additionally when you compiled IMAP, a file named c-client.a was created. Also put this in the lib/ directory but rename it as libc-client.a.
Nota: To build the c-client library with SSL or/and Kerberos support read the docs supplied with the package.
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.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Open mailbox read-only
Don't use or update a .newsrc for news (NNTP only)
For IMAP and NNTP names, open a connection but don't open a mailbox.
silently expunge the mailbox before closing when calling imap_close()
The parameter is a UID
Do not set the \Seen flag if not already set
The return string is in internal format, will not canonicalize to CRLF.
The sequence argument contains UIDs instead of sequence numbers
the sequence numbers contain UIDS
Delete the messages from the current mailbox after copying with imap_mail_copy()
Return UIDs instead of sequence numbers
Don't prefetch searched messages
This mailbox has no "children" (there are no mailboxes below this one).
This is only a container, not a mailbox - you cannot open it.
This mailbox is marked. Only used by UW-IMAPD.
This mailbox is not marked. Only used by UW-IMAPD.
Sort criteria for imap_sort(): message Date
Sort criteria for imap_sort(): arrival date
Sort criteria for imap_sort(): mailbox in first From address
Sort criteria for imap_sort(): message subject
Sort criteria for imap_sort(): mailbox in first To address
Sort criteria for imap_sort(): mailbox in first cc address
Sort criteria for imap_sort(): size of message in octets
This document can't go into detail on all the topics touched by the provided functions. Further information is provided by the documentation of the c-client library source (docs/internal.txt). and the following RFC documents:
RFC2821: Simple Mail Transfer Protocol (SMTP).
RFC2822: Standard for ARPA internet text messages.
RFC2060: Internet Message Access Protocol (IMAP) Version 4rev1.
RFC1939: Post Office Protocol Version 3 (POP3).
RFC977: Network News Transfer Protocol (NNTP).
RFC2076: Common Internet Message Headers.
RFC2045 , RFC2046 , RFC2047 , RFC2048 & RFC2049: Multipurpose Internet Mail Extensions (MIME).
Convert an 8bit string to a quoted-printable string (according to RFC2045, section 6.7).
Returns a quoted-printable string.
See also imap_qprint().
(PHP 3>= 3.0.12, PHP 4 , PHP 5)
imap_alerts -- This function returns all IMAP alert messages (if any) that have occurred during this page request or since the alert stack was resetThis function returns an array of all of the IMAP alert messages generated since the last imap_alerts() call, or the beginning of the page. When imap_alerts() is called, the alert stack is subsequently cleared. The IMAP specification requires that these messages be passed to the user.
imap_append() appends a string message to the specified mailbox mbox. If the optional options is specified, writes the options to that mailbox also.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
When talking to the Cyrus IMAP server, you must use "\r\n" as your end-of-line terminator instead of "\n" or the operation will fail.
Esempio 1. imap_append() example
|
imap_base64() function decodes BASE-64 encoded text (see RFC2045, Section 6.8). The decoded message is returned as a string.
See also imap_binary(), base64_encode() and base64_decode().
Convert an 8bit string to a base64 string (according to RFC2045, Section 6.8).
Returns a base64 string.
See also imap_base64().
imap_body() returns the body of the message, numbered msg_number in the current mailbox.
The optional options are a bit mask with one or more of the following:
FT_UID - The msg_number is a UID
FT_PEEK - Do not set the \Seen flag if not already set
FT_INTERNAL - The return string is in internal format, will not canonicalize to CRLF.
imap_body() will only return a verbatim copy of the message body. To extract single parts of a multipart MIME-encoded message you have to use imap_fetchstructure() to analyze its structure and imap_fetchbody() to extract a copy of a single body component.
(PHP 3>= 3.0.4, PHP 4 , PHP 5)
imap_bodystruct -- Read the structure of a specified body section of a specific message
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Returns information about the current mailbox. Returns FALSE on failure.
The imap_check() function checks the current mailbox status on the server and returns the information in an object with following properties:
Date - current system time formatted according to RFC822
Driver - protocol used to access this mailbox: POP3, IMAP, NNTP
Mailbox - the mailbox name
Nmsgs - number of messages in the mailbox
Recent - number of recent messages in the mailbox
Esempio 1. imap_check() example
this will output :
|
This function causes a store to delete the specified flag to the flags set for the messages in the specified sequence. The flags which you can unset are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", and "\\Draft" (as defined by RFC2060). Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
options are a bit mask and may contain the single option:
ST_UID - The sequence argument contains UIDs instead of sequence numbers
See also: imap_setflag_full().
Closes the imap stream. Takes an optional flag CL_EXPUNGE, which will silently expunge the mailbox before closing, removing all messages marked for deletion.
See also: imap_open().
imap_createmailbox() creates a new mailbox specified by mbox. Names containing international characters should be encoded by imap_utf7_encode()
Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
Esempio 1. imap_createmailbox() example
|
See also imap_renamemailbox(), imap_deletemailbox() and imap_open() for the format of mbox names.
Returns TRUE.
imap_delete() marks messages listed in msg_number for deletion. The optional flags parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID. Messages marked for deletion will stay in the mailbox until either imap_expunge() is called or imap_close() is called with the optional parameter CL_EXPUNGE.
Nota: POP3 mailboxes do not have their message flags saved between connections, so imap_expunge() must be called during the same connection in order for messages marked for deletion to actually be purged.
Esempio 1. imap_delete() example
|
See also: imap_undelete(), imap_expunge(), and imap_close().
imap_deletemailbox() deletes the specified mailbox (see imap_open() for the format of mbox names).
Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
See also imap_createmailbox(), imap_renamemailbox(), and imap_open() for the format of mbox.
(PHP 3>= 3.0.12, PHP 4 , PHP 5)
imap_errors -- This function returns all of the IMAP errors (if any) that have occurred during this page request or since the error stack was reset.This function returns an array of all of the IMAP error messages generated since the last imap_errors() call, or the beginning of the page. When imap_errors() is called, the error stack is subsequently cleared.
See also: imap_last_error().
imap_expunge() deletes all the messages marked for deletion by imap_delete(), imap_mail_move(), or imap_setflag_full().
Returns TRUE.
(PHP 3>= 3.0.4, PHP 4 , PHP 5)
imap_fetch_overview -- Read an overview of the information in the headers of the given messageThis function fetches mail headers for the given sequence and returns an overview of their contents. sequence will contain a sequence of message indices or UIDs, if flags contains FT_UID. The returned value is an array of objects describing one message header each:
subject - the messages subject
from - who sent it
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
|
This function causes a fetch of a particular section of the body of the specified messages as a text string and returns that text string. The section specification is a string of integers delimited by period which index into a body part list as per the IMAP4 specification. Body parts are not decoded by this function.
The options for imap_fetchbody() is a bitmask with one or more of the following:
FT_UID - The msg_number is a UID
FT_PEEK - Do not set the \Seen flag if not already set
FT_INTERNAL - The return string is in internal format, will not canonicalize to CRLF.
See also: imap_fetchstructure().
This function causes a fetch of the complete, unfiltered RFC2822 format header of the specified message as a text string and returns that text string.
The options are:
FT_UID - The msgno argument is a UID
FT_INTERNAL - The return string is in "internal" format, without any attempt to canonicalize to CRLF newlines
FT_PREFETCHTEXT - The RFC822.TEXT should be pre-fetched at the same time. This avoids an extra RTT on an IMAP connection if a full message text is desired (e.g. in a "save to local file" operation)
This function fetches all the structured information for a given message. The optional options parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID. The returned object includes the envelope, internal date, size, flags and body structure along with a similar object for each mime attachment. The structure of the returned objects is as follows:
Tabella 1. Returned Objects for imap_fetchstructure()
type | Primary body type |
encoding | Body transfer encoding |
ifsubtype | TRUE if there is a subtype string |
subtype | MIME subtype |
ifdescription | TRUE if there is a description string |
description | Content description string |
ifid | TRUE if there is an identification string |
id | Identification string |
lines | Number of lines |
bytes | Number of bytes |
ifdisposition | TRUE if there is a disposition string |
disposition | Disposition string |
ifdparameters | TRUE if the dparameters array exists |
dparameters | An array of objects where each object has an "attribute" and a "value" property corresponding to the parameters on the Content-disposition MIMEheader. |
ifparameters | TRUE if the parameters array exists |
parameters | An array of objects where each object has an "attribute" and a "value" property. |
parts | An array of objects identical in structure to the top-level object, each of which corresponds to a MIME body part. |
See also: imap_fetchbody().
(PHP 4 >= 4.0.5, PHP 5)
imap_get_quota -- Retrieve the quota level settings, and usage statics per mailboxReturns an array with integer values limit and usage for the given mailbox. The value of limit represents the total amount of space allowed for this mailbox. The usage value represents the mailboxes current level of capacity. Will return FALSE in the case of failure.
This function is currently only available to users of the c-client2000 or greater library.
NOTE: For this function to work, the mail stream is required to be opened as the mail-admin user. For a non-admin user version of this function, please see the imap_get_quotaroot() function of PHP.
imap_stream should be the value returned from an imap_open() call. NOTE: This stream is required to be opened as the mail admin user for the get_quota function to work. quota_root should normally be in the form of user.name where name is the mailbox you wish to retrieve information about.
Esempio 1. imap_get_quota() example
|
As of PHP 4.3, the function more properly reflects the functionality as dictated by the RFC 2087. The array return value has changed to support an unlimited number of returned resources (i.e. messages, or sub-folders) with each named resource receiving an individual array key. Each key value then contains an another array with the usage and limit values within it. The example below shows the updated returned output.
For backwards compatibility reasons, the originial access methods are still available for use, although it is suggested to update.
Esempio 2. imap_get_quota() 4.3 or greater example
|
See also imap_open(), imap_set_quota() and imap_get_quotaroot().
Returns an array of integer values pertaining to the specified user mailbox. All values contain a key based upon the resource name, and a corresponding array with the usage and limit values within.
The limit value represents the total amount of space allowed for this user's total mailbox usage. The usage value represents the user's current total mailbox capacity. This function will return FALSE in the case of call failure, and an array of information about the connection upon an un-parsable response from the server.
This function is currently only available to users of the c-client2000 or greater library.
imap_stream should be the value returned from an imap_open() call. This stream should be opened as the user whose mailbox you wish to check. quota_root should normally be in the form of which mailbox (i.e. INBOX).
Esempio 1. imap_get_quotaroot() example
|
See also imap_open(), imap_set_quota() and imap_get_quota().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
See also: imap_setacl().
(PHP 3>= 3.0.12, PHP 4 , PHP 5)
imap_getmailboxes -- Read the list of mailboxes, returning detailed information on each oneReturns an array of objects containing mailbox information. Each object has the attributes name, specifying the full name of the mailbox; delimiter, which is the hierarchy delimiter for the part of the hierarchy this mailbox is in; and attributes. Attributes is a bitmask that can be tested against:
LATT_NOINFERIORS - This mailbox has no "children" (there are no mailboxes below this one).
LATT_NOSELECT - This is only a container, not a mailbox - you cannot open it.
LATT_MARKED - This mailbox is marked. Only used by UW-IMAPD.
LATT_UNMARKED - This mailbox is not marked. Only used by UW-IMAPD.
Mailbox names containing international Characters outside the printable ASCII range will be encoded and may be decoded by imap_utf7_decode().
ref should normally be just the server specification as described in imap_open(), and pattern specifies where in the mailbox hierarchy to start searching. If you want all mailboxes, pass '*' for pattern.
There are two special characters you can pass as part of the pattern: '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.
Esempio 1. imap_getmailboxes() example
|
See also imap_getsubscribed().
This function is identical to imap_getmailboxes(), except that it only returns mailboxes that the user is subscribed to.
This function returns an object of various header elements.
remail, date, Date, subject, Subject, in_reply_to, message_id,
newsgroups, followup_to, references
message flags:
Recent - 'R' if recent and seen,
'N' if recent and not seen,
' ' if not recent
Unseen - 'U' if not seen AND not recent,
' ' if seen OR not seen and recent
Answered -'A' if answered,
' ' if unanswered
Deleted - 'D' if deleted,
' ' if not deleted
Draft - 'X' if draft,
' ' if not draft
Flagged - 'F' if flagged,
' ' if not flagged
NOTE that the Recent/Unseen behavior is a little odd. If you want to
know if a message is Unseen, you must check for
Unseen == 'U' || Recent == 'N'
toaddress (full to: line, up to 1024 characters)
to[] (returns an array of objects from the To line, containing):
personal
adl
mailbox
host
fromaddress (full from: line, up to 1024 characters)
from[] (returns an array of objects from the From line, containing):
personal
adl
mailbox
host
ccaddress (full cc: line, up to 1024 characters)
cc[] (returns an array of objects from the Cc line, containing):
personal
adl
mailbox
host
bccaddress (full bcc line, up to 1024 characters)
bcc[] (returns an array of objects from the Bcc line, containing):
personal
adl
mailbox
host
reply_toaddress (full reply_to: line, up to 1024 characters)
reply_to[] (returns an array of objects from the Reply_to line,
containing):
personal
adl
mailbox
host
senderaddress (full sender: line, up to 1024 characters)
sender[] (returns an array of objects from the sender line, containing):
personal
adl
mailbox
host
return_path (full return-path: line, up to 1024 characters)
return_path[] (returns an array of objects from the return_path line,
containing):
personal
adl
mailbox
host
udate (mail message date in unix time)
fetchfrom (from line formatted to fit fromlength
characters)
fetchsubject (subject line formatted to fit subjectlength characters)
Returns an array of string formatted with header info. One element per mail message.
(PHP 3>= 3.0.12, PHP 4 , PHP 5)
imap_last_error -- This function returns the last IMAP error (if any) that occurred during this page requestThis function returns the full text of the last IMAP error message that occurred on the current page. The error stack is untouched; calling imap_last_error() subsequently, with no intervening errors, will return the same error.
See also: imap_errors().
Returns an array containing the names of the mailboxes. See imap_getmailboxes() for a description of ref and pattern.
Esempio 1. imap_list() example
|
See also: imap_getmailboxes().
(no version information, might be only in CVS)
imap_listscan -- Read the list of mailboxes, takes a string to search for in the text of the mailboxReturns an array containing the names of the mailboxes that have content in the text of the mailbox.
This function is similar to imap_listmailbox(), but it will additionally check for the presence of the string content inside the mailbox data.
See imap_getmailboxes() for a description of ref and pattern.
Returns an array of all the mailboxes that you have subscribed.
(PHP 3>= 3.0.5, PHP 4 , PHP 5)
imap_mail_compose -- Create a MIME message based on given envelope and body sections
Esempio 1. imap_mail_compose() example
|
Copies mail messages specified by msglist to specified mailbox. Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
msglist is a range not just message numbers (as described in RFC2060).
options is a bitmask of one or more of
CP_UID - the sequence numbers contain UIDS
CP_MOVE - Delete the messages from the current mailbox after copying
See also imap_mail_move().
Moves mail messages specified by msglist to specified mailbox mbox. Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
msglist is a range not just message numbers (as described in RFC2060).
options is a bitmask and may contain the single option:
CP_UID - the sequence numbers contain UIDS
See also imap_mail_copy().
This function allows sending of emails with correct handling of Cc and Bcc receivers. Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
The parameters to, cc and bcc are all strings and are all parsed as rfc822 address lists.
The receivers specified in bcc will get the mail, but are excluded from the headers.
Use the rpath parameter to specify return path. This is useful when using PHP as a mail client for multiple users.
Returns information about the current mailbox. Returns FALSE on failure.
The imap_mailboxmsginfo() function checks the current mailbox status on the server. It is similar to imap_status(), but will additionally sum up the size of all messages in the mailbox, which will take some additional time to execute. It returns the information in an object with following properties.
Tabella 1. Mailbox properties
Date | date of last change |
Driver | driver |
Mailbox | name of the mailbox |
Nmsgs | number of messages |
Recent | number of recent messages |
Unread | number of unread messages |
Deleted | number of deleted messages |
Size | mailbox size |
Esempio 1. imap_mailboxmsginfo() example
|
imap_mime_header_decode() function decodes MIME message header extensions that are non ASCII text (see RFC2047) The decoded elements are returned in an array of objects, where each object has two properties, "charset" and "text". If the element hasn't been encoded, and in other words is in plain US-ASCII,the "charset" property of that element is set to "default".
In the above example we would have two elements, whereas the first element had previously been encoded with ISO-8859-1, and the second element would be plain US-ASCII.
(PHP 3>= 3.0.3, PHP 4 , PHP 5)
imap_msgno -- This function returns the message sequence number for the given UIDThis function returns the message sequence number for the given uid. It is the inverse of imap_uid().
See also imap_uid().
Return the number of messages in the current mailbox.
See also: imap_num_recent() and imap_status().
Returns the number of recent messages in the current mailbox.
See also: imap_num_msg() and imap_status().
Returns an IMAP stream on success and FALSE on error. This function can also be used to open streams to POP3 and NNTP servers, but some functions and features are only available on IMAP servers.
A mailbox name consists of a server part and a mailbox path on this server. The special name INBOX stands for the current users personal mailbox. The server part, which is enclosed in '{' and '}', consists of the servers name or ip address, an optional port (prefixed by ':'), and an optional protocol specification (prefixed by '/'). The server part is mandatory in all mailbox parameters. Mailbox names that contain international characters besides those in the printable ASCII space have to be encoded with imap_utf7_encode().
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:
To connect to a POP3 server on port 110 on the local server, use: To connect to an SSL IMAP or POP3 server, add /ssl after the protocol specification: To connect to an SSL IMAP or POP3 server with a self-signed certificate, add /ssl/novalidate-cert after the protocol specification: To connect to an NNTP server on port 119 on the local server, use: To connect to a remote server replace "localhost" with the name or the IP address of the server you want to connect to.
Esempio 1. imap_open() example
|
Returns TRUE if the stream is still alive, FALSE otherwise.
imap_ping() function pings the stream to see it is still active. It may discover new mail; this is the preferred method for a periodic "new mail check" as well as a "keep alive" for servers which have inactivity timeout. (As PHP scripts do not tend to run that long, I can hardly imagine that this function will be useful to anyone.)
Convert a quoted-printable string to an 8 bit string (according to RFC2045, section 6.7).
See also imap_8bit().
This function renames on old mailbox to new mailbox (see imap_open() for the format of mbox names).
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also imap_createmailbox(), imap_deletemailbox(), and imap_open() for the format of mbox.
This function reopens the specified stream to a new mailbox on an IMAP or NNTP server.
The options are a bit mask with one or more of the following:
OP_READONLY - Open mailbox read-only
OP_ANONYMOUS - Don't use or update a .newsrc for news (NNTP only)
OP_HALFOPEN - For IMAP and NNTP names, open a connection but don't open a mailbox.
CL_EXPUNGE - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
This function parses the address string as defined in RFC2822 and for each address, returns an array of objects. The objects properties are:
mailbox - the mailbox name (username)
host - the host name
personal - the personal name
adl - at domain source route
Esempio 1. imap_rfc822_parse_adrlist() example
|
This function returns an object of various header elements, similar to imap_header(), except without the flags and other elements that come from the IMAP server.
(PHP 3>= 3.0.2, PHP 4 , PHP 5)
imap_rfc822_write_address -- Returns a properly formatted email address given the mailbox, host, and personal info.Returns a properly formatted email address as defined in RFC2822 given the mailbox, host, and personal info.
(PHP 3>= 3.0.12, PHP 4 , PHP 5)
imap_search -- This function returns an array of messages matching the given search criteriaThis function performs a search on the mailbox currently opened in the given imap stream. criteria is a string, delimited by spaces, in which the following keywords are allowed. Any multi-word arguments (e.g. FROM "joey smith") must be quoted.
ALL - return all messages matching the rest of the criteria
ANSWERED - match messages with the \\ANSWERED flag set
BCC "string" - match messages with "string" in the Bcc: field
BEFORE "date" - match messages with Date: before "date"
BODY "string" - match messages with "string" in the body of the message
CC "string" - match messages with "string" in the Cc: field
DELETED - match deleted messages
FLAGGED - match messages with the \\FLAGGED (sometimes referred to as Important or Urgent) flag set
FROM "string" - match messages with "string" in the From: field
KEYWORD "string" - match messages with "string" as a keyword
NEW - match new messages
OLD - match old messages
ON "date" - match messages with Date: matching "date"
RECENT - match messages with the \\RECENT flag set
SEEN - match messages that have been read (the \\SEEN flag is set)
SINCE "date" - match messages with Date: after "date"
SUBJECT "string" - match messages with "string" in the Subject:
TEXT "string" - match messages with text "string"
TO "string" - match messages with "string" in the To:
UNANSWERED - match messages that have not been answered
UNDELETED - match messages that are not deleted
UNFLAGGED - match messages that are not flagged
UNKEYWORD "string" - match messages that do not have the keyword "string"
UNSEEN - match messages which have not been read yet
For example, to match all unanswered messages sent by Mom, you'd use: "UNANSWERED FROM mom". Searches appear to be case insensitive. This list of criteria is from a reading of the UW c-client source code and may be incomplete or inaccurate (see also RFC2060, section 6.4.4).
Valid values for flags are SE_UID, which causes the returned array to contain UIDs instead of messages sequence numbers.
Sets an upper limit quota on a per mailbox basis. This function requires the imap_stream to have been opened as the mail administrator account. It will not work if opened as any other user.
This function is currently only available to users of the c-client2000 or greater library.
imap_stream is the stream pointer returned from a imap_open() call. This stream must be opened as the mail administrator, other wise this function will fail. quota_root is the mailbox to have a quota set. This should follow the IMAP standard format for a mailbox, 'user.name'. quota_limit is the maximum size (in KB) for the quota_root.
Returns TRUE on success and FALSE on error.
See also imap_open() and imap_set_quota().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
See also: imap_getacl().
This function causes a store to add the specified flag to the flags set for the messages in the specified sequence.
The flags which you can set are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", and "\\Draft" (as defined by RFC2060).
options are a bit mask and may contain the single option:
ST_UID - The sequence argument contains UIDs instead of sequence numbers
See also: imap_clearflag_full().
Returns an array of message numbers sorted by the given parameters.
Reverse is 1 for reverse-sorting.
Criteria can be one (and only one) of the following:
SORTDATE - message Date
SORTARRIVAL - arrival date
SORTFROM - mailbox in first From address
SORTSUBJECT - message subject
SORTTO - mailbox in first To address
SORTCC - mailbox in first cc address
SORTSIZE - size of message in octets
The flags are a bitmask of one or more of the following:
SE_UID - Return UIDs instead of sequence numbers
SE_NOPREFETCH - Don't prefetch searched messages
(PHP 3>= 3.0.4, PHP 4 , PHP 5)
imap_status -- This function returns status information on a mailbox other than the current oneThis function returns an object containing status information. Valid flags are:
SA_MESSAGES - set status->messages to the number of messages in the mailbox
SA_RECENT - set status->recent to the number of recent messages in the mailbox
SA_UNSEEN - set status->unseen to the number of unseen (new) messages in the mailbox
SA_UIDNEXT - set status->uidnext to the next uid to be used in the mailbox
SA_UIDVALIDITY - set status->uidvalidity to a constant that changes when uids for the mailbox may no longer be valid
SA_ALL - set all of the above
status->flags is also set, which contains a bitmask which can be checked against any of the above constants.
Esempio 1. imap_status() example
|
Subscribe to a new mailbox.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also: imap_unsubscribe().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 3>= 3.0.3, PHP 4 , PHP 5)
imap_uid -- This function returns the UID for the given message sequence numberThis function returns the UID for the given message sequence number. An UID is 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().
This function removes the deletion flag for a specified message, which is set by imap_delete() or imap_mail_move().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also: imap_delete(), and imap_mail_move().
Unsubscribe from a specified mailbox.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also: imap_subscribe().
Decodes modified UTF-7 text into ISO-8859-1 string.
Returns a string that is encoded in ISO-8859-1 and consists of the same sequence of characters in text, or FALSE if text contains invalid modified UTF-7 sequence or text contains a character that is not part of ISO-8859-1 character set.
This function is needed to decode mailbox names that contain certain characters which are not in range of printable ASCII characters.
The modified UTF-7 encoding is defined in RFC 2060, section 5.1.3 (original UTF-7 was defined in RFC1642).
See also: imap_utf7_encode().
(PHP 3>= 3.0.15, PHP 4 , PHP 5)
imap_utf7_encode -- Converts ISO-8859-1 string to modified UTF-7 text.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().
The Informix driver for Informix (IDS) 7.x, SE 7.x, Universal Server (IUS) 9.x and IDS 2000 is implemented in "ifx.ec" and "php3_ifx.h" in the informix extension directory. IDS 7.x support is fairly complete, with full support for BYTE and TEXT columns. IUS 9.x support is partly finished: the new data types are there, but SLOB and CLOB support is still under construction.
Configuration notes: You need a version of ESQL/C to compile the PHP Informix driver. ESQL/C versions from 7.2x on should be OK. ESQL/C is now part of the Informix Client SDK.
Make sure that the "INFORMIXDIR" variable has been set, and that $INFORMIXDIR/bin is in your PATH before you run the "configure" script.
To be able to use the functions defined in this module you must compile your PHP interpreter using the configure line --with_informix[=DIR], where DIR is the Informix base install directory, defaults to nothing.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Nota: Make sure that the Informix environment variables INFORMIXDIR and INFORMIXSERVER are available to the PHP ifx driver, and that the INFORMIX bin directory is in the PATH. Check this by running a script that contains a call to phpinfo() before you start testing. The phpinfo() output should list these environment variables. This is TRUE for both CGI php and Apache mod_php. You may have to set these environment variables in your Apache startup script.
The Informix shared libraries should also be available to the loader (check LD_LIBRARY_PATH or ld.so.conf/ldconfig).
Some notes on the use of BLOBs (TEXT and BYTE columns): BLOBs are normally addressed by BLOB identifiers. Select queries return a "blob id" for every BYTE and TEXT column. You can get at the contents with "string_var = ifx_get_blob($blob_id);" if you choose to get the BLOBs in memory (with: "ifx_blobinfile(0);"). If you prefer to receive the content of BLOB columns in a file, use "ifx_blobinfile(1);", and "ifx_get_blob($blob_id);" will get you the filename. Use normal file I/O to get at the blob contents.
For insert/update queries you must create these "blob id's" yourself with "ifx_create_blob();". You then plug the blob id's into an array, and replace the blob columns with a question mark (?) in the query string. For updates/inserts, you are responsible for setting the blob contents with ifx_update_blob().
The behaviour of BLOB columns can be altered by configuration variables that also can be set at runtime:
configuration variable: ifx.textasvarchar
configuration variable: ifx.byteasvarchar
runtime functions:
ifx_textasvarchar(0): use blob id's for select queries with TEXT columns
ifx_byteasvarchar(0): use blob id's for select queries with BYTE columns
ifx_textasvarchar(1): return TEXT columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.
ifx_byteasvarchar(1): return BYTE columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.
configuration variable: ifx.blobinfile
runtime function:
ifx_blobinfile_mode(0): return BYTE columns in memory, the blob id lets you get at the contents.
ifx_blobinfile_mode(1): return BYTE columns in a file, the blob id lets you get at the file name.
If you set ifx_text/byteasvarchar to 1, you can use TEXT and BYTE columns in select queries just like normal (but rather long) VARCHAR fields. Since all strings are "counted" in PHP, this remains "binary safe". It is up to you to handle this correctly. The returned data can contain anything, you are responsible for the contents.
If you set ifx_blobinfile to 1, use the file name returned by ifx_get_blob(..) to get at the blob contents. Note that in this case YOU ARE RESPONSIBLE FOR DELETING THE TEMPORARY FILES CREATED BY INFORMIX when fetching the row. Every new row fetched will create new temporary files for every BYTE column.
The location of the temporary files can be influenced by the environment variable "blobdir", default is "." (the current directory). Something like: putenv(blobdir=tmpblob"); will ease the cleaning up of temp files accidentally left behind (their names all start with "blb").
Automatically trimming "char" (SQLCHAR and SQLNCHAR) data: This can be set with the configuration variable
ifx.charasvarchar: if set to 1 trailing spaces will be automatically trimmed, to save you some "chopping".
NULL values: The configuration variable ifx.nullformat (and the runtime function ifx_nullformat()) when set to TRUE will return NULL columns as the string "NULL", when set to FALSE they return the empty string. This allows you to discriminate between NULL columns and empty columns.
Tabella 1. Informix configuration options
Name | Default | Changeable |
---|---|---|
ifx.allow_persistent | "1" | PHP_INI_SYSTEM |
ifx.max_persistent | "-1" | PHP_INI_SYSTEM |
ifx.max_links | "-1" | PHP_INI_SYSTEM |
ifx.default_host | NULL | PHP_INI_SYSTEM |
ifx.default_user | NULL | PHP_INI_SYSTEM |
ifx.default_password | NULL | PHP_INI_SYSTEM |
ifx.blobinfile | "1" | PHP_INI_ALL |
ifx.textasvarchar | "0" | PHP_INI_ALL |
ifx.byteasvarchar | "0" | PHP_INI_ALL |
ifx.charasvarchar | "0" | PHP_INI_ALL |
ifx.nullformat | "0" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
Whether to allow persistent Informix connections.
The maximum number of persistent Informix connections per process.
The maximum number of Informix connections per process, including persistent connections.
The default host to connect to when no host is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.
The default user id to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.
The default password to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.
Set to TRUE if you want to return blob columns in a file, FALSE if you want them in memory. You can override the setting at runtime with ifx_blobinfile_mode().
Set to TRUE if you want to return TEXT columns as normal strings in select statements, FALSE if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().
Set to TRUE if you want to return BYTE columns as normal strings in select queries, FALSE if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().
Set to TRUE if you want to trim trailing spaces from CHAR columns when fetching them.
Set to TRUE if you want to return NULL columns as the literal string "NULL", FALSE if you want them returned as the empty string "". You can override this setting at runtime with ifx_nullformat().
result_id is a valid result id returned by ifx_query() or ifx_prepare().
Returns the number of rows affected by a query associated with result_id.
For inserts, updates and deletes the number is the real number (sqlerrd[2]) of affected rows. For selects it is an estimate (sqlerrd[0]). Don't rely on it. The database server can never return the actual number of rows that will be returned by a SELECT because it has not even begun fetching them at this stage (just after the "PREPARE" when the optimizer has determined the query plan).
Useful after ifx_prepare() to limit queries to reasonable result sets.
Esempio 1. Informix affected rows
|
See also ifx_num_rows().
(PHP 3>= 3.0.4, PHP 4 , PHP 5)
ifx_blobinfile_mode -- Set the default blob mode for all select queriesSet the default blob mode for all select queries. Mode "0" means save Byte-Blobs in memory, and mode "1" means save Byte-Blobs in a file.
Sets the default byte mode for all select-queries. Mode "0" will return a blob id, and mode "1" will return a varchar with text content.
Returns: always TRUE.
ifx_close() closes the link to an Informix database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.
Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
ifx_close() will not close persistent links generated by ifx_pconnect().
See also ifx_connect() and ifx_pconnect().
Returns a connection identifier on success, or FALSE on error.
ifx_connect() establishes a connection to an Informix server. All of the arguments are optional, and if they're missing, defaults are taken from values supplied in configuration file (ifx.default_host for the host (Informix libraries will use INFORMIXSERVER environment value if not defined), ifx.default_user for user, ifx.default_password for the password (none if not defined).
In case a second call is made to ifx_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.
The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling ifx_close().
See also ifx_pconnect() and ifx_close().
Duplicates the given blob object. bid is the ID of the blob object.
Returns FALSE on error otherwise the new blob object-id.
Creates an blob object.
type: 1 = TEXT, 0 = BYTE
mode: 0 = blob-object holds the content in memory, 1 = blob-object holds the content in file.
param: if mode = 0: pointer to the content, if mode = 1: pointer to the filestring.
Return FALSE on error, otherwise the new blob object-id.
Creates an char object. param should be the char content.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Executes a previously prepared query or opens a cursor for it.
Does NOT free result_id on error.
Also sets the real number of ifx_affected_rows() for non-select statements for retrieval by ifx_affected_rows()
See also: ifx_prepare().
The Informix error codes (SQLSTATE & SQLCODE) formatted as follows :
x [SQLSTATE = aa bbb SQLCODE=cccc]
where x = space : no error
E : error
N : no more data
W : warning
? : undefined
If the "x" character is anything other than space, SQLSTATE and SQLCODE describe the error in more detail.
See the Informix manual for the description of SQLSTATE and SQLCODE
Returns in a string one character describing the general results of a statement and both SQLSTATE and SQLCODE associated with the most recent SQL statement executed. The format of the string is "(char) [SQLSTATE=(two digits) (three digits) SQLCODE=(one digit)]". The first character can be ' ' (space) (success), 'W' (the statement caused some warning), 'E' (an error happened when executing the statement) or 'N' (the statement didn't return any data).
See also: ifx_errormsg()
Returns the Informix error message associated with the most recent Informix error, or, when the optional "errorcode" parameter is present, the error message corresponding to "errorcode".
See also ifx_error().
Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.
Blob columns are returned as integer blob id values for use in ifx_get_blob() unless you have used ifx_textasvarchar(1) or ifx_byteasvarchar(1), in which case blobs are returned as string values. Returns FALSE on error
result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).
position is an optional parameter for a "fetch" operation on "scroll" cursors: "NEXT", "PREVIOUS", "CURRENT", "FIRST", "LAST" or a number. If you specify a number, an "absolute" row fetch is executed. This parameter is optional, and only valid for SCROLL cursors.
ifx_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0, with the column name as key.
Subsequent calls to ifx_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.
Esempio 1. Informix fetch rows
|
Returns an associative array with fieldnames as key and the SQL fieldproperties as data for a query with result_id. Returns FALSE on error.
Returns the Informix SQL fieldproperties of every field in the query as an associative array. Properties are encoded as: "SQLTYPE;length;precision;scale;ISNULLABLE" where SQLTYPE = the Informix type like "SQLVCHAR" etc. and ISNULLABLE = "Y" or "N".
Returns an associative array with fieldnames as key and the SQL fieldtypes as data for query with result_id. Returns FALSE on error.
Deletes the blobobject for the given blob object-id bid. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Deletes the charobject for the given char object-id bid. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Releases resources for the query associated with result_id. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Returns the content of the blob object for the given blob object-id bid.
Returns the content of the char object for the given char object-id bid.
result_id is a valid result id returned by ifx_query() or ifx_prepare().
Returns a pseudo-row (associative array) with sqlca.sqlerrd[0] ... sqlca.sqlerrd[5] after the query associated with result_id.
For inserts, updates and deletes the values returned are those as set by the server after executing the query. This gives access to the number of affected rows and the serial insert value. For SELECTs the values are those saved after the PREPARE statement. This gives access to the *estimated* number of affected rows. The use of this function saves the overhead of executing a "select dbinfo('sqlca.sqlerrdx')" query, as it retrieves the values that were saved by the ifx driver at the appropriate moment.
Esempio 1. Retrieve Informix sqlca.sqlerrd[x] values
|
Returns the number of rows fetched or FALSE on error.
Formats all rows of the result_id query into a HTML table. The optional second argument is a string of <table> tag options
Esempio 1. Informix results as HTML table
|
Sets the default return value of a NULL-value on a fetch row. Mode "0" returns "", and mode "1" returns "NULL".
Returns the number of columns in query for result_id or FALSE on error
After preparing or executing a query, this call gives you the number of columns in the query.
Gives the number of rows fetched so far for a query with result_id after a ifx_query() or ifx_do() query.
Returns: A positive Informix persistent link identifier on success, or FALSE on error
ifx_pconnect() acts very much like ifx_connect() with two major differences.
This function behaves exactly like ifx_connect() when PHP is not running as an Apache module. First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ifx_close() will not close links established by ifx_pconnect()).
This type of links is therefore called 'persistent'.
See also: ifx_connect().
Returns an integer result_id for use by ifx_do(). Sets affected_rows for retrieval by the ifx_affected_rows() function.
Prepares query on connection conn_id. For "select-type" queries a cursor is declared and opened. The optional cursor_type parameter allows you to make this a "scroll" and/or "hold" cursor. It's a bitmask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together.
For either query type the estimated number of affected rows is saved for retrieval by ifx_affected_rows().
If you have BLOB (BYTE or TEXT) columns in the query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.
If the contents of the TEXT (or BYTE) column allow it, you can also use "ifx_textasvarchar(1)" and "ifx_byteasvarchar(1)". This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.
With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).
See also: ifx_do().
Returns a positive Informix result identifier on success, or FALSE on error.
A "result_id" resource used by other functions to retrieve the query results. Sets "affected_rows" for retrieval by the ifx_affected_rows() function.
ifx_query() sends a query to the currently active database on the server that's associated with the specified link identifier.
Executes query on connection conn_id. For "select-type" queries a cursor is declared and opened. The optional cursor_type parameter allows you to make this a "scroll" and/or "hold" cursor. It's a bitmask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together. Non-select queries are "execute immediate". IFX_SCROLL and IFX_HOLD are symbolic constants and as such shouldn't be between quotes. I you omit this parameter the cursor is a normal sequential cursor.
For either query type the number of (estimated or real) affected rows is saved for retrieval by ifx_affected_rows().
If you have BLOB (BYTE or TEXT) columns in an update query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.
If the contents of the TEXT (or BYTE) column allow it, you can also use "ifx_textasvarchar(1)" and "ifx_byteasvarchar(1)". This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.
With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).
Esempio 1. Show all rows of the "orders" table as a HTML table
|
Esempio 2. Insert some values into the "catalog" table
|
See also ifx_connect().
Sets the default text mode for all select-queries. Mode "0" will return a blob id, and mode "1" will return a varchar with text content.
Updates the content of the blob object for the given blob object bid. content is a string with new data. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Updates the content of the char object for the given char object bid. content is a string with new data. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Deletes the slob object on the given slob object-id bid. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Creates an slob object and opens it. Modes: 1 = LO_RDONLY, 2 = LO_WRONLY, 4 = LO_APPEND, 8 = LO_RDWR, 16 = LO_BUFFER, 32 = LO_NOBUFFER -> or-mask. You can also use constants named IFX_LO_RDONLY, IFX_LO_WRONLY etc. Return FALSE on error otherwise the new slob object-id.
Deletes the slob object. bid is the Id of the slob object. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Opens an slob object. bid should be an existing slob id. Modes: 1 = LO_RDONLY, 2 = LO_WRONLY, 4 = LO_APPEND, 8 = LO_RDWR, 16 = LO_BUFFER, 32 = LO_NOBUFFER -> or-mask. Returns FALSE on error otherwise the new slob object-id.
Reads nbytes of the slob object. bid is a existing slob id and nbytes is the number of bytes read. Return FALSE on error otherwise the string.
Sets the current file or seek position of an open slob object. bid should be an existing slob id. Modes: 0 = LO_SEEK_SET, 1 = LO_SEEK_CUR, 2 = LO_SEEK_END and offset is an byte offset. Return FALSE on error otherwise the seek position.
Returns the current file or seek position of an open slob object bid should be an existing slob id. Return FALSE on error otherwise the seek position.
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!
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
See also ibase_modify_user() and ibase_delete_user().
This function returns the number of rows that were affected by the previous query that was executed from within the transaction context specified by link_identifier. If link_identifier is a connection resource, its default transaction is used.
See also ibase_query() and ibase_execute().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ibase_blob_add() aggiunge dati ad un blob creato con ibase_blob_create().
Vedere anche ibase_blob_cancel(), ibase_blob_close(), ibase_blob_create() e ibase_blob_import().
Questa funzione cancella un BLOB creato da ibase_create_blob() se questo non è già stato chiuso da ibase_blob_close(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche ibase_blob_close(), ibase_blob_create() e ibase_blob_import().
Questa funzione chiude un BLOB aperto in lettura da ibase_open_blob() o aperto in scrittura da ibase_create_blob(). Se il BLOB è stato letto, questa funzione restituisce TRUE se riesce, se il BLOB è stato scritto, questa funzion restituisce la stringa contenente il BLOB id assegnato dal database. Se si verificano errori, questa funzione restituisce FALSE.
Vedere anche ibase_blob_cancel() e ibase_blob_open().
ibase_blob_create() crea un nuovo blob da riempire di dati. La funzione restituisce un puntatore al BLOB da utilizzare successivamente con ibase_blob_add() oppure FALSE se si verifica un errore.
Vedere anche ibase_blob_add(), ibase_blob_cancel(), ibase_blob_close() e ibase_blob_import().
Questa funzione apre un BLOB in lettura ed invia il suo contenuto direttamente allo standard output (prevalentemente il browser). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche ibase_blob_open(), ibase_blob_close() e ibase_blob_get().
Questa funzine restituisce almeno len bytes da un BLOB che è stato aperto in lettura con ibase_blob_open(). Restituisce FALSE se si verifica un errore.
<?php $sql = "SELECT blob_value FROM table"; $result = ibase_query($sql); $data = ibase_fetch_object($result); $blob_data = ibase_blob_info($data->BLOB_VALUE); $blob_hndl = ibase_blob_open($data->BLOB_VALUE); echo ibase_blob_get($blob_hndl, $blob_data[0]); ?> |
Nota: Non è possibile leggere da un BLOB che è stato aperto in scrittura da ibase_blob_create().
Vedere anche ibase_blob_open(), ibase_blob_close() e ibase_blob_echo().
(PHP 3>= 3.0.7, PHP 4 , PHP 5)
ibase_blob_import -- Create un blob, copy il file al suo interno e lo chiudeQuesta funzione crea un BLOB e vi inserisce un file intero, lo chiude e restituisce l'id assegnato al BLOB. file_handle è un puntatore di file restituito da fopen(). La funzione restituisce FALSE se si verifica un errore.
Vedere anche ibase_blob_add(), ibase_blob_cancel(), ibase_blob_close() e ibase_blob_create().
(PHP 3>= 3.0.7, PHP 4 , PHP 5)
ibase_blob_info -- Restituisce la lunghezza del blob e altre informazioni utliliLa funzione restituisce un array contenente informazioni su un BLOB. Le informazioni restituite consistono nella lunghezza del BLOB, il numero di segmenti contenuti, la dimensione del segmento più grande, e se si tratta di un BLOB segmentato o a flusso.
ibase_blob_open() apre un BLOB esistente in lettura. Restituisce un puntatore al BLOB da usarsi successivamente con ibase_blob_get() oppure FALSE se si verifica un errore.
Vedere anche ibase_blob_close(), ibase_blob_echo() e ibase_blob_get().
Chiude il collegamento ad un database InterBase che è stato associato con un id di connessione restituito da ibase_connect(). Se l'id di connessione viene omesso, viene considerato l'ultimo collegamento che è stato aperto. La transazione predefinita sul collegamento viene "committed", le altre transazioni vengono "rolled back".
Vedere anche ibase_connect() e ibase_pconnect().
If called without an argument, this function commits the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be committed. If the argument is a transaction identifier, the corresponding transaction will be committed. The transaction context will be retained, so statements executed from within this transaction will not be invalidated. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Se chiamata senza parametri, la funzione esegue il commit della transazione di default, sul link di default. Se l'argomento identifica una transazione, verrà aseguito il commit della transazione di default su quella connessione. Se l'argomento identifica una transazione verrà eseguito il commit della transazione. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Stabilisce una connessione con un server InterBase. Il parametro database deve essere un percorso valido di un file di database sul server dove risiede. Se il server non fosse locale, bisogna aggiungere prima del percorso o 'hostname:' (TCP/IP), o '//hostname/' (NetBEUI) o 'hostname@' (IPX/SPX), in base al protocollo di connessione utilizzato. username e password possono venire specificati anche con le direttive di configurazione del PHP ibase.default_user e ibase.default_password. charset è il set di caratteri predefinito per un database. buffers è il numero di buffer di database da allocare per la cache dal lato server. Se è 0 o viene omesso, il server usa il suo valore predefinito. dialect seleziona il dialetto SQL predefinito per ogni operazione eseguita all'interno di una connessione, e il suo valore predefinito è il più alto supportato dalle librerie del client.
Nel caso di una seconda chiamata fatta con ibase_connect() con gli stessi parametri, non verrà creato alcun nuovo collegamento, bensì, l'identificatore del collegamento già aperto verrà restituito. Il collegamento al server verrà chiuso appena termina l'esecuzione dello script, a meno che non venga chiuso prima esplicitamente chiamando ibase_close().
Esempio 1. Esempio di ibase_connect()
|
Nota: Il parametro opzionale buffers è stato aggiunto in PHP 4.0.0.
Nota: dialect è stato aggiunto in PHP 4.0.0. E' funzionante solo con InterBase 6 e versioni successive.
Nota: role è stato aggiunto in PHP 4.0.0. E' funzionante solo con InterBase 5 e versioni successive.
Nota: Se si verificano degli errori tipo "arithmetic exception", "numeric overflow", oppure "string truncation. Cannot transliterate character between character sets" (questo capita quando si tenta di usare dei caratteri accentati) questa funzione o dopo la funzione ibase_query(), occorre impostare il set di caratteri (ad esempio ISO8859_1 oppure il set di caratteri corrente).
Vedere anche: ibase_pconnect() e ibase_close().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ibase_delete_user -- Delete a user from a security database (only for IB6 or later)Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
See also ibase_add_user() and ibase_modify_user().
This functions drops a database that was opened by either ibase_connect() or ibase_pconnect(). The database is closed and deleted from the server. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also ibase_connect() and ibase_pconnect().
Returns the error code that resulted from the most recent InterBase function call. Returns FALSE if no error occurred.
See also ibase_errmsg().
Restituisce una stringa contenente un messaggio di errore dalla più recente funzione InterBse eseguita. La funzione restituisce FALSE se non vi sono errori.
Vedere anche ibase_errcode().
Esegue una query preparata da ibase_prepare(). Se la query genera un errore, la funzione restituisce FALSE. Se invece ha successo ed si ha un set di risultati (tipo un query SELECT), la funzione ne restituisce l'identificativo. Se la query ha successo e non vi sono risultati, restituisce TRUE
Ciò è molto più efficace che usare ibase_query() se state ripetendo uno stesso tipo di query molte volte cambiando solo alcuni parametri.
Esempio 1. Esempio di uso di ibase_execute()
|
Nota: In PHP 5.0.0 e successivi, questa funzione restituisce il numero di righe toccate dalla query (se >0 ed è applicabile al tipo di query). Una query che ha successo, ma che non modifica nessuna righa (ad esempio un UPDATE su record che non esistono) restituirà TRUE
Vedere anche ibase_query().
ibase_fetch_assoc() returns an associative array that corresponds to the fetched row. Subsequent calls will return the next row in the result set, or FALSE if there are no more rows.
ibase_fetch_assoc() fetches one row of data from the result. If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using ibase_fetch_row() or use alias names in your query.
fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.
See also ibase_fetch_row() and ibase_fetch_object().
Elabora una riga come un pseudo-oggetto da un result_id ottenuto o da ibase_query() o da ibase_execute().
<?php $dbh = ibase_connect($host, $username, $password); $stmt = 'SELECT * FROM tblname'; $sth = ibase_query($dbh, $stmt); while ($row = ibase_fetch_object($sth)) { echo $row->email . "\n"; } ibase_close($dbh); ?> |
Chiamate successive a ibase_fetch_object() restituiscono la successiva riga dai risultati della query o FALSE se non vi sono ulteriori righe.
Il parametro fetch_flag è una combinazione delle costanti IBASE_TEXT e IBASE_UNIXTIME con l'operatore OR. Passando IBASE_TEXT si forza questa funzione a resituire il contenuto del BLOB anzichè l'identificatore del BLOB. Passando IBASE_UNIXTIME si forza la funzione a restituire i valori di data/ora com Unix timestamp anzichè come stringa formattata.
Vedere anche ibase_fetch_row() e ibase_fetch_assoc().
Restituisce un array che corrisponde alla riga ottenuta o FALSE se non ci sono righe rimanenti.
ibase_fetch_row() prende una riga di dati dai risultati associati allo specificato result_identifier. La riga viene restituita come un array. Ogni colonna risultante viene immagazzinata in un offset dell'array, l'offset inizia da 0.
Chiamate successive a ibase_fetch_row() restituiscono la successiva riga dai risultati della query o FALSE se non vi sono ulteriori righe.
Restituisce un array con informazioni relative a un campo dopo che una query select è stata eseguita. L'array ha la forma name, alias, relation, length e type.
$rs=ibase_query("SELECT * FROM tablename"); $coln = ibase_num_fields($rs); for ($i=0; $i < $coln; $i++) { $col_info = ibase_field_info($rs, $i); echo "name: ".$col_info['name']."\n"; echo "alias: ".$col_info['alias']."\n"; echo "relation: ".$col_info['relation']."\n"; echo "length: ".$col_info['length']."\n"; echo "type: ".$col_info['type']."\n"; } |
This function causes the registered event handler specified by event to be cancelled. The callback function will no longer be called for the events it was registered to handle. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also ibase_set_event_handler().
Libera un result set che è stato creato da ibase_query().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ibase_modify_user -- Modify a user to a security database (only for IB6 or later)Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
See also ibase_add_user() and ibase_delete_user().
This function assigns a name to a result set. This name can be used later in UPDATE|DELETE ... WHERE CURRENT OF name statements. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
<?php $result = ibase_query("SELECT field1,field2 FROM table FOR UPDATE"); ibase_name_result($result, "my_cursor"); $updateqry = ibase_prepare("UPDATE table SET field2 = ? WHERE CURRENT OF my_cursor"); for ($i = 0; ibase_fetch_row($result); ++$i) { ibase_execute($updateqry, $i); } ?> |
See also ibase_prepare() and ibase_execute().
Restituisce un integer contenente il numero di campi in un result set.
<?php $dbh = ibase_connect ($host, $username, $password); $stmt = 'SELECT * FROM tblname'; $sth = ibase_query ($dbh, $stmt); if (ibase_num_fields($sth) > 0) { while ($row = ibase_fetch_object ($sth)) { print $row->email . "\n"; } } else { die ("Nessun result è stato trovato per la tua query"); } ibase_close ($dbh); ?> |
Vedere anche: ibase_field_info().
This function returns the number of parameters in the prepared query specified by query. This is the number of binding arguments that must be present when calling ibase_execute().
See also ibase_prepare() and ibase_param_info().
Returns an array with information about a parameter after a query has been prepared. The array is in the form of name, alias, relation, length, type.
See also ibase_field_info() and ibase_num_params().
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
ibase_pconnect -- Crea una connessione persistente ad un database Interbaseibase_pconnect() agisce in modo molto simile a ibase_connect() con due differenze principali. Innanzitutto, durante la connessione, la funzione cercherà prima di trovare un collegamento (persistente) che è già stato aperto con gli stessi parametri. Se viene trovato, il suo identificatore verrà restituito al posto di aprire una nuova connessione. In secondo luogo, la connessione al server InterBase non verrà chiusa al termine dell'esecuzione dello script. Invece, il collegamento resterà aperto per un uso futuro (ibase_close() non chiuderà i collegamenti stabiliti da ibase_pconnect()). Questo tipo di collegamento è perciò chiamato 'persistente'.
Nota: buffers è stato aggiunto in PHP4-RC2.
Nota: dialect è stato aggiunto in PHP4-RC2. Funziona soltanto con InterBase 6 e superiori.
Nota: role è stato aggiunto in PHP4-RC2. Funziona soltanto con InterBase 5 e superiori.
Vedere anche ibase_connect() per il significato dei parametri passati a questa funzione. Sono esattamente gli stessi.
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
ibase_prepare -- Prepara una query per un successivo binding dei segnaposto dei parametri ed esecuzionePrepara una query per un successivo binding dei segnaposto dei parametri ed esecuzione (tramite ibase_execute()).
Esegue una query su di un database InterBase. Se la query non ha successo, restituisce FALSE. Se ha successo e vi sono riga di risultato (come si ha ad esempio con le query SELECT), restituisce un identificatore di risorsa. Se la query ha avuto successo, ma non ci sono risultati, restituisce TRUE. Restutuisce FALSE se la query fallisce.
Vedere anche ibase_errmsg(), ibase_fetch_row(), ibase_fetch_object() e ibase_free_result().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
If called without an argument, this function rolls back the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be rolled back. If the argument is a transaction identifier, the corresponding transaction will be rolled back. The transaction context will be retained, so statements executed from within this transaction will not be invalidated. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Rolls back transaction trans_number which was created with ibase_trans().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
This function registers a PHP user function as event handler for the specified events. The callback is called with the event name and the link resource as arguments whenever one of the specified events is posted by the database. The callback must return FALSE if the event handler should be canceled. Any other return value is ignored.
<?php function event_handler($event_name, $link) { if ($event_name=="NEW ORDER") { // process new order ibase_query($link, "UPDATE orders SET status='handled'"); } else if ($event_name=="DB_SHUTDOWN") { // free event handler return false; } } ibase_set_event_handler($link, "event_handler", "NEW_ORDER", "DB_SHUTDOWN"); ?> |
The return value is an event resource. This resource can be used to free the event handler using ibase_free_event_handler().
See also ibase_free_event_handler() and ibase_wait_event().
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
ibase_timefmt -- Imposta il formato delle colonne timestamp, date e time restituite dalle queryImposta il formato delle colonne di tipo timestamp, date o time restituite dalle query. Internamente, le colonne vengono formattate dalla funzione C strftime(), quindi fate riferimento alla sua documentazione riguardo al formato della stringa. columntype è una delle costanti IBASE_TIMESTAMP, IBASE_DATE e IBASE_TIME. Se omessa, è predefinita a IBASE_TIMESTAMP per motivi di compatibilità con il passato.
<?php // Le colonne di tipo TIME di InterBase vengono restituite nella // forma '05 hours 37 minutes'. ibase_timefmt("%H hours %M minutes", IBASE_TIME); ?> |
Potete impostare anche valori predefiniti per questi formati con la direttiva di configurazione ibase.timestampformat, ibase.dateformat e ibase.timeformat.
Nota: columntype è stata aggiunta in PHP 4.0. Ha significato solo con InterBase versione 6 e successive.
Nota: Un'incompatibilità con il passato si è avuta nel PHP 4.0 quando la direttiva di configurazione del PHP ibase.timeformat è stata rinominata in ibase.timestampformat e la direttiva ibase.dateformat e ibase.timeformat sono state aggiunte, così che i loro nomi fossero più simili alle loro funzionalità.
This function suspends execution of the script until one of the specified events is posted by the database. The name of the event that was posted is returned. This function accepts up to 15 event arguments.
See also ibase_set_event_handler() and ibase_free_event_handler().
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.
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.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Most of the id3 functions either let you specify or return a tag version. In order to specify the version please use on of these constants.
ID3_V1_0 is used if you are working with ID3 V1.0 tags. These tags may contain the fields title, artist, album, genre, year and comment.
ID3_V1_1 is used if you are working with ID3 V1.1 tags. These tags may all information contained in v1.0 tags plus the track number.
ID3_V2 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.
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.
See also id3_get_genre_list() and id3_get_genre_name().
id3_get_genre_list() returns an array containing all possible genres that may be stored in an ID3 tag. This list has been created by Eric Kemp and later extended by WinAmp.
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
This will output:
|
See also id3_get_genre_name() and id3_get_genre_id().
id3_get_genre_name() returns the name for a genre id.
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.
See also id3_get_genre_list() and id3_get_genre_id().
(no version information, might be only in CVS)
id3_get_tag -- Get all information stored in an ID3 tagid3_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.
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() retrieves the version(s) of the ID3 tag(s) in the MP3 file. As a tag can contain ID3 v1.x and v2.x tags, the return value of this function should be bitwise compared with the predefined constants ID3_V1_0, ID3_V1_1 and ID3_V2.
Nota: Instead of a filename you may also pass a valid stream resource.
Esempio 1. id3_get_version() example
This will output something like:
|
If a file contains an ID3 v1.1 tag, it always contains a 1.0 tag, as version 1.1 is just an extension of 1.0.
See also id3_get_tag(), id3_set_tag() and id3_remove_tag().
id3_remove_tag() is used to remove the information stored of an ID3 tag. If no tag has been present, it will return FALSE and leave the file as it was.
Nota: Instead of a filename you may also pass a valid stream resource.
The optional version parameter allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags.
Nota: Currently id3_remove_tag() only supports version 1.0 and 1.1. If you choose to remove a 1.0 tag and the file contains a 1.1 tag, this tag will be removed, as v1.1 is only an extension of 1.0.
See also id3_get_tag(), id3_set_tag() and id3_get_version().
(no version information, might be only in CVS)
id3_set_tag -- Update information stored in an ID3 tagid3_set_tag() is used to change the information stored of an ID3 tag. If no tag has been present, it will be added to the file.
Nota: Instead of a filename you may also pass a valid stream resource.
The optional version parameter allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags.
Esempio 1. id3_set_tag() example
If the file is writeable, this will output:
|
Nota: Currently id3_set_tag() only supports version 1.0 and 1.1.
The following keys may be used in the associative array:
Tabella 1. Keys in the associative array
key | possible value | available in version |
---|---|---|
title | string with maximum of 30 characters | v1.0, v1.1 |
artist | string with maximum of 30 characters | v1.0, v1.1 |
album | string with maximum of 30 characters | v1.0, v1.1 |
year | 4 digits | v1.0, v1.1 |
genre | integer value between 0 and 147 | v1.0, v1.1 |
comment | string with maximum of 30 characters (28 in v1.1) | v1.0, v1.1 |
track | integer between 0 and 255 | v1.1 |
See also id3_get_tag(), id3_remove_tag() and id3_get_version().
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. |
To compile PHP with Ingres support, you need the Open API library and header files included with Ingres II.
In order to have these functions available, you must compile PHP with Ingres support by using the --with-ingres[=DIR] option, where DIR is the Ingres base directory, which defaults to /II/ingres. If the II_SYSTEM environment variable isn't correctly set you may have to use --with-ingres=DIR to specify your Ingres installation directory.
When using this extension with Apache, if Apache does not start and complains with "PHP Fatal error: Unable to start ingres_ii module in Unknown on line 0" then make sure the environment variable II_SYSTEM is correctly set. Adding "export II_SYSTEM="/home/ingres/II" in the script that starts Apache, just before launching httpd, should be fine.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Ingres II configuration options
Name | Default | Changeable |
---|---|---|
ingres.allow_persistent | "1" | PHP_INI_SYSTEM |
ingres.max_persistent | "-1" | PHP_INI_SYSTEM |
ingres.max_links | "-1" | PHP_INI_SYSTEM |
ingres.default_database | NULL | PHP_INI_ALL |
ingres.default_user | NULL | PHP_INI_ALL |
ingres.default_password | NULL | PHP_INI_ALL |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.
See also ingres_pconnect() and ingres_close().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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).
See also ingres_query(), ingres_num_fields(), ingres_field_name(), ingres_fetch_object(), and ingres_fetch_row().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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).
See also ingres_query(), ingres_num_fields(), ingres_field_name(), ingres_fetch_array(), and ingres_fetch_row().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.
See also ingres_num_fields(), ingres_query(), ingres_fetch_array(), and ingres_fetch_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. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
(PHP 4 >= 4.0.2, PHP 5)
ingres_num_rows -- Get the number of rows affected or returned by the last queryAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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:
close (see ingres_close())
commit (see ingres_commit())
connect (see ingres_connect())
disconnect (see ingres_close())
get dbevent
prepare to commit
rollback (see ingres_rollback())
savepoint
set autocommit (see ingres_autocommit())
all cursor related queries are unsupported
See also ingres_fetch_array(), ingres_fetch_object(), ingres_fetch_row(), ingres_commit(), ingres_rollback(), and ingres_autocommit().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
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
Detailed installation instructions can be found at http://www.schumann.cx/ircg/. We urge you to use the provided installation script.
It is not recommended, but you can try enable IRCG support yourself. Provide the path to the ircg-config script, --with-ircg-config=path/to/irc-config and in addition add --with-ircg to your configure line.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Set channel mode flags for channel on server connected to by connection. Mode flags are passed in mode_spec and are applied to the user specified by nick.
Mode flags are set or cleared by specifying a mode character and prepending it with a plus or minus character, respectively. E.g. operator mode is granted by '+o' and revoked by '-o', as passed as mode_spec.
ircg_disconnect() will close a connection to a server previously established with ircg_pconnect().
See also: ircg_pconnect().
ircg_fetch_error_msg() returns the error from a failed connection.
Nota: Error code is stored in first array element, error text in second. The error code is equivalent to IRC reply codes as defined by RFC 2812.
Function ircg_get_username() returns the username for the specified connection connection. Returns FALSE if connection died or is not valid.
Encodes a HTML string html_string for output. This exposes the interface which the IRCG extension uses internally to reformat data coming from an IRC link. The function causes IRC color/font codes to be encoded in HTML and escapes certain entities.
This function adds user nick to the ignore list of connection connection. Afterwards, IRCG will suppress all messages from this user through the associated connection.
See also: ircg_ignore_del().
This function removes user nick from the IRCG ignore list associated with connection.
See also: ircg_ignore_add().
ircg_invite() will send an invitation to the user nickname, prompting him to join channel. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
ircg_is_conn_alive() returns TRUE if connection is still alive and working or FALSE, if the connection has died for some reason.
Join the channel channel on the server connected to by connection. IRCG will optionally pass the room key key.
Kick user nick from channel on server connected to by connection. reason should give a short message describing why this action was performed.
ircg_list() will request a list of users in the channel. The answer is sent to the output defined by ircg_set_file() or ircg_set_current(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. ircg_list() example
This example will output something similar to:
|
See also: ircg_set_file(), ircg_set_current(), and ircg_who().
(PHP 4 >= 4.0.5, PHP 5)
ircg_lookup_format_messages -- Check for the existence of a format message setCheck for the existence of the format message set name. Sets may be registered with ircg_register_format_messages(), a default set named ircg is always available. Returns TRUE, if the set exists and FALSE otherwise.
See also: ircg_register_format_messages()
ircg_lusers() will request a statistical breakdown of users on the network connected to on connection. The answer is sent to the output defined by ircg_set_file() or ircg_set_current(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also: ircg_set_file(), and ircg_set_current().
ircg_msg() will send the message to a channel or user on the server connected to by connection. A recipient starting with # or & will send the message to a channel, anything else will be interpreted as a username.
Setting the optional parameter suppress to a TRUE value will suppress output of your message to your own connection. This so-called loopback is necessary, because the IRC server does not echo PRIVMSG commands back to us.
Change your nickname on the given connection to the one given in nick, if possible.
Will return TRUE on success and FALSE on failure.
(PHP 4 >= 4.0.6, PHP 5)
ircg_nickname_escape -- Encode special characters in nickname to be IRC-compliantFunction ircg_nickname_escape() returns an encoded nickname specified by nick which is IRC-compliant.
See also: ircg_nickname_unescape()
Function ircg_nickname_unescape() returns a decoded nickname, which is specified in nick.
See also: ircg_nickname_escape()
This function will send the message text to the user nick on the server connected to by connection. IRC servers and other software will not automatically generate replies to NOTICEs in contrast to other message types.
ircg_oper() will authenticate the logged in user on connection as an IRC operator. name and password must match a registered IRC operator account. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Leave the channel channel on the server connected to by connection.
ircg_pconnect() will try to establish a connection to an IRC server and return a connection resource handle for further use.
The only mandatory parameter is username, this will set your initial nickname on the server. server_ip and server_port are optional and default to 127.0.0.1 and 6667.
Nota: For now parameter server_ip will not do any hostname lookups and will only accept IP addresses in numerical form. DNS lookups are expensive and should be done in the context of IRCG.
You can customize the output of IRC messages and events by selecting a format message set previously created with ircg_register_format_messages() by specifying the set's name in msg_format.
If you want to handle CTCP messages such as ACTION (/me), you need to define a mapping from CTCP type (e.g. ACTION) to a custom format string. Do this by passing an associative array as ctcp_messages. The keys of the array are the CTCP type and the respective value is the format message.
You can define "ident", "password", and "realname" tokens which are sent to the IRC server by setting these in an associative array. Pass that array as user_settings.
See also: ircg_disconnect(), ircg_is_conn_alive(), ircg_register_format_messages().
With ircg_register_format_messages() you can customize the way your IRC output looks like or which script functions are invoked on the client side.
Plain channel message
Private message received
Private message sent
Some user leaves channel
Some user enters channel
Some user was kicked from the channel
Topic has been changed
Error
Fatal error
Join list end(?)
Self part(?)
Some user changes his nick
Some user quits his connection
Mass join begin
Mass join element
Mass join end
Whois user
Whois server
Whois idle
Whois channel
Whois end
Voice status change on user
Operator status change on user
Banlist
Banlist end
%f - from
%t - to
%c - channel
%r - plain message
%m - encoded message
%j - js encoded message
1 - mod encode
2 - nickname decode
See also: ircg_lookup_format_messages().
Select the current HTTP connection for output in this execution context. Every output sent from the server connected to by connection will be copied to standard output while using default formatting or a format message set specified by ircg_register_format_messages().
See also: ircg_register_format_messages().
Function ircg_set_file() specifies a logfile path in which all output from connection connection will be logged. Returns TRUE on success, otherwise FALSE.
In case of the termination of connection connection IRCG will connect to host at port (Note: host must be an IPv4 address, IRCG does not resolve host-names due to blocking issues), send data to the new host connection and will wait until the remote part closes connection. This can be used to trigger a PHP script for example.
This feature requires IRCG 3.
Change the topic for channel channel on the server connected to by connection to new_topic.
ircg_who() will request a list of users whose nickname is matching mask on connected network connection. The optional parameter ops_only will shrink the list to server operators only.
The answer is sent to the output defined by ircg_set_file() or ircg_set_current(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also: ircg_set_file(), and ircg_set_current().
There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension.
The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
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.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Java configuration options
Name | Default | Changeable |
---|---|---|
java.class.path | NULL | PHP_INI_ALL |
java.home | NULL | PHP_INI_ALL |
java.library.path | NULL | PHP_INI_ALL |
java.library | JAVALIB | PHP_INI_ALL |
Esempio 1. Java Example
|
Esempio 2. AWT Example
|
new Java() will create an instance of a class if a suitable constructor is available. If no parameters are passed and the default constructor is useful as it provides access to classes like java.lang.System which expose most of their functionallity through static methods.
Accessing a member of an instance will first look for bean properties then public fields. In other words, print $date.time will first attempt to be resolved as $date.getTime(), then as $date.time.
Both static and instance members can be accessed on an object with the same syntax. Furthermore, if the java object is of type java.lang.Class, then static members of the class (fields and methods) can be accessed.
Exceptions raised result in PHP warnings, and NULL results. The warnings may be eliminated by prefixing the method call with an "@" sign. The following APIs may be used to retrieve and reset the last error:
Overload resolution is in general a hard problem given the differences in types between the two languages. The PHP Java extension employs a simple, but fairly effective, metric for determining which overload is the best match.
Additionally, method names in PHP are not case sensitive, potentially increasing the number of overloads to select from.
Once a method is selected, the parameters are coerced if necessary, possibly with a loss of data (example: double precision floating point numbers will be converted to boolean).
In the tradition of PHP, arrays and hashtables may pretty much be used interchangably. Note that hashtables in PHP may only be indexed by integers or strings; and that arrays of primitive types in Java can not be sparse. Also note that these constructs are passed by value, so may be expensive in terms of memory and time.
The Java Servlet SAPI builds upon the mechanism defined by the Java extension to enable the entire PHP processor to be run as a servlet. The primary 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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
See java_last_exception_get() for an example.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The following example demonstrates the usage of Java's exception handler from within PHP:
Esempio 1. Java exception handler
|
LDAP is the Lightweight Directory Access Protocol, and is a protocol used to access "Directory Servers". The Directory is a special kind of database that holds information in a tree structure.
The concept is similar to your hard disk directory structure, except that in this context, the root directory is "The world" and the first level subdirectories are "countries". Lower levels of the directory structure contain entries for companies, organisations or places, while yet lower still we find directory entries for people, and perhaps equipment or documents.
To refer to a file in a subdirectory on your hard disk, you might use something like:
/usr/local/myapp/docs
The forwards slash marks each division in the reference, and the sequence is read from left to right.
The equivalent to the fully qualified file reference in LDAP is the "distinguished name", referred to simply as "dn". An example dn might be:
cn=John Smith,ou=Accounts,o=My Company,c=US
The comma marks each division in the reference, and the sequence is read from right to left. You would read this dn as:
country = US
organization = My Company
organizationalUnit = Accounts
commonName = John Smith
In the same way as there are no hard rules about how you organise the directory structure of a hard disk, a directory server manager can set up any structure that is meaningful for the purpose. However, there are some conventions that are used. The message is that you can not write code to access a directory server unless you know something about its structure, any more than you can use a database without some knowledge of what is available.
Lots of information about LDAP can be found at
The Netscape SDK contains a helpful Programmer's Guide in HTML format.
You will need to get and compile LDAP client libraries from either the University of Michigan ldap-3.3 package, Netscape Directory SDK 3.0 or OpenLDAP to compile PHP with LDAP support.
LDAP support in PHP is not enabled by default. You will need to use the --with-ldap[=DIR] configuration option when compiling PHP to enable LDAP support. DIR is the LDAP base install directory.
Note to Win32 Users: In order to enable this module on a Windows environment, you must copy 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.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
For further details and definition of the PHP_INI_* constants see ini_set().
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Retrieve information for all entries where the surname starts with "S" from a directory server, displaying an extract with name and email address.
Esempio 1. LDAP search example
|
Before you can use the LDAP calls you will need to know ..
The name or address of the directory server you will use
The "base dn" of the server (the part of the world directory that is held on this server, which could be "o=My Company,c=US")
Whether you need a password to access the server (many servers will provide read access for an "anonymous bind" but require a password for anything else)
The typical sequence of LDAP calls you will make in an application will follow this pattern:
ldap_connect() // establish connection to server
|
ldap_bind() // anonymous or authenticated "login"
|
do something like search or update the directory
and display the results
|
ldap_close() // "logout"
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The ldap_add() function is used to add entries in the LDAP directory. The DN of the entry to be added is specified by dn. Array entry specifies the information about the entry. The values in the entries are indexed by individual attributes. In case of multiple values for an attribute, they are indexed using integers starting with 0.
Esempio 1. Complete example with authenticated bind
|
Binds to the LDAP directory with specified RDN and password. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
ldap_bind() does a bind operation on the directory. bind_rdn and bind_password are optional. If not specified, anonymous bind is attempted.
Esempio 1. Using LDAP Bind
|
Esempio 2. Using LDAP Bind Anonymously
|
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().
Returns TRUE if value matches otherwise returns FALSE. Returns -1 on error.
ldap_compare() is used to compare value of attribute to value of same attribute in LDAP directory entry specified with dn.
The following example demonstrates how to check whether or not given password matches the one defined in DN specified entry.
Esempio 1. Complete example of password check
|
Avvertimento |
ldap_compare() can NOT be used to compare BINARY values! |
Nota: This function was added in 4.0.2.
Returns a positive LDAP link identifier on success, or FALSE on error.
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.
Returns number of entries in the result or FALSE on error.
ldap_count_entries() returns the number of entries stored in the result of previous search operations. result_identifier identifies the internal ldap result.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
ldap_delete() function delete a particular entry in LDAP directory specified by dn.
ldap_dn2ufn() function is used to turn a DN, specified by dn, into a more user-friendly form, stripping off type names.
Returns string error message.
This function returns the string error message explaining the error number errno. While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.
See also ldap_errno() and ldap_error().
Return the LDAP error number of the last LDAP command for this link.
This function returns the standardized error number returned by the last LDAP command for the given link_identifier. This number can be converted into a textual error message using ldap_err2str().
Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.
Esempio 1. Generating and catching an error
|
See also ldap_err2str() and ldap_error().
Returns string error message.
This function returns the string error message explaining the error generated by the last LDAP command for the given link_identifier While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.
Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.
See also ldap_err2str() and ldap_errno().
ldap_explode_dn() function is used to split the DN returned by ldap_get_dn() and breaks it up into its component parts. Each part is known as Relative Distinguished Name, or RDN. ldap_explode_dn() returns an array of all those components. with_attrib is used to request if the RDNs are returned with only values or their attributes as well. To get RDNs with the attributes (i.e. in attribute=value format) set with_attrib to 0 and to get only values set it to 1.
Returns the first attribute in the entry on success and FALSE on error.
Similar to reading entries, attributes are also read one by one from a particular entry. ldap_first_attribute() returns the first attribute in the entry pointed by the result_entry_identifier. Remaining attributes are retrieved by calling ldap_next_attribute() successively. ber_identifier is the identifier to internal memory location pointer. It is passed by reference. The same ber_identifier is passed to the ldap_next_attribute() function, which modifies that pointer.
See also ldap_get_attributes()
Returns the result entry identifier for the first entry on success and FALSE on error.
Entries in the LDAP result are read sequentially using the ldap_first_entry() and ldap_next_entry() functions. ldap_first_entry() returns the entry identifier for first entry in the result. This entry identifier is then supplied to ldap_next_entry() routine to get successive entries from the result.
See also ldap_get_entries().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
ldap_free_result() frees up the memory allocated internally to store the result and pointed by the result_identifier. All result memory will be automatically freed when the script terminates.
Typically all the memory allocated for the ldap result gets freed at the end of the script. In case the script is making successive searches which return large result sets, ldap_free_result() could be called to keep the runtime memory usage by the script low.
Returns a complete entry information in a multi-dimensional array on success and FALSE on error.
ldap_get_attributes() function is used to simplify reading the attributes and values from an entry in the search result. The return value is a multi-dimensional array of attributes and values.
Having located a specific entry in the directory, you can find out what information is held for that entry by using this call. You would use this call for an application which "browses" directory entries and/or where you do not know the structure of the directory entries. In many applications you will be searching for a specific attribute such as an email address or a surname, and won't care what other data is held.
return_value["count"] = number of attributes in the entry
return_value[0] = first attribute
return_value[n] = nth attribute
return_value["attribute"]["count"] = number of values for attribute
return_value["attribute"][0] = first value of the attribute
return_value["attribute"][i] = (i+1)th value of the attribute
Esempio 1. Show the list of attributes held for a particular directory entry
|
See also ldap_first_attribute() and ldap_next_attribute().
Returns the DN of the result entry and FALSE on error.
ldap_get_dn() function is used to find out the DN of an entry in the result.
Returns a complete result information in a multi-dimensional array on success and FALSE on error.
ldap_get_entries() function is used to simplify reading multiple entries from the result, specified with result_identifier, and then reading the attributes and multiple values. The entire information is returned by one function call in a multi-dimensional array. The structure of the array is as follows.
The attribute index is converted to lowercase. (Attributes are case-insensitive for directory servers, but not when used as array indices.)
return_value["count"] = number of entries in the result
return_value[0] : refers to the details of first entry
return_value[i]["dn"] = DN of the ith entry in the result
return_value[i]["count"] = number of attributes in ith entry
return_value[i][j] = jth attribute in the ith entry in the result
return_value[i]["attribute"]["count"] = number of values for
attribute in ith entry
return_value[i]["attribute"][j] = jth value of attribute in ith entry
See also ldap_first_entry() and ldap_next_entry()
Sets retval to the value of the specified option. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The parameter option can be one of: LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT, LDAP_OPT_PROTOCOL_VERSION, LDAP_OPT_ERROR_NUMBER, LDAP_OPT_REFERRALS, LDAP_OPT_RESTART, LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING, LDAP_OPT_MATCHED_DN. These are described in draft-ietf-ldapext-ldap-c-api-xx.txt
Nota: This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x, and was added in PHP 4.0.4
See also ldap_set_option().
Returns an array of values for the attribute on success and FALSE on error.
ldap_get_values_len() function is used to read all the values of the attribute in the entry in the result. entry is specified by the result_entry_identifier. The number of values can be found by indexing "count" in the resultant array. Individual values are accessed by integer index in the array. The first index is 0.
This function is used exactly like ldap_get_values() except that it handles binary data and not string data.
Nota: This function was added in 4.0.
Returns an array of values for the attribute on success and FALSE on error.
ldap_get_values() function is used to read all the values of the attribute in the entry in the result. entry is specified by the result_entry_identifier. The number of values can be found by indexing "count" in the resultant array. Individual values are accessed by integer index in the array. The first index is 0.
This call needs a result_entry_identifier, so needs to be preceded by one of the ldap search calls and one of the calls to get an individual entry.
You application will either be hard coded to look for certain attributes (such as "surname" or "mail") or you will have to use the ldap_get_attributes() call to work out what attributes exist for a given entry.
LDAP allows more than one entry for an attribute, so it can, for example, store a number of email addresses for one person's directory entry all labeled with the attribute "mail"
return_value["count"] = number of values for attribute
return_value[0] = first value of attribute
return_value[i] = ith value of attribute
Esempio 1. List all values of the "mail" attribute for a directory entry
|
Returns a search result identifier or FALSE on error.
ldap_list() performs the search for a specified filter on the directory with the scope LDAP_SCOPE_ONELEVEL.
LDAP_SCOPE_ONELEVEL means that the search should only return information that is at the level immediately below the base_dn given in the call. (Equivalent to typing "ls" and getting a list of files and folders in the current working directory.)
This call takes 5 optional parameters. See ldap_search() notes.
Nota: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.
Esempio 1. Produce a list of all organizational units of an organization
|
Nota: From 4.0.5 on it's also possible to do parallel searches. See ldap_search() for details.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
This function adds attribute(s) to the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level additions are done by the ldap_add() function.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
This function removes attribute(s) from the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level deletions are done by the ldap_delete() function.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
This function replaces attribute(s) from the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level modifications are done by the ldap_modify() function.
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().
Returns the next attribute in an entry on success and FALSE on error.
ldap_next_attribute() is called to retrieve the attributes in an entry. The internal state of the pointer is maintained by the ber_identifier. It is passed by reference to the function. The first call to ldap_next_attribute() is made with the result_entry_identifier returned from ldap_first_attribute().
See also ldap_get_attributes()
Returns entry identifier for the next entry in the result whose entries are being read starting with ldap_first_entry(). If there are no more entries in the result then it returns FALSE.
ldap_next_entry() function is used to retrieve the entries stored in the result. Successive calls to the ldap_next_entry() return entries one by one till there are no more entries. The first call to ldap_next_entry() is made after the call to ldap_first_entry() with the result_entry_identifier as returned from the ldap_first_entry().
See also ldap_get_entries()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Returns a search result identifier or FALSE on error.
ldap_read() performs the search for a specified filter on the directory with the scope LDAP_SCOPE_BASE. So it is equivalent to reading an entry from the directory.
An empty filter is not allowed. If you want to retrieve absolutely all information for this entry, use a filter of "objectClass=*". If you know which entry types are used on the directory server, you might use an appropriate filter such as "objectClass=inetOrgPerson".
This call takes 5 optional parameters. See ldap_search() notes.
Nota: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.
From 4.0.5 on it's also possible to do parallel searches. See ldap_search() for details.
The entry specified by dn is renamed/moved. The new RDN is specified by newrdn and the new parent/superior entry is specified by newparent. If the parameter deleteoldrdn is TRUE the old RDN value(s) is removed, else the old RDN value(s) is retained as non-distinguished values of the entry. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: This function currently only works with LDAPv3. You may have to use ldap_set_option() prior to binding to use LDAPv3. This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x, and was added in PHP 4.0.5.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Returns a search result identifier or FALSE on error.
ldap_search() performs the search for a specified filter on the directory with the scope of LDAP_SCOPE_SUBTREE. This is equivalent to searching the entire directory. base_dn specifies the base DN for the directory.
There is an optional fourth parameter, that can be added to restrict the attributes and values returned by the server to just those required. This is much more efficient than the default action (which is to return all attributes and their associated values). The use of the fourth parameter should therefore be considered good practice.
The fourth parameter is a standard PHP string array of the required attributes, e.g. array("mail", "sn", "cn") Note that the "dn" is always returned irrespective of which attributes types are requested.
Note too that some directory server hosts will be configured to return no more than a preset number of entries. If this occurs, the server will indicate that it has only returned a partial results set. This occurs also if the sixth parameter sizelimit has been used to limit the count of fetched entries.
The fifth parameter attrsonly should be set to 1 if only attribute types are wanted. If set to 0 both attributes types and attribute values are fetched which is the default behaviour.
With the sixth parameter sizelimit it is possible to limit the count of entries fetched. Setting this to 0 means no limit. NOTE: This parameter can NOT override server-side preset sizelimit. You can set it lower though.
The seventh parameter timelimit sets the number of seconds how long is spend on the search. Setting this to 0 means no limit. NOTE: This parameter can NOT override server-side preset timelimit. You can set it lower though.
The eighth parameter deref specifies how aliases should be handled during the search. It can be one of the following:
LDAP_DEREF_NEVER - (default) aliases are never dereferenced.
LDAP_DEREF_SEARCHING - aliases should be dereferenced during the search but not when locating the base object of the search.
LDAP_DEREF_FINDING - aliases should be dereferenced when locating the base object but not during the search.
LDAP_DEREF_ALWAYS - aliases should be dereferenced always.
Nota: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.
The search filter can be simple or advanced, using boolean operators in the format described in the LDAP documentation (see the Netscape Directory SDK for full information on filters).
The example below retrieves the organizational unit, surname, given name and email address for all people in "My Company" where the surname or given name contains the substring $person. This example uses a boolean filter to tell the server to look for information in more than one attribute.
Esempio 1. LDAP search
|
From 4.0.5 on it's also possible to do parallel searches. To do this you use an array of link identifiers, rather than a single identifier, as the first argument. If you don't want the same base DN and the same filter for all the searches, you can also use an array of base DNs and/or an array of filters. Those arrays must be of the same size as the link identifier array since the first entries of the arrays are used for one search, the second entries are used for another, and so on. When doing parallel searches an array of search result identifiers is returned, except in case of error, then the entry corresponding to the search will be FALSE. This is very much like the value normally returned, except that a result identifier is always returned when a search was made. There are some rare cases where the normal search returns FALSE while the parallel search returns an identifier.
Sets the value of the specified option to be newval. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. on error.
The parameter option can be one of: LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT, LDAP_OPT_PROTOCOL_VERSION, LDAP_OPT_ERROR_NUMBER, LDAP_OPT_REFERRALS, LDAP_OPT_RESTART, LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING, LDAP_OPT_MATCHED_DN, LDAP_OPT_SERVER_CONTROLS, LDAP_OPT_CLIENT_CONTROLS. Here's a brief description, see draft-ietf-ldapext-ldap-c-api-xx.txt for details.
The options LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT, LDAP_OPT_PROTOCOL_VERSION and LDAP_OPT_ERROR_NUMBER have integer value, LDAP_OPT_REFERRALS and LDAP_OPT_RESTART have boolean value, and the options LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING and LDAP_OPT_MATCHED_DN have string value. The first example illustrates their use. The options LDAP_OPT_SERVER_CONTROLS and LDAP_OPT_CLIENT_CONTROLS require a list of controls, this means that the value must be an array of controls. A control consists of an oid identifying the control, an optional value, and an optional flag for criticality. In PHP a control is given by an array containing an element with the key oid and string value, and two optional elements. The optional elements are key value with string value and key iscritical with boolean value. iscritical defaults to FALSE if not supplied. See also the second example below.
Nota: This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x, and was added in PHP 4.0.4.
Esempio 2. Set server controls
|
See also ldap_get_option().
(PHP 4 >= 4.2.0, PHP 5)
ldap_set_rebind_proc -- Set a callback function to do re-binds on referral chasing.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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.
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:
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/.
lzf_compress() compresses data in arg parameter.
Returns compressed data or FALSE if an error occured.
See also lzf_decompress().
lzf_decompress() decompresses data from parameter arg.
Returns decompressed data or FALSE if an error occured.
See also lzf_compress().
La funzione mail() permette di inviare messaggi di posta elettronica.
Per avere disponibili le funzioni Mail, il PHP deve potere accedere all'eseguibile sendmail del sistema durante la compila. Qualora si utilizzi un'altro programma di posta, tipo qmail o postfix, occorre utlizzare il wrapper sendmail allegato al programma di posta. Il PHP cercherà sendmail in PATH e quindi in: /usr/bin:/usr/sbin:/usr/etc:/etc:/usr/ucblib:/usr/lib. Si consiglia vivamente di avere sendmail in PATH. Inoltre, l'utente che compila PHP deve avere i diritti di accesso all'eseguibile di sendmail.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Opzioni di configurazione Mail
Nome | Predefinito | Modificabile in |
---|---|---|
SMTP | "localhost" | PHP_INI_ALL |
smtp_port | "25" | PHP_INI_ALL |
sendmail_from | NULL | PHP_INI_ALL |
sendmail_path | DEFAULT_SENDMAIL_PATH | PHP_INI_SYSTEM |
Breve descrizione dei parametri di configurazione.
Usato solo sotto Windows: Nome DNS o indirizzo IP del server SMTP che PHP deve usare per spedire posta elettronica con la funzione mail().
Usato solo sotto Windows: Numero della porta del server specificato da SMTP al quale connettersi quando si inviano email usando mail(); il valore predefinito è 25. Disponibile solo a partire da PHP 4.3.0.
Quale campo "From:" devono avere i messaggi inviati da PHP sotto Windows.
Dove trovare il programma sendmail, solitamente /usr/sbin/sendmail oppure /usr/lib/sendmail. configure cerca di trovare il file e lo imposta di default, ma se non riesce a localizzarlo, lo si può impostare qui.
I sistemi che non usano sendmail devono impostare questa direttiva al wrapper che i rispettivi sistemi di posta offrono, se esistenti. Per esempio, gli utenti di Qmail possono normalmente impostarla a /var/qmail/bin/sendmail o /var/qmail/bin/qmail-inject.
qmail-inject non necessita di nessuna opzione al fine di processare correttamente la mail.
ezmlm_hash() calcola il valore hash che occorre quando si mantengono mailing list EZMLM in un database MySQL.
mail() invia automaticamente il messaggio specificato in messaggio al destinatario specificato in a. Destinatari multipli possono essere specificati mettendo una virgola tra ogni indirizzo in a. Email con allegati e tipi speciali di contenuto possono essere spedite usando questa funzione. Questo è possibile tramite la codifica MIME. Per maggiori informazioni, fare riferimento a un articolo Zend o alle Classi Mime del PEAR.
Le seguenti RFC possono essere di aiuto: RFC 1896, RFC 2045, RFC 2046, RFC 2047, RFC 2048 e RFC 2049.
mail() restituisce TRUE se la mail è stata accettata per la spedizione con successo, altrimenti restituisce FALSE.
Avvertimento |
L'implementazione Windows della funzione mail() differisce sotto molti aspetti dall'implementazione Unix. Primo, non usa una un programma in locale per comporre i messaggi, ma opera soltanto direttamente sui socket, il che significa che deve essere presente in ascolto un MTA su un socket di rete (che può essere su localhost o su una macchina remota). Secondo, gli header custom quali From:, Cc:, Bcc: e Date: non vengono interpretati subito dal MTA, ma ne viene fatto prima il parsing da parte di PHP. PHP < 4.3 supportava solo gli header Cc: (ed era case-sensitive). PHP >= 4.3 supporta tutti gli header e non è più case-sensitive. |
Se viene passata come parametro una quarta stringa, questa stringa viene inserita alla fine dell'intestazione (header). Ciò viene tipicamente usato per aggiungere intestazioni supplementari. Intestazioni multiple supplementari sono separate da un carattere di "a capo" (sia newline che carriage return).
Nota: È necessario usare \r\n per separare le intestazioni, alcuni mail transfer agent sotto Unix potrebbero funzionare anche solo con un singolo newline (\n).
Con il parametro parametri_addizionali è possibile impostare un parametro addizionale a linea di comando per il programma configurato per inviare mail usando sendmail_path. Per esempio si può impostare il corretto valore per envelope sender di sendmail con l'opzione -f di sendmail. Potrebbe essere necessario aggiungere l'utente che ha in esecuzione il server web alla configurazione di sendmail per prevenire l'aggiunta dell'intestazione 'X-Warning' quando si imposta envelope sender in questo modo.
Nota: Questo quinto parametro è stato aggiunto in PHP 4.0.5. A partire da PHP 4.2.3, questo parametro è disabilitato in modalità safe_mode, se si cerca di usarlo comunque, la funzione mail() darà un messaggio di errore e restituirà FALSE.
È possibile costruire messaggi complessi utilizzando la tecnica di concatenazione delle stringhe.
Esempio 4. Invio di mail complessa.
|
Nota: Assicurarsi di non avere nessun carattere di newline nei parametri a o oggetto, o la mail non verrà spedita correttamente.
Nota: Il parametro a non può essere un indirizzo nella forma "Qualcosa <qualcuno@example.com>". Il comando di mail non sarebbe in grado di effettuare correttamente il parsing mentre dialoga con il MTA (in particolare sotto Windows).
Vedere anche imap_mail().
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
This extension has been moved from PHP as of PHP 4.2.0 and now mailparse lives in PECL.
(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-ableAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only)
mailparse_msg_extract_part_file -- Extracts/decodes a message section, decoding the transfer encodingAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(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"Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only)
mailparse_msg_get_part_data -- Returns an associative array of info about the messageAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only)
mailparse_msg_get_structure -- Returns an array of mime section names in the supplied messageAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only)
mailparse_msg_parse_file -- Parse file and return a resource representing the structureAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only)
mailparse_rfc822_parse_addresses -- Parse addresses and returns a hash containing that dataAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only)
mailparse_stream_encode -- Streams data from source file pointer, apply encoding and write to destfpAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(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 informationAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Queste funzioni matematiche operano esclusivamente nel range dei tipi di dato integer e float del computer. (questo corrisponde attualmente ai tipi di dati long e double del C) Se si ha necessità di lavorare con numeri più grandi, fare riferimento alle funzioni matematiche a precisione arbitraria.
Vedere anche il manuale alle pagine operatori aritmetici.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Le costanti qui elencate sono sempre disponibili in quanto parte del core di PHP.
Tabella 1. Costanti Matematiche
Costante | Valore | Descrizione |
---|---|---|
M_PI | 3.14159265358979323846 | Pi |
M_E | 2.7182818284590452354 | e |
M_LOG2E | 1.4426950408889634074 | log_2 e |
M_LOG10E | 0.43429448190325182765 | log_10 e |
M_LN2 | 0.69314718055994530942 | log_e 2 |
M_LN10 | 2.30258509299404568402 | log_e 10 |
M_PI_2 | 1.57079632679489661923 | pi/2 |
M_PI_4 | 0.78539816339744830962 | pi/4 |
M_1_PI | 0.31830988618379067154 | 1/pi |
M_2_PI | 0.63661977236758134308 | 2/pi |
M_SQRTPI | 1.77245385090551602729 | sqrt(pi) [4.0.2] |
M_2_SQRTPI | 1.12837916709551257390 | 2/sqrt(pi) |
M_SQRT2 | 1.41421356237309504880 | sqrt(2) |
M_SQRT3 | 1.73205080756887729352 | sqrt(3) [4.0.2] |
M_SQRT1_2 | 0.70710678118654752440 | 1/sqrt(2) |
M_LNPI | 1.14472988584940017414 | log_e(pi) [4.0.2] |
M_EULER | 0.57721566490153286061 | Costante di Eulero [4.0.2] |
Restituisce il valore assoluto di un numero. Se l'argomento della funzione è di tipo float, il valore restituito è float, altrimenti restituisce un integer (perché float di solito ha un range di valori più grande di integer).
Restituisce l'arco coseno di arg in radianti. La funzione acos() è complementare alla funzione cos(), ovvero che a==cos(acos(a)) per ciascun valore di a nel range di acos().
Restituisce l'inverso del coseno iperbolico di arg, cioè il valore il cui coseno iperbolico vale arg.
Nota: Questa funzione non è implementata su piattaforme Windows
Restituisce l'arco seno di arg in radianti. La funzione asin() è complementare alla funzione sin(), ovvero che a==sin(asin(a)) per ciascun valore di a nel range di asin().
Restituisce l'inverso del seno iperbolico di arg, cioè il valore il cui seno iperbolico vale arg
Nota: Questa funzione non è implementata su piattaforme Windows
Questa funzione calcola l'arco tangente delle due variabili x e y. È simile al calcolo dell'arco tangente di y / x, eccetto per il fatto che viene tenuto in considearazione il segno di entrambi gli argomenti per determinare il quadrante del risultato.
La funzione restituisce il risultato in radianti, compreso fra -PI e PI (inclusi).
Restituisce l'arco tangente di arg in radianti. La funzione è complementare a tan(), ovvero a==tan(atan(a)) per ciascun valore di a nel range di atan()
Restituisce l'inverso della tangente iperbolica di arg, cioè il valore la cui tangente iperbolica vale arg.
Nota: Questa funzione non è implementata su piattaforme Windows
Restituisce una stringa contenente numero rappresentata in base base_di_arrivo. La base in cui numero è dato è specificata da base_di_partenza. Entrambe base_di_partenza e base_di_arrivo devono essere comprese fra 2 e 36, inclusi. Cifre in numeri con una base maggiore di 10 saranno rappresentati con le lettere a-z, con a significante 10, b significante 11 e z significante 35.
Restituisce il decimale equivalente al numero binario rappresentato dall'argomento stringa_binaria.
bindec() converte un binario in integer. Il più grande numero che può essere convertito è 31 volte la cifra 1 oppure 2147483647 espresso in formato decimale.
Vedere anche decbin(), octdec(), hexdec() e base_convert().
Restituisce il primo intero più grande di numero, se necessario. Il valore restituito da ceil() è ancora di tipo float, poiché la gamma di valori del tipo float è solitamente più grande di quella del tipo integer.
Restituisce il coseno di arg. Il parametro arg deve essere espresso in radianti.
Restituisce il coseno iperbolico di arg, definito come (exp(arg) + exp(-arg))/2.
Restituisce una stringa contenente una rappresentazione binaria di un dato argomento numero. Il più grande numero che può essere convertito è 4294967295 in decimale, risultante in una stringa composta da 32 volte la cifra 1.
Vedere anche bindec(), decoct(), dechex() e base_convert().
Restituisce una stringa contenente una rappresentazione esadecimale di un dato argomento numero. Il più grande numero che puù essere convertito è 2147483647 in decimale risultante in "7fffffff".
Vedere anche hexdec(), decbin(), decoct() e base_convert().
Restituisce una stringa contenente una rappresentazione in ottale di un dato argomento numero. Il più grande numero che può essere convertito è 2147483647 in decimale risultante in "17777777777". Vedere anche octdec().
Vedere anche octdec(), decbin(), dechex() e base_convert().
(PHP 3>= 3.0.4, PHP 4 , PHP 5)
deg2rad -- Converte il numero dato in gradi nell'equivalente espresso in radiantiQuesta funzione converte numero da gradi al valore equivalente espresso in radianti.
Vedere anche rad2deg().
Restituisce e elevato alla potenza di arg.
Nota: 'e' è la base del sistema dei logaritmi dei numeri naturali, e vale 2.718282.
(PHP 4 >= 4.1.0, PHP 5)
expm1 -- Restituisce exp(numero) - 1, computato in maniera tale da essere accurato anche se il valore del numero è vicino a zeroAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Questa funzione non è implementata su piattaforme Windows
Restituisce il primo intero più piccolo di numero, se necessario. Il valore restituito da floor() è ancora di tipo float, poiché la gamma di valori del tipo float è solitamente più grande di quella del tipo integer.
(PHP 4 >= 4.2.0, PHP 5)
fmod -- Returns the floating point remainder (modulo) of the division of the argumentsReturns the floating point remainder of dividing the dividend (x) by the divisor (y). The reminder (r) is defined as: x = i * y + r, for some integer i. If y is non-zero, r has the same sign as x and a magnitude less than the magnitude of y.
Restituisce il valore massimo che può essere restituito da una chiamata alla funzione rand().
Vedere anche rand(), srand() e mt_getrandmax().
Restituisce l'equivalente decimale di un numero esadecimale rappresentato dall'argomento stringa_esadecimale. hexdec() converte una stringa esadecimale in un numero decimale. Il più grande numero che può essere convertito è 7fffffff o 2147483647 espresso in decimale.
hexdec() 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.
Vedere anche dechex(), bindec(), octdec() e base_convert().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce TRUE se val è un numero finito valido all'interno del range dei float, come definito da PHP su questa piattaforma.
Vedere anche is_infinite() e is_nan().
Restituisce TRUE se val è infinito (positivo o negativo), come il risultato di log(0) o ogni altro valore troppo grande per essere contenuto nel range dei float di una determinata piattaforma.
Vedere anche is_finite() e is_nan().
Restituisce TRUE se val 'non è un numero', come il risultato di acos(1.01).
Vedere anche is_finite() e is_infinite().
lcg_value() restituisce uno pseudo numero casuale nell'intervallo (0, 1). La funzione combina due GC con periodo di 2^31 - 85 e 2^31 - 249. Il periodo di questa funzione è uguale al prodotto dei due primi.
(PHP 4 >= 4.1.0, PHP 5)
log1p -- Restituisce log(1 + numero), computato in maniera tale da essere accurato anche se il valore del numero è vicino a zeroAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Questa funzione non è implementata su piattaforme Windows
Se si specifica il parametro opzionale base, la funzione log() restituisce logbase arg, altrimenti log() il logaritmo naturale di arg.
Nota: Il parametro base è disponibile dalla versione 4.3.0 di PHP.
Si può comunque calcolare il logaritmo in base b di un numero n, usando la formula matematica: logb(n) = log(n)/log(b), dove log è il logaritmo neperiano (o naturale).
Vedere anche exp().
max() restituisce il numericamente più grande dei valori dati come parametro.
Se il primo ed unico parametro è un array, max() restituisce il massimo dei valori di tale array. Se il primo parametro è un integer, string o double, si ha bisogno almeno di due parametri e max() restituisce il maggiore di tali valori. Si può confrontare un numero illimitato di valori.
Nota: Le stringhe non numeriche saranno considerate dal PHP come 0, ma verrà restituita la stringa se questa è il più alto valore numerico. Se vi sono più argomenti considerati come 0, la funzione max() restituirà il primo (il valore più a sinistra).
Esempio 1. Esempio di max()
|
min() restituisce il numericamente più piccolo dei valori dati come parametro.
Se il primo ed unico pareametro è un array, la funzione min() restituisce il valore più basso nell'array. Se il primo parametro è un intero, una stringa, o un float, occorrono almeno due parametri e min() restituisce il minore tra questi. Si può confrontare un numero illimitato di valori.
Nota: Le stringhe non numeriche saranno considerate dal PHP come 0, ma verrà restituita la stringa se questa è il più basso valore numerico. Se vi sono più argomenti considerati come 0, la funzione min() restituirà il primo (il valore più a sinistra).
Esempio 1. Esempio di uso di min()
|
Restituisce il massimo valore che può essere restituito da una chiamata alla funzione mt_rand().
Vedere anche mt_rand(), mt_srand() e getrandmax().
Molti generatori di numeri casuali di vecchie libc hanno caratteristiche dubbie o sconosciute e sono lenti. Di default, PHP usa il generatore di numeri casuali libc con la funzione rand(). La funzione mt_rand() è un sostituto per questa. Usa un generatore di numeri casuali con caratteristiche conosciute, il Mersenne Twister, il quale 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).
Nota: Come in PHP 4.2.0, non vi è necessità di inizializzare il generatore di numeri casuali con srand() oppure con mt_srand() poichè viene eseguito in modo automatico.
Nota: Nelle versioni precedenti la 3.0.7 il significato di max era range. Per ottenere lo stesso risultato in queste vecchie versioni un breve esempio dovrebbe essere il seguente: mt_rand (5, 11), si otterrà un numero casuale compreso fra 5 e 15.
Vedere anche mt_srand(), mt_getrandmax() e rand().
Inizializza il generatore di numeri casuali con il parametro seme. A partire dalla versione 4.2.0 di PHP il parametro seme è diventato opzionale, e, per default, viene impostato ad un valore random.
<?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().
Restituisce l'equivalente decimale del numero ottale rappresentato dall'argomento stringa_ottale. OctDec converte una stringa ottale in un numero decimale. Il più grande numero che può essere convertito è 17777777777 o 2147483647 in decimale.
Vedere anche decoct(), bindec(), hexdec() e base_convert().
Restituisce una appossimazione di pi. Il valore restituito è un float e ha precisione secondo la direttiva precision del file php.ini, che ha come valore predefinito 14. Inoltre, si può usare la costante M_PI che permette di ottenere risultati identici all'uso di pi().
Restituisce base elevato alla potenza di esp. Se possibile, questa funzione restituisce un integer.
Se la potenza non può essere computata, viene generato un errore, e pow() restituirà FALSE.
Avvertimento |
Nel PHP 4.0.6 e precedenti, pow() restituiva sempre un float e non generava alcun errore. |
(PHP 3>= 3.0.4, PHP 4 , PHP 5)
rad2deg -- Converte un numero in radianti nell'equivalente numero in gradiQuesta funzione converte numero da radianti a gradi.
Vedere anche deg2rad().
Se chiamata senza i parametri opzionali min, max, rand() restituisce un valore pseudo casuale compreso fra 0 e RAND_MAX. Se ad esempio si desidera un numero casuale compreso fra 5 e 15 (inclusi) usare rand (5, 15).
Nota: Su alcune piattaforme (come Windows) RAND_MAX vale soltanto 32768. Se si desidera un range più ampio si valuti l'utilizzo di mt_rand()
Nota: Come in PHP 4.2.0, non vi è necessità di inizializzare il generatore di numeri casuali con srand() oppure con mt_srand() poichè viene eseguito in modo automatico.
Nota: Nelle versioni precedenti la 3.0.7 il significato di max era range. Per ottenere lo stesso risultato in queste vecchie versioni un breve esempio dovrebbe essere il seguente: rand (5, 11), si otterrà un numero casuale compreso fra 5 e 15.
Vedere anche srand(), getrandmax() e mt_rand().
Restituisce il valore arrotondato di val con la precisione specificata (numero di cifre dopo il punto decimale). precisione può anche essere negativa o zero (predefinito).
Nota: Il PHP non maneggia correttamente stringhe quali "12,300.2" in maniera predefinita. Fare riferimento a conversione da stringhe.
Nota: Il parametro precisione è disponibile solo nel PHP 4.
Vedere anche ceil(), floor() e number_format().
La funzione sin() restituisce il seno di arg. Il parametro arg viene espresso in radianti.
Restituisce il seno iperbolico di arg, definito come (exp(arg) - exp(-arg))/2.
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().
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().
La funzione tan() restituisce la tangente del parametro arg. Il parametro arg deve essere espresso in radianti.
While there are many languages in which every necessary character can be represented by a one-to-one mapping to a 8-bit value, there are also several languages which require so many characters for written communication that cannot be contained within the range a mere byte can code. Multibyte character encoding schemes were developed to express that many (more than 256) characters in the regular bytewise coding system.
When you manipulate (trim, split, splice, etc.) strings encoded in a multibyte encoding, you need to use special functions since two or more consecutive bytes may represent a single character in such encoding schemes. Otherwise, if you apply a non-multibyte-aware string function to the string, it probably fails to detect the beginning or ending of the multibyte character and ends up with a corrupted garbage string that most likely loses its original meaning.
mbstring provides these multibyte specific string functions that help you deal with multibyte encodings in PHP, which is basically supposed to be used with single byte encodings. In addition to that, mbstring handles character encoding conversion between the possible encoding pairs.
mbstring is also designed to handle Unicode-based encodings such as UTF-8 and UCS-2 and many single-byte encodings for convenience (listed below), whereas mbstring was originally developed for use in Japanese web pages.
Encodings of the following types are safely used with PHP.
A singlebyte encoding,
which has ASCII-compatible (ISO646 compatible) mappings for the characters in range of 00h to 7fh.
A multibyte encoding,
which has ASCII-compatible mappings for the characters in range of 00h to 7fh.
which don't use ISO2022 escape sequences.
which don't use a value from 00h to 7fh in any of the compounded bytes that represents a single character.
These are examples of character encodings that are unlikely to work with PHP.
Although PHP scripts written in any of those encodings might not work, especially in the case where encoded strings appear as identifiers or literals in the script, you can almost avoid using these encodings by setting up the mbstring's transparent encoding filter function for incoming HTTP queries.
Nota: It's highly discouraged to use SJIS, BIG5, CP936, CP949 and GB18030 for the internal encoding unless you are familiar with the parser, the scanner and the character encoding.
Nota: If you have some database connected with PHP, it is recommended that you use the same character encoding for both database and the internal encoding for ease of use and better performance.
If you are using PostgreSQL, the character encoding used in the database and the one used in the PHP may differ as it supports automatic character set conversion between the backend and the frontend.
mbstring is a non-default extension. This means it is not enabled by default. You must explicitly enable the module with the configure option. See the Install section for details.
The following configure options are related to the mbstring module.
--enable-mbstring=LANG: Enable mbstring functions. This option is required to use mbstring functions.
As of PHP 4.3.0, mbstring extension provides enhanced support for Simplified Chinese, Traditional Chinese, Korean, and Russian in addition to Japanese. To enable that feature, you will have to supply either one of the following options to the LANG parameter; --enable-mbstring=cn for Simplified Chinese support, --enable-mbstring=tw for Traditional Chinese support, --enable-mbstring=kr for Korean support, --enable-mbstring=ru for Russian support, and --enable-mbstring=ja for Japanese support.
Also --enable-mbstring=all is convenient for you to enable all the supported languages listed above.
Nota: Japanese language support is also enabled by --enable-mbstring without any options for the sake of backwards compatibility.
--enable-mbstr-enc-trans : Enable HTTP input character encoding conversion using mbstring conversion engine. If this feature is enabled, HTTP input character encoding may be converted to mbstring.internal_encoding automatically.
Nota: As of PHP 4.3.0, the option --enable-mbstr-enc-trans was eliminated and replaced with the runtime setting mbstring.encoding_translation. HTTP input character encoding conversion is enabled when this is set to On (the default is Off).
--enable-mbregex: Enable regular expression functions with multibyte character support.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. mbstring configuration options
Name | Default | Changeable |
---|---|---|
mbstring.language | "neutral" | PHP_INI_SYSTEM | PHP_INI_PERDIR |
mbstring.detect_order | NULL | PHP_INI_ALL |
mbstring.http_input | "pass" | PHP_INI_ALL |
mbstring.http_output | "pass" | PHP_INI_ALL |
mbstring.internal_encoding | NULL | PHP_INI_ALL |
mbstring.script_encoding | NULL | PHP_INI_ALL |
mbstring.substitute_character | NULL | PHP_INI_ALL |
mbstring.func_overload | "0" | PHP_INI_SYSTEM | PHP_INI_PERDIR |
mbstring.encoding_translation | "0" | PHP_INI_SYSTEM | PHP_INI_PERDIR |
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
|
Esempio 2. php.ini setting for EUC-JP users
|
Esempio 3. php.ini setting for SJIS users
|
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
HTTP input/output character encoding conversion may convert binary data also. Users are supposed to control character encoding conversion if binary data is used for HTTP input/output.
Nota: In PHP 4.3.2 or earlier versions, there was a limitation in this functionality that mbstring does not perform character encoding conversion in POST data if the enctype attribute in the form element is set to multipart/form-data. So you have to convert the incoming data by yourself in this case if necessary.
Beginning with PHP 4.3.3, if enctype for HTML form is set to multipart/form-data and mbstring.encoding_translation is set to On in php.ini the POST'ed variables and the names of uploaded files will be converted to the internal character encoding as well. However, the conversion isn't applied to the query keys.
HTTP Input
There is no way to control HTTP input character conversion from PHP script. To disable HTTP input character conversion, it has to be done in php.ini.
When using PHP as an Apache module, it is possible to override those settings in each Virtual Host directive in httpd.conf or per directory with .htaccess. Refer to the Configuration section and Apache Manual for details.
HTTP Output
There are several ways to enable output character encoding conversion. One is using php.ini, another is using ob_start() with mb_output_handler() as ob_start callback function.
Nota: PHP3-i18n users should note that mbstring's output conversion differs from PHP3-i18n. Character encoding is converted using output buffer.
Currently the following character encodings are supported by the mbstring module. Any of those Character encodings can be specified in the encoding parameter of mbstring functions.
The following character encoding is supported in this PHP extension:
UCS-4
UCS-4BE
UCS-4LE
UCS-2
UCS-2BE
UCS-2LE
UTF-32
UTF-32BE
UTF-32LE
UTF-16
UTF-16BE
UTF-16LE
UTF-7
UTF7-IMAP
UTF-8
ASCII
EUC-JP
SJIS
eucJP-win
SJIS-win
ISO-2022-JP
JIS
ISO-8859-1
ISO-8859-2
ISO-8859-3
ISO-8859-4
ISO-8859-5
ISO-8859-6
ISO-8859-7
ISO-8859-8
ISO-8859-9
ISO-8859-10
ISO-8859-13
ISO-8859-14
ISO-8859-15
byte2be
byte2le
byte4be
byte4le
BASE64
HTML-ENTITIES
7bit
8bit
EUC-CN
CP936
HZ
EUC-TW
CP950
BIG-5
EUC-KR
UHC (CP949)
ISO-2022-KR
Windows-1251 (CP1251)
Windows-1252 (CP1252)
CP866 (IBM866)
KOI8-R
php.ini entry, which accepts encoding name, accepts "auto" and "pass" also. mbstring functions, which accepts encoding name, and accepts "auto".
If "pass" is set, no character encoding conversion is performed.
If "auto" is set, it is expanded to the list of encodings defined per the NLS. For instance, if the NLS is set to Japanese, the value is assumed to be "ASCII,JIS,UTF-8,EUC-JP,SJIS".
See also mb_detect_order()
You might often find it difficult to get an existing PHP application work in a given multibyte environment. That's mostly because lots of PHP applications out there are written with the standard string functions such as substr(), which are known to not properly handle multibyte-encoded strings.
mbstring supports 'function overloading' feature which enables you to add multibyte awareness to such an application without code modification by overloading multibyte counterparts on the standard string functions. For example, mb_substr() is called instead of substr() if function overloading is enabled. This feature makes it easy to port applications that only support single-byte encodings to a multibyte environment in many cases.
To use the function overloading, set mbstring.func_overload in php.ini to a positive value that represents a combination of bitmasks specifying the categories of functions to be overloaded. It should be set to 1 to overload the mail() function. 2 for string functions, 4 for regular expression functions. For example, if is set for 7, mail, strings and regular expression functions should be overloaded. The list of overloaded functions are shown below.
Tabella 2. Functions to be overloaded
value of mbstring.func_overload | original function | overloaded function |
---|---|---|
1 | mail() | mb_send_mail() |
2 | strlen() | mb_strlen() |
2 | strpos() | mb_strpos() |
2 | strrpos() | mb_strrpos() |
2 | substr() | mb_substr() |
2 | strtolower() | mb_strtolower() |
2 | strtoupper() | mb_strtoupper() |
2 | substr_count() | mb_substr_count() |
4 | ereg() | mb_ereg() |
4 | eregi() | mb_eregi() |
4 | ereg_replace() | mb_ereg_replace() |
4 | eregi_replace() | mb_eregi_replace() |
4 | split() | mb_split() |
Nota: It is not recommended to use the function overloading option in the per-directory context, because it's not confirmed yet to be stable enough in a production environment and may lead to undefined behaviour.
It is often said quite hard to figure out how Japanese texts are handled in the computer. This is not only because Japanese characters can only be represented by multibyte encodings, but because different encoding standards are adopted for different purposes / platforms. Moreover, not a few character set standards are used there, which are slightly different from one another. Those facts have often led developers to inevitable mess-up.
To create a working web application that would be put in the Japanese environment, it is important to use the proper character encoding and character set for the task in hand.
Storage for a character can be up to six bytes
Most of multibyte characters often appear twice as wide as a single-byte character on display. Those characters are called "zen-kaku" in Japanese which means "full width", and the other (narrower) characters are called "han-kaku" - means half width. However the graphical properties of the characters depend on the glyphs of the type faces used to display them or print them out.
Some character encodings use shift(escape) sequences defined in ISO2022 to switch the code map of the specific code area (00h to 7fh).
ISO-2022-JP should be used in SMTP/NNTP, and headers and entities should be reencoded as per RFC requirements. Although those are not requisites, it's still a good idea because several popular user agents cannot recognize any other encoding methods.
Webpages created for mobile phone services such as i-mode, Vodafone live!, or EZweb are supposed to use Shift_JIS.
Multibyte character encoding schemes and the related issues are very complicated. There should be too few space to cover in sufficient details. Please refer to the following URLs and other resources for further readings.
Unicode materials
Japanese/Korean/Chinese character information
Summaries of supported encodings
Name in the IANA character set registry: ISO-10646-UCS-4
Underlying character set: ISO 10646
Description: The Universal Character Set with 31-bit code space, standardized as UCS-4 by ISO/IEC 10646. It is kept synchronized with the latest version of the Unicode code map.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry: ISO-10646-UCS-4
Underlying character set: UCS-4
Description: See above.
Additional note: In contrast to UCS-4, strings are always assumed to be in big endian form.
Name in the IANA character set registry: ISO-10646-UCS-4
Underlying character set: UCS-4
Description: See above.
Additional note: In contrast to UCS-4, strings are always assumed to be in little endian form.
Name in the IANA character set registry: ISO-10646-UCS-2
Underlying character set: UCS-2
Description: The Universal Character Set with 16-bit code space, standardized as UCS-2 by ISO/IEC 10646. It is kept synchronized with the latest version of the unicode code map.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry: ISO-10646-UCS-2
Underlying character set: UCS-2
Description: See above.
Additional note: In contrast to UCS-2, strings are always assumed to be in big endian form.
Name in the IANA character set registry: ISO-10646-UCS-2
Underlying character set: UCS-2
Description: See above.
Additional note: In contrast to UCS-2, strings are always assumed to be in little endian form.
Name in the IANA character set registry: UTF-32
Underlying character set: Unicode
Description: Unicode Transformation Format of 32-bit unit width, whose encoding space refers to the Unicode's codeset standard. This encoding scheme wasn't identical to UCS-4 because the code space of Unicode were limited to a 21-bit value.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry: UTF-32BE
Underlying character set: Unicode
Description: See above
Additional note: In contrast to UTF-32, strings are always assumed to be in big endian form.
Name in the IANA character set registry: UTF-32LE
Underlying character set: Unicode
Description: See above
Additional note: In contrast to UTF-32, strings are always assumed to be in little endian form.
Name in the IANA character set registry: UTF-16
Underlying character set: Unicode
Description: Unicode Transformation Format of 16-bit unit width. It's worth a note that UTF-16 is no longer the same specification as UCS-2 because the surrogate mechanism has been introduced since Unicode 2.0 and UTF-16 now refers to a 21-bit code space.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry: UTF-16BE
Underlying character set: Unicode
Description: See above.
Additional note: In contrast to UTF-16, strings are always assumed to be in big endian form.
Name in the IANA character set registry: UTF-16BE
Underlying character set: Unicode
Description: See above.
Additional note: In contrast to UTF-16, strings are always assumed to be in big endian form.
Name in the IANA character set registry: UTF-8
Underlying character set: Unicode / UCS
Description: Unicode Transformation Format of 8-bit unit width.
Additional note: none
Name in the IANA character set registry: UTF-7
Underlying character set: Unicode
Description: A mail-safe transformation format of Unicode, specified in RFC2152.
Additional note: none
Name in the IANA character set registry: (none)
Underlying character set: Unicode
Description: A variant of UTF-7 which is specialized for use in the IMAP protocol.
Additional note: none
Name in the IANA character set registry: US-ASCII (preferred MIME name) / iso-ir-6 / ANSI_X3.4-1986 / ISO_646.irv:1991 / ASCII / ISO646-US / us / IBM367 / CP367 / csASCII
Underlying character set: ASCII / ISO 646
Description: American Standard Code for Information Interchange is a commonly-used 7-bit encoding. Also standardized as an international standard, ISO 646.
Additional note: (none)
Name in the IANA character set registry: EUC-JP (preferred MIME name) / Extended_UNIX_Code_Packed_Format_for_Japanese / csEUCPkdFmtJapanese
Underlying character set: Compound of US-ASCII / JIS X0201:1997 (hankaku kana part) / JIS X0208:1990 / JIS X0212:1990
Description: As you see the name is derived from an abbreviation of Extended UNIX Code Packed Format for Japanese, this encoding is mostly used on UNIX or alike platforms. The original encoding scheme, Extended UNIX Code, is designed on the basis of ISO 2022.
Additional note: The character set referred to by EUC-JP is different to IBM932 / CP932, which are used by OS/2® and Microsoft® Windows®. For information interchange with those platforms, use EUCJP-WIN instead.
Name in the IANA character set registry: Shift_JIS (preferred MIME name) / MS_Kanji / csShift_JIS
Underlying character set: Compound of JIS X0201:1997 / JIS X0208:1997
Description: Shift_JIS was developed in early 80's, at the time personal Japanese word processors were brought into the market, in order to maintain compatiblities with the legacy encoding scheme JIS X 0201:1976. According to the IANA definition the codeset of Shift_JIS is slightly different to IBM932 / CP932. However, the names "SJIS" / "Shift_JIS" are often wrongly used to refer to these codesets.
Additional note: For the CP932 codemap, use SJIS-WIN instead.
Name in the IANA character set registry: (none)
Underlying character set: Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions
Description: While this "encoding" uses the same encoding scheme as EUC-JP, the underlying character set is different. That is, some code points map to different characters than EUC-JP.
Additional note: none
Name in the IANA character set registry: Windows-31J / csWindows31J
Underlying character set: Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions
Description: While this "encoding" uses the same encoding scheme as Shift_JIS, the underlying character set is different. That means some code points map to different characters than Shift_JIS.
Additional note: (none)
Name in the IANA character set registry: ISO-2022-JP (preferred MIME name) / csISO2022JP
Underlying character set: US-ASCII / JIS X0201:1976 / JIS X0208:1978 / JIS X0208:1983
Description: RFC1468
Additional note: (none)
Name in the IANA character set registry: JIS
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-1
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-2
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-3
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-4
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-5
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-6
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-7
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-8
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-9
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-10
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-13
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-14
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-15
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: byte2be
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: byte2le
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: byte4be
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: byte4le
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: BASE64
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: HTML-ENTITIES
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: 7bit
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: 8bit
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: EUC-CN
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: CP936
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: HZ
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: EUC-TW
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: CP950
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: BIG-5
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: EUC-KR
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: UHC (CP949)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-2022-KR
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: Windows-1251 (CP1251)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: Windows-1252 (CP1252)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: CP866 (IBM866)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: KOI8-R
Underlying character set:
Description:
Additional note:
mb_convert_case() returns case folded version of string converted in the way specified by mode.
mode can be one of MB_CASE_UPPER, MB_CASE_LOWER or MB_CASE_TITLE.
encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.
The return value is str with the appropriate case folding applied.
By contrast to the standard case folding functions such as strtolower() and strtoupper(), case folding is performed on the basis of the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as A-umlaut (Ä).
For more information about the Unicode properties, please see http://www.unicode.org/unicode/reports/tr21/.
Esempio 1. mb_convert_case() example
|
See also mb_strtolower(), mb_strtoupper(), strtolower() and strtoupper().
mb_convert_encoding() converts character encoding of string str from from-encoding to to-encoding.
str : String to be converted.
from-encoding is specified by character code name before conversion. it can be array or string - comma separated enumerated list. If it is not specified, the internal encoding will be used.
Esempio 1. mb_convert_encoding() example
|
See also mb_detect_order().
(PHP 4 >= 4.0.6, PHP 5)
mb_convert_kana -- Convert "kana" one from another ("zen-kaku", "han-kaku" and more)mb_convert_kana() performs "han-kaku" - "zen-kaku" conversion for string str. It returns converted string. This function is only useful for Japanese.
option is conversion option. Default value is "KV".
encoding is character encoding. If it is omitted, internal character encoding is used.
Specify with combination of following options. Default value is KV.
Tabella 1. Applicable Conversion Options
Option | Meaning |
---|---|
r | Convert "zen-kaku" alphabets to "han-kaku" |
R | Convert "han-kaku" alphabets to "zen-kaku" |
n | Convert "zen-kaku" numbers to "han-kaku" |
N | Convert "han-kaku" numbers to "zen-kaku" |
a | Convert "zen-kaku" alphabets and numbers to "han-kaku" |
A | Convert "han-kaku" alphabets and numbers to "zen-kaku" (Characters included in "a", "A" options are U+0021 - U+007E excluding U+0022, U+0027, U+005C, U+007E) |
s | Convert "zen-kaku" space to "han-kaku" (U+3000 -> U+0020) |
S | Convert "han-kaku" space to "zen-kaku" (U+0020 -> U+3000) |
k | Convert "zen-kaku kata-kana" to "han-kaku kata-kana" |
K | Convert "han-kaku kata-kana" to "zen-kaku kata-kana" |
h | Convert "zen-kaku hira-gana" to "han-kaku kata-kana" |
H | Convert "han-kaku kata-kana" to "zen-kaku hira-gana" |
c | Convert "zen-kaku kata-kana" to "zen-kaku hira-gana" |
C | Convert "zen-kaku hira-gana" to "zen-kaku kata-kana" |
V | Collapse voiced sound notation and convert them into a character. Use with "K","H" |
mb_convert_variables() convert character encoding of variables vars in encoding from-encoding to encoding to-encoding. It returns character encoding before conversion for success, FALSE for failure.
mb_convert_variables() join strings in Array or Object to detect encoding, since encoding detection tends to fail for short strings. Therefore, it is impossible to mix encoding in single array or object.
It from-encoding is specified by array or comma separated string, it tries to detect encoding from from-coding. When encoding is omitted, detect_order is used.
vars (3rd and larger) is reference to variable to be converted. String, Array and Object are accepted. mb_convert_variables() assumes all parameters have the same encoding.
mb_decode_mimeheader() decodes encoded-word string str in MIME header.
It returns decoded string in internal character encoding.
See also mb_encode_mimeheader().
Convert numeric string reference of string str in specified block to character. It returns converted string.
convmap is array to specifies code area to convert.
encoding is character encoding. If it is omitted, internal character encoding is used.
Esempio 1. convmap example
|
See also mb_encode_numericentity().
mb_detect_encoding() detects character encoding in string str. It returns detected character encoding.
encoding-list is list of character encoding. Encoding order may be specified by array or comma separated list string.
If encoding_list is omitted, detect_order is used.
Esempio 1. mb_detect_encoding() example
|
See also mb_detect_order().
mb_detect_order() sets automatic character encoding detection order to encoding-list. It returns TRUE for success, FALSE for failure.
encoding-list is array or comma separated list of character encoding. ("auto" is expanded to "ASCII, JIS, UTF-8, EUC-JP, SJIS")
If encoding-list is omitted, it returns current character encoding detection order as array.
This setting affects mb_detect_encoding() and mb_send_mail().
Nota: mbstring currently implements following encoding detection filters. If there is an invalid byte sequence for following encoding, encoding detection will fail.
Nota: UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP
For ISO-8859-*, mbstring always detects as ISO-8859-*.
For UTF-16, UTF-32, UCS2 and UCS4, encoding detection will fail always.
Esempio 2. mb_detect_order() examples
|
See also mb_internal_encoding(), mb_http_input(), mb_http_output() and mb_send_mail().
mb_encode_mimeheader() encodes a given string str by the MIME header encoding scheme. Returns a converted version of the string represented in ASCII.
charset specifies the name of the character set in which str is represented in. The default value is determined by the current NLS setting (mbstring.language).
transfer-encoding specifies the scheme of MIME encoding. It should be either "B" (Base64) or "Q" (Quoted-Printable). Falls back to "B" if not given.
linefeed specifies the EOL (end-of-line) marker with which mb_encode_mime_header() performs line-folding (a RFC term, the act of breaking a line longer than a certain length into multiple lines. The length is currently hard-coded to 74 characters). Falls back to "\r\n" (CRLF) if not given.
Nota: This function isn't designed to break lines at higher-level contextual break points (word boundaries, etc.). This behaviour may clutter up the original string with unexpected spaces.
See also mb_decode_mimeheader().
mb_encode_numericentity() converts specified character codes in string str from HTML numeric character reference to character code. It returns converted string.
convmap is array specifies code area to convert.
encoding is character encoding.
Esempio 1. convmap example
|
Esempio 2. mb_encode_numericentity() example
|
See also mb_decode_numericentity().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
(PHP 4 >= 4.2.0)
mb_ereg_search_getregs -- Retrieve the result from the last multibyte regular expression matchAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
(PHP 4 >= 4.2.0)
mb_ereg_search_init -- Setup string and regular expression for multibyte regular expression matchAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
(PHP 4 >= 4.2.0)
mb_ereg_search_pos -- Return position and length of matched part of multibyte regular expression for predefined multibyte stringAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
(PHP 4 >= 4.2.0)
mb_ereg_search -- Multibyte regular expression match for predefined multibyte stringAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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() returns result of HTTP input character encoding detection.
type: Input string specifies input type. "G" for GET, "P" for POST, "C" for COOKIE. If type is omitted, it returns last input type processed.
Return Value: Character encoding name. If mb_http_input() does not process specified HTTP input, it returns FALSE.
See also mb_internal_encoding(), mb_http_output(), mb_detect_order().
If encoding is set, mb_http_output() sets HTTP output character encoding to encoding. Output after this function is converted to encoding. mb_http_output() returns TRUE for success and FALSE for failure.
If encoding is omitted, mb_http_output() returns current HTTP output character encoding.
See also mb_internal_encoding(), mb_http_input(), mb_detect_order().
mb_internal_encoding() sets internal character encoding to encoding If parameter is omitted, it returns current internal encoding.
encoding is used for HTTP input character encoding conversion, HTTP output character encoding conversion and default character encoding for string functions defined by mbstring module.
encoding: Character encoding name
Return Value: If encoding is set,mb_internal_encoding() returns TRUE for success, otherwise returns FALSE. If encoding is omitted, it returns current character encoding name.
See also mb_http_input(), mb_http_output() and mb_detect_order().
mb_language() sets language. If language is omitted, it returns current language as string.
language setting is used for encoding e-mail messages. Valid languages are "Japanese", "ja","English","en" and "uni" (UTF-8). mb_send_mail() uses this setting to encode e-mail.
Language and its setting is ISO-2022-JP/Base64 for Japanese, UTF-8/Base64 for uni, ISO-8859-1/quoted printable for English.
Return Value: If language is set and language is valid, it returns TRUE. Otherwise, it returns FALSE. When language is omitted, it returns language name as string. If no language is set previously, it returns FALSE.
See also mb_send_mail().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.0.6, PHP 5)
mb_output_handler -- Callback function converts character encoding in output buffermb_output_handler() is ob_start() callback function. mb_output_handler() converts characters in output buffer from internal character encoding to HTTP output character encoding.
4.1.0 or later version, this handler adds charset HTTP header when following conditions are met:
Does not set Content-Type by header()
Default MIME type begins with text/
http_output setting is other than pass
contents : Output buffer contents
status : Output buffer status
Return Value: String converted
Nota: If you want to output some binary data such as image from PHP script with PHP 4.3.0 or later, Content-Type: header must be send using header() before any binary data was send to client (e.g. header("Content-Type: image/png")). If Content-Type: header was send, output character encoding conversion will not be performed.
Note that if 'Content-Type: text/*' was send using header(), the sending data is regarded as text, encoding conversion will be performed using character encoding settings.
If you want to output some binary data such as image from PHP script with PHP 4.2.x or earlier, you must set output encoding to "pass" using mb_http_output().
See also ob_start().
mb_parse_str() parses GET/POST/COOKIE data and sets global variables. Since PHP does not provide raw POST/COOKIE data, it can only used for GET data for now. It preses URL encoded data, detects encoding, converts coding to internal encoding and set values to result array or global variables.
encoded_string: URL encoded data.
result: Array contains decoded and character encoding converted values.
Return Value: It returns TRUE for success or FALSE for failure.
See also mb_detect_order(), mb_internal_encoding().
mb_preferred_mime_name() returns MIME charset string for character encoding encoding. It returns charset string.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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() 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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() returns the portion of str specified by the start and length parameters.
mb_strcut() performs equivalent operation as mb_substr() with different method. If start position is multi-byte character's second byte or larger, it starts from first byte of multi-byte character.
It subtracts string from str that is shorter than length AND character that is not part of multi-byte string or not being middle of shift sequence.
encoding is character encoding. If it is not set, internal character encoding is used.
See also mb_substr(), mb_internal_encoding().
mb_strimwidth() truncates string str to specified width. It returns truncated string.
If trimmarker is set, trimmarker is appended to return value.
start is start position offset. Number of characters from the beginning of string. (First character is 0)
trimmarker is string that is added to the end of string when string is truncated.
encoding is character encoding. If it is omitted, internal encoding is used.
See also mb_strwidth() and mb_internal_encoding().
mb_strlen() returns number of characters in string str having character encoding encoding. A multi-byte character is counted as 1.
encoding is character encoding for str. If encoding is omitted, internal character encoding is used.
See also mb_internal_encoding(), strlen().
mb_strpos() returns the numeric position of the first occurrence of needle in the haystack string. If needle is not found, it returns FALSE.
mb_strpos() performs multi-byte safe strpos() operation based on number of characters. needle position is counted from the beginning of the haystack. First character's position is 0. Second character position is 1, and so on.
If encoding is omitted, internal character encoding is used. mb_strrpos() accepts string for needle where strrpos() accepts only character.
offset is search offset. If it is not specified, 0 is used.
encoding is character encoding name. If it is omitted, internal character encoding is used.
See also mb_strpos(), mb_internal_encoding(), strpos()
mb_strrpos() returns the numeric position of the last occurrence of needle in the haystack string. If needle is not found, it returns FALSE.
mb_strrpos() performs multi-byte safe strrpos() operation based on number of characters. needle position is counted from the beginning of haystack. First character's position is 0. Second character position is 1.
If encoding is omitted, internal encoding is assumed. mb_strrpos() accepts string for needle where strrpos() accepts only character.
encoding is character encoding. If it is not specified, internal character encoding is used.
See also mb_strpos(), mb_internal_encoding(), strrpos().
mb_strtolower() returns str with all alphabetic characters converted to lowercase.
encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.
For more information about the Unicode properties, please see http://www.unicode.org/unicode/reports/tr21/.
By contrast to strtolower(), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as A-umlaut (Ä).
See also strtolower(), mb_strtoupper() and mb_convert_case().
mb_strtoupper() returns str with all alphabetic characters converted to uppercase.
encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.
By contrast to strtoupper(), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as a-umlaut (ä).
For more information about the Unicode properties, please see http://www.unicode.org/unicode/reports/tr21/.
See also strtoupper(), mb_strtolower() and mb_convert_case().
mb_strwidth() returns width of string str.
Multi-byte character usually twice of width compare to single byte character.
Tabella 1. Characters width
Chars | Width |
---|---|
U+0000 - U+0019 | 0 |
U+0020 - U+1FFF | 1 |
U+2000 - U+FF60 | 2 |
U+FF61 - U+FF9F | 1 |
U+FFA0 - | 2 |
encoding is character encoding. If it is omitted, internal encoding is used.
See also: mb_strimwidth(), mb_internal_encoding().
mb_substitute_character() specifies substitution character when input character encoding is invalid or character code is not exist in output character encoding. Invalid characters may be substituted NULL(no output), string or integer value (Unicode character code value).
This setting affects mb_convert_encoding(), mb_convert_variables(), mb_output_handler(), and mb_send_mail().
substchar : Specify Unicode value as integer or specify as string as follows
"none" : no output
"long" : Output character code value (Example: U+3000,JIS+7E7E)
Return Value: If substchar is set, it returns TRUE for success, otherwise returns FALSE. If substchar is not set, it returns Unicode value or "none"/"long".
mb_substr_count() returns the number of times the needle substring occurs in the haystack string.
encoding specifies the encoding for needle and haystack. If omitted, internal character encoding is used.
See also substr_count(), mb_strpos(), mb_substr().
mb_substr() returns the portion of str specified by the start and length parameters.
mb_substr() performs multi-byte safe substr() operation based on number of characters. Position is counted from the beginning of str. First character's position is 0. Second character position is 1, and so on.
If encoding is omitted, internal encoding is assumed.
encoding is character encoding. If it is omitted, internal character encoding is used.
See also mb_strcut(), mb_internal_encoding().
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.
This extension requires the mcal library to be installed. Grab the latest version from http://mcal.chek.com/ and compile and install it.
After you installed the mcal library, to get these functions to work, you have to compile PHP -with-mcal[=DIR].
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
mcal_append_event() stores the global event into an MCAL calendar for the stream mcal_stream.
Returns the id of the newly inserted event.
Creates a new calendar named calendar.
mcal_date_compare() Compares the two given dates, returns <0, 0, >0 if a<b, a==b, a>b respectively.
(PHP 3>= 3.0.13, PHP 4 )
mcal_date_valid -- Returns TRUE if the given year, month, day is a valid datemcal_date_valid() Returns TRUE if the given year, month and day is a valid date, FALSE if not.
mcal_day_of_week() returns the day of the week of the given date. Possible return values range from 0 for Sunday through 6 for Saturday.
mcal_day_of_year() returns the day of the year of the given date.
mcal_days_in_month() returns the number of days in the month month, taking into account if the considered year is a leap year or not.
Deletes the calendar named calendar.
mcal_delete_event() deletes the calendar event specified by the event_id.
Returns TRUE.
(PHP 3>= 3.0.15, PHP 4 )
mcal_event_add_attribute -- Adds an attribute and a value to the streams global event structuremcal_event_add_attribute() adds an attribute to the stream's global event structure with the value given by "value".
mcal_event_init() initializes a streams global event structure. this effectively sets all elements of the structure to 0, or the default settings.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_alarm -- Sets the alarm of the streams global event structuremcal_event_set_alarm() sets the streams global event structure's alarm to the given minutes before the event.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_category -- Sets the category of the streams global event structuremcal_event_set_category() sets the streams global event structure's category to the given string.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_class -- Sets the class of the streams global event structuremcal_event_set_class() sets the streams global event structure's class to the given value. The class is either 1 for public, or 0 for private.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_description -- Sets the description of the streams global event structuremcal_event_set_description() sets the streams global event structure's description to the given string.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_end -- Sets the end date and time of the streams global event structuremcal_event_set_end() sets the streams global event structure's end date and time to the given values.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_recur_daily -- Sets the recurrence of the streams global event structuremcal_event_set_recur_daily() sets the streams global event structure's recurrence to the given value to be reoccurring on a daily basis, ending at the given date.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_recur_monthly_mday -- Sets the recurrence of the streams global event structuremcal_event_set_recur_monthly_mday() sets the streams global event structure's recurrence to the given value to be reoccurring on a monthly by month day basis, ending at the given date.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_recur_monthly_wday -- Sets the recurrence of the streams global event structuremcal_event_set_recur_monthly_wday() sets the streams global event structure's recurrence to the given value to be reoccurring on a monthly by week basis, ending at the given date.
(PHP 3>= 3.0.15, PHP 4 )
mcal_event_set_recur_none -- Sets the recurrence of the streams global event structuremcal_event_set_recur_none() sets the streams global event structure to not recur (event->recur_type is set to MCAL_RECUR_NONE).
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_recur_weekly -- Sets the recurrence of the streams global event structuremcal_event_set_recur_weekly() sets the streams global event structure's recurrence to the given value to be reoccurring on a weekly basis, ending at the given date.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_recur_yearly -- Sets the recurrence of the streams global event structuremcal_event_set_recur_yearly() sets the streams global event structure's recurrence to the given value to be reoccurring on a yearly basis,ending at the given date.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_start -- Sets the start date and time of the streams global event structuremcal_event_set_start() sets the streams global event structure's start date and time to the given values.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_title -- Sets the title of the streams global event structuremcal_event_set_title() sets the streams global event structure's title to the given string.
Returns TRUE.
(no version information, might be only in CVS)
mcal_expunge -- Deletes all events marked for being expunged.mcal_expunge() deletes all events which have been previously marked for deletion.
(PHP 3>= 3.0.13, PHP 4 )
mcal_fetch_current_stream_event -- Returns an object containing the current streams event structuremcal_fetch_current_stream_event() returns the current stream's event structure as an object containing:
int id - ID of that event.
int public - TRUE if the event if public, FALSE if it is private.
string category - Category string of the event.
string title - Title string of the event.
string description - Description string of the event.
int alarm - number of minutes before the event to send an alarm/reminder.
object start - Object containing a datetime entry.
object end - Object containing a datetime entry.
int recur_type - recurrence type
int recur_interval - recurrence interval
datetime recur_enddate - recurrence end date
int recur_data - recurrence data
int year - year
int month - month
int mday - day of month
int hour - hour
int min - minutes
int sec - seconds
int alarm - minutes before event to send an alarm
mcal_fetch_event() fetches an event from the calendar stream specified by id.
Returns an event object consisting of:
int id - ID of that event.
int public - TRUE if the event if public, FALSE if it is private.
string category - Category string of the event.
string title - Title string of the event.
string description - Description string of the event.
int alarm - number of minutes before the event to send an alarm/reminder.
object start - Object containing a datetime entry.
object end - Object containing a datetime entry.
int recur_type - recurrence type
int recur_interval - recurrence interval
datetime recur_enddate - recurrence end date
int recur_data - recurrence data
int year - year
int month - month
int mday - day of month
int hour - hour
int min - minutes
int sec - seconds
int alarm - minutes before event to send an alarm
0 - Indicates that this event does not recur
1 - This event recurs daily
2 - This event recurs on a weekly basis
3 - This event recurs monthly on a specific day of the month (e.g. the 10th of the month)
4 - This event recurs monthly on a sequenced day of the week (e.g. the 3rd Saturday)
5 - This event recurs on an annual basis
mcal_is_leap_year() returns 1 if the given year is a leap year, 0 if not.
(PHP 3>= 3.0.13, PHP 4 )
mcal_list_alarms -- Return a list of events that has an alarm triggered at the given datetimeReturns an array of event ID's that has an alarm going off between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.
mcal_list_events() function takes in an optional beginning date and an end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.
Returns an array of ID's that are between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.
mcal_list_events() takes in an beginning date and an optional end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.
mcal_next_recurrence() returns an object filled with the next date the event occurs, on or after the supplied date. Returns empty date field if event does not occur or something is invalid. Uses weekstart to determine what day is considered the beginning of the week.
Returns an MCAL stream on success, FALSE on error.
mcal_open() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also. The streams internal event structure is also initialized upon connection.
Returns an MCAL stream on success, FALSE on error.
mcal_popen() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also. The streams internal event structure is also initialized upon connection.
Renames the calendar old_name to new_name.
Reopens an MCAL stream to a new calendar.
mcal_reopen() reopens an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also.
mcal_snooze() turns off an alarm for a calendar event specified by the stream_id and event_id.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
mcal_store_event() stores the modifications to the current global event for the given stream.
Returns the event id of the modified event on success and FALSE on error.
(PHP 3>= 3.0.13, PHP 4 )
mcal_time_valid -- Returns TRUE if the given hour, minutes and seconds is a valid timemcal_time_valid() Returns TRUE if the given hour, minutes and seconds is a valid time, FALSE if not.
This is an interface to the mcrypt library, which supports a wide variety of block algorithms such as DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST in CBC, OFB, CFB and ECB cipher modes. Additionally, it supports RC6 and IDEA which are considered "non-free".
These functions work using mcrypt. To use it, download libmcrypt-x.x.tar.gz from http://mcrypt.sourceforge.net/ and follow the included installation instructions. Windows users will find all the needed compiled mcrypt binaries at http://ftp.emini.dk/pub/php/win32/mcrypt/.
If you linked against libmcrypt 2.4.x or higher, the following additional block algorithms are supported: CAST, LOKI97, RIJNDAEL, SAFERPLUS, SERPENT and the following stream ciphers: ENIGMA (crypt), PANAMA, RC4 and WAKE. With libmcrypt 2.4.x or higher another cipher mode is also available; nOFB.
You need to compile PHP with the --with-mcrypt[=DIR] parameter to enable this extension. DIR is the mcrypt install directory. Make sure you compile libmcrypt with the option --disable-posix-threads.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Mcrypt configuration options
Name | Default | Changeable |
---|---|---|
mcrypt.algorithms_dir | NULL | PHP_INI_ALL |
mcrypt.modes_dir | NULL | PHP_INI_ALL |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Mcrypt can operate in four block cipher modes (CBC, OFB, CFB, and ECB). If linked against libmcrypt-2.4.x or higher the functions can also operate in the block cipher mode nOFB and in STREAM mode. Below you find a list with all supported encryption modes together with the constants that are defines for the encryption mode. For a more complete reference and discussion see Applied Cryptography by Schneier (ISBN 0-471-11709-9).
MCRYPT_MODE_ECB (electronic codebook) is suitable for random data, such as encrypting other keys. Since data there is short and random, the disadvantages of ECB have a favorable negative effect.
MCRYPT_MODE_CBC (cipher block chaining) is especially suitable for encrypting files where the security is increased over ECB significantly.
MCRYPT_MODE_CFB (cipher feedback) is the best mode for encrypting byte streams where single bytes must be encrypted.
MCRYPT_MODE_OFB (output feedback, in 8bit) is comparable to CFB, but can be used in applications where error propagation cannot be tolerated. It's insecure (because it operates in 8bit mode) so it is not recommended to use it.
MCRYPT_MODE_NOFB (output feedback, in nbit) is comparable to OFB, but more secure because it operates on the block size of the algorithm.
MCRYPT_MODE_STREAM is an extra mode to include some stream algorithms like WAKE or RC4.
Some other mode and random device constants:
Here is a list of ciphers which are currently supported by the mcrypt extension. For a complete list of supported ciphers, see the defines at the end of mcrypt.h. The general rule with the mcrypt-2.2.x API is that you can access the cipher from PHP with MCRYPT_ciphername. With the libmcrypt-2.4.x and libmcrypt-2.5.x API these constants also work, but it is possible to specify the name of the cipher as a string with a call to mcrypt_module_open().
MCRYPT_3DES
MCRYPT_ARCFOUR_IV (libmcrypt > 2.4.x only)
MCRYPT_ARCFOUR (libmcrypt > 2.4.x only)
MCRYPT_BLOWFISH
MCRYPT_CAST_128
MCRYPT_CAST_256
MCRYPT_CRYPT
MCRYPT_DES
MCRYPT_DES_COMPAT (libmcrypt 2.2.x only)
MCRYPT_ENIGMA (libmcrypt > 2.4.x only, alias for MCRYPT_CRYPT)
MCRYPT_GOST
MCRYPT_IDEA (non-free)
MCRYPT_LOKI97 (libmcrypt > 2.4.x only)
MCRYPT_MARS (libmcrypt > 2.4.x only, non-free)
MCRYPT_PANAMA (libmcrypt > 2.4.x only)
MCRYPT_RIJNDAEL_128 (libmcrypt > 2.4.x only)
MCRYPT_RIJNDAEL_192 (libmcrypt > 2.4.x only)
MCRYPT_RIJNDAEL_256 (libmcrypt > 2.4.x only)
MCRYPT_RC2
MCRYPT_RC4 (libmcrypt 2.2.x only)
MCRYPT_RC6 (libmcrypt > 2.4.x only)
MCRYPT_RC6_128 (libmcrypt 2.2.x only)
MCRYPT_RC6_192 (libmcrypt 2.2.x only)
MCRYPT_RC6_256 (libmcrypt 2.2.x only)
MCRYPT_SAFER64
MCRYPT_SAFER128
MCRYPT_SAFERPLUS (libmcrypt > 2.4.x only)
MCRYPT_SERPENT(libmcrypt > 2.4.x only)
MCRYPT_SERPENT_128 (libmcrypt 2.2.x only)
MCRYPT_SERPENT_192 (libmcrypt 2.2.x only)
MCRYPT_SERPENT_256 (libmcrypt 2.2.x only)
MCRYPT_SKIPJACK (libmcrypt > 2.4.x only)
MCRYPT_TEAN (libmcrypt 2.2.x only)
MCRYPT_THREEWAY
MCRYPT_TRIPLEDES (libmcrypt > 2.4.x only)
MCRYPT_TWOFISH (for older mcrypt 2.x versions, or mcrypt > 2.4.x )
MCRYPT_TWOFISH128 (TWOFISHxxx are available in newer 2.x versions, but not in the 2.4.x versions)
MCRYPT_TWOFISH192
MCRYPT_TWOFISH256
MCRYPT_WAKE (libmcrypt > 2.4.x only)
MCRYPT_XTEA (libmcrypt > 2.4.x only)
You must (in CFB and OFB mode) or can (in CBC mode) supply an initialization vector (IV) to the respective cipher function. The IV must be unique and must be the same when decrypting/encrypting. With data which is stored encrypted, you can take the output of a function of the index under which the data is stored (e.g. the MD5 key of the filename). Alternatively, you can transmit the IV together with the encrypted data (see chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9) for a discussion of this topic).
Mcrypt can be used to encrypt and decrypt using the above mentioned ciphers. If you linked against libmcrypt-2.2.x, the four important mcrypt commands (mcrypt_cfb(), mcrypt_cbc(), mcrypt_ecb(), and mcrypt_ofb()) can operate in both modes which are named MCRYPT_ENCRYPT and MCRYPT_DECRYPT, respectively.
If you linked against libmcrypt 2.4.x or 2.5.x, these functions are still available, but it is recommended that you use the advanced functions.
Esempio 2. Encrypt an input value with TripleDES under 2.4.x and higher in ECB mode
|
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.
(PHP 3>= 3.0.8, PHP 4 , PHP 5)
mcrypt_create_iv -- Create an initialization vector (IV) from a random sourcemcrypt_create_iv() is used to create an IV.
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.
The IV is only meant to give an alternative seed to the encryption routines. This IV does not need to be secret at all, though it can be desirable. You even can send it along with your ciphertext without loosing security.
More information can be found at http://www.ciphersbyritter.com/GLOSSARY.HTM#IV, http://fn2.freenet.edmonton.ab.ca/~jsavard/crypto/co0409.htm and in chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9) for a discussion of this topic.
mcrypt_decrypt() decrypts the data and returns the unencrypted data.
Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.
Key is the key with which the data is encrypted. If it's smaller that the required keysize, it is padded with '\0'.
Data is the data that will be decrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'.
Mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".
The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to '\0'.
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
This function is deprecated and should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.
This function returns the name of the algorithm.
Esempio 1. mcrypt_enc_get_algorithms_name() example
|
This function returns the block size of the algorithm specified by the encryption descriptor td in bytes.
This function returns the size of the iv of the algorithm specified by the encryption descriptor in bytes. If it returns '0' then the IV is ignored in the algorithm. An IV is used in cbc, cfb and ofb modes, and in some algorithms in stream mode.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_enc_get_key_size -- Returns the maximum supported keysize of the opened modeThis function returns the maximum supported key size of the algorithm specified by the encryption descriptor td in bytes.
This function returns the name of the mode.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_enc_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithmReturns an array with the key sizes supported by the algorithm specified by the encryption descriptor. If it returns an empty array then all key sizes between 1 and mcrypt_enc_get_key_size() are supported by the algorithm.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_enc_is_block_algorithm_mode -- Checks whether the encryption of the opened mode works on blocksThis function returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE. (e.g. FALSE for stream, and TRUE for cbc, cfb, ofb).
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_enc_is_block_algorithm -- Checks whether the algorithm of the opened mode is a block algorithmThis function returns TRUE if the algorithm is a block algorithm, or FALSE if it is a stream algorithm.
This function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs bytes. (e.g. TRUE for cbc and ecb, and FALSE for cfb and stream).
This function runs the self test on the algorithm specified by the descriptor td. If the self test succeeds it returns FALSE. In case of an error, it returns TRUE.
mcrypt_encrypt() encrypts the data and returns the encrypted data.
Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.
Key is the key with which the data will be encrypted. If it's smaller that the required keysize, it is padded with '\0'. It is better not to use ASCII strings for keys. It is recommended to use the mhash functions to create a key from a string.
Data is the data that will be encrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'. The returned crypttext can be larger that the size of the data that is given by data.
Mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".
The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to '\0'.
Esempio 1. mcrypt_encrypt() Example
The above example will print out:
|
See also mcrypt_module_open() for a more advanced API and an example.
This function terminates encryption specified by the encryption descriptor (td). It clears all buffers, but does not close the module. You need to call mcrypt_module_close() yourself. (But PHP does this for you at the end of the script.) Returns FALSE on error, or TRUE on success.
See for an example mcrypt_module_open() and the entry on mcrypt_generic_init().
Avvertimento |
This function is deprecated, use mcrypt_generic_deinit() instead. It can cause crashes when used with mcrypt_module_close() due to multiple buffer frees. |
This function terminates encryption specified by the encryption descriptor (td). Actually it clears all buffers, and closes all the modules used. Returns FALSE on error, or TRUE on success.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_generic_init -- This function initializes all buffers needed for encryptionThe maximum length of the key should be the one obtained by calling mcrypt_enc_get_key_size() and every value smaller than this is legal. The IV should normally have the size of the algorithms block size, but you must obtain the size by calling mcrypt_enc_get_iv_size(). IV is ignored in ECB. IV MUST exist in CFB, CBC, STREAM, nOFB and OFB modes. It needs to be random and unique (but not secret). The same IV must be used for encryption/decryption. If you do not want to use it you should set it to zeros, but this is not recommended.
The function returns a negative value on error, -3 when the key length was incorrect, -4 when there was a memory allocation problem and any other return value is an unknown error. If an error occurs a warning will be displayed accordingly.
You need to call this function before every call to mcrypt_generic() or mdecrypt_generic().
See for an example mcrypt_module_open().
This function encrypts data. The data is padded with "\0" to make sure the length of the data is n * blocksize. This function returns the encrypted data. Note that the length of the returned string can in fact be longer then the input, due to the padding of the data.
If you want to store the encrypted data in a database make sure to store the entire string as returned by mcrypt_generic, or the string will not entirely decrypt properly. If your original string is 10 characters long and the block size is 8 (use mcrypt_enc_get_block_size() to determine the blocksize), you would need at least 16 characters in your database field. Note the string returned by mdecrypt_generic() will be 16 characters as well...use rtrim()($str, "\0") to remove the padding.
If you are for example storing the data in a MySQL database remember that varchar fields automatically have trailing spaces removed during insertion. As encrypted data can end in a space (ASCII 32), the data will be damaged by this removal. Store data in a tinyblob/tinytext (or larger) field instead.
The encryption handle should always be initialized with mcrypt_generic_init() with a key and an IV before calling this function. Where the encryption is done, you should free the encryption buffers by calling mcrypt_generic_deinit(). See mcrypt_module_open() for an example.
See also mdecrypt_generic(), mcrypt_generic_init(), and mcrypt_generic_deinit().
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.
mcrypt_get_block_size() is used to get the size of a block of the specified cipher (in combination with an encryption mode).
It is more useful to use the mcrypt_enc_get_block_size() function as this uses the resource returned by mcrypt_module_open().
This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x.
See also: mcrypt_get_key_size(), mcrypt_enc_get_block_size() and mcrypt_encrypt().
mcrypt_get_cipher_name() is used to get the name of the specified cipher.
mcrypt_get_cipher_name() takes the cipher number as an argument (libmcrypt 2.2.x) or takes the cipher name as an argument (libmcrypt 2.4.x or higher) and returns the name of the cipher or FALSE, if the cipher does not exist.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_get_iv_size -- Returns the size of the IV belonging to a specific cipher/mode combinationmcrypt_get_iv_size() returns the size of the Initialisation Vector (IV) in bytes. On error the function returns FALSE. If the IV is ignored in the specified cipher/mode combination zero is returned.
cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.
mode is one of the MCRYPT_MODE_modename constants or one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream". The IV is ignored in ECB mode as this mode does not require it. You will need to have the same IV (think: starting point) both at encryption and decryption stages, otherwise your encryption will fail.
It is more useful to use the mcrypt_enc_get_iv_size() function as this uses the resource returned by mcrypt_module_open().
See also mcrypt_get_block_size(), mcrypt_enc_get_iv_size() and mcrypt_create_iv().
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.
mcrypt_get_key_size() is used to get the size of a key of the specified cipher (in combination with an encryption mode).
This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x. It is more useful to use the mcrypt_enc_get_key_size() function as this uses the resource returned by mcrypt_module_open().
Esempio 1. mcrypt_get_block_size() example
|
See also: mcrypt_get_block_size(), mcrypt_end_get_key_size() and mcrypt_encrypt().
mcrypt_list_algorithms() is used to get an array of all supported algorithms in the lib_dir parameter.
mcrypt_list_algorithms() takes an optional lib_dir parameter which specifies the directory where all algorithms are located. If not specifies, the value of the mcrypt.algorithms_dir php.ini directive is used.
mcrypt_list_modes() is used to get an array of all supported modes in the lib_dir.
mcrypt_list_modes() takes as optional parameter a directory which specifies the directory where all modes are located. If not specifies, the value of the mcrypt.modes_dir php.ini directive is used.
Esempio 1. mcrypt_list_modes() Example
The above example will produce a list with all supported algorithms in the default mode directory. If it is not set with the ini directive mcrypt.modes_dir, the default directory of mcrypt is used (which is /usr/local/lib/libmcrypt). |
This function closes the specified encryption handle.
See mcrypt_module_open() for an example.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_get_algo_block_size -- Returns the blocksize of the specified algorithmThis function returns the block size of the algorithm specified in bytes. The optional lib_dir parameter can contain the location where the mode module is on the system.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_get_algo_key_size -- Returns the maximum supported keysize of the opened modeThis function returns the maximum supported key size of the algorithm specified in bytes. The optional lib_dir parameter can contain the location where the mode module is on the system.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithmReturns an array with the key sizes supported by the specified algorithm. If it returns an empty array then all key sizes between 1 and mcrypt_module_get_algo_key_size() are supported by the algorithm. The optional lib_dir parameter can contain the location where the mode module is on the system.
See also mcrypt_enc_get_supported_key_sizes() which is used on open encryption modules.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_is_block_algorithm_mode -- returns if the specified module is a block algorithm or notThis function returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE. (e.g. FALSE for stream, and TRUE for cbc, cfb, ofb). The optional lib_dir parameter can contain the location where the mode module is on the system.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_is_block_algorithm -- This function checks whether the specified algorithm is a block algorithmThis function returns TRUE if the specified algorithm is a block algorithm, or FALSE is it is a stream algorithm. The optional lib_dir parameter can contain the location where the algorithm module is on the system.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_is_block_mode -- Returns if the specified mode outputs blocks or notThis function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs just bytes. (e.g. TRUE for cbc and ecb, and FALSE for cfb and stream). The optional lib_dir parameter can contain the location where the mode module is on the system.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_open -- Opens the module of the algorithm and the mode to be usedThis function opens the module of the algorithm and the mode to be used. The name of the algorithm is specified in algorithm, e.g. "twofish" or is one of the MCRYPT_ciphername constants. The module is closed by calling mcrypt_module_close(). Normally it returns an encryption descriptor, or FALSE on error.
The algorithm_directory and mode_directory are used to locate the encryption modules. When you supply a directory name, it is used. When you set one of these to the empty string (""), the value set by the mcrypt.algorithms_dir or mcrypt.modes_dir ini-directive is used. When these are not set, the default directories that are used are the ones that were compiled in into libmcrypt (usually /usr/local/lib/libmcrypt).
The first line in the example above will try to open the DES cipher from the default directory and the EBC mode from the directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher and mode, this only works when the extension is linked against libmcrypt 2.4.x or 2.5.x.
Esempio 2. Using mcrypt_module_open() in encryption
|
The first line in the example above will try to open the DES cipher from the default directory and the EBC mode from the directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher and mode, this only works when the extension is linked against libmcrypt 2.4.x or 2.5.x.
See also mcrypt_module_close(), mcrypt_generic(), mdecrypt_generic(), mcrypt_generic_init(), and mcrypt_generic_deinit().
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_self_test -- This function runs a self test on the specified moduleThis function runs the self test on the algorithm specified. The optional lib_dir parameter can contain the location of where the algorithm module is on the system.
The function returns TRUE if the self test succeeds, or FALSE when if fails.
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.
This function decrypts data. Note that the length of the returned string can in fact be longer then the unencrypted string, due to the padding of the data.
Esempio 1. mdecrypt_generic() example
|
The above example shows how to check if the data before the encryption is the same as the data after the decryption. It is very important to reinitialize the encryption buffer with mcrypt_generic_init() before you try to decrypt the data.
The decryption handle should always be initialized with mcrypt_generic_init() with a key and an IV before calling this function. Where the encryption is done, you should free the encryption buffers by calling mcrypt_generic_deinit(). See mcrypt_module_open() for an example.
See also mcrypt_generic(), mcrypt_generic_init(), and mcrypt_generic_deinit().
These functions interface the MCVE API (libmcve), allowing you to work directly with MCVE from your PHP scripts. MCVE is Main Street Softworks' solution to direct credit card processing for Linux / Unix ( http://www.mainstreetsoftworks.com/ ). It lets you directly address the credit card clearing houses via your *nix box, modem and/or internet connection (bypassing the need for an additional service such as Authorize.Net or Pay Flow Pro). Using the MCVE module for PHP, you can process credit cards directly through MCVE via your PHP scripts. The following references will outline the process.
Nota: MCVE is the replacement for RedHat's CCVS. They contracted with RedHat in late 2001 to migrate all existing clientele to the MCVE platform.
Nota: Questo modulo non è disponibile su piattaforme Windows.
To enable MCVE Support in PHP, first verify your LibMCVE installation directory. You will then need to configure PHP with the --with-mcve option. If you use this option without specifying the path to your MCVE installation, PHP will attempt to look in the default LibMCVE Install location (/usr/local). If MCVE is in a non-standard location, run configure with: --with-mcve=$mcve_path, where $mcve_path is the path to your MCVE installation. Please note that MCVE support requires that $mcve_path/lib and $mcve_path/include exist, and include mcve.h under the include directory and libmcve.so and/or libmcve.a under the lib directory.
Since MCVE has true server/client separation, there are no additional requirements for running PHP with MCVE support. To test your MCVE extension in PHP, you may connect to testbox.mcve.com on port 8333 for IP, or port 8444 for SSL using the MCVE PHP API. Use 'vitale' for your username, and 'test' for your password. Additional information about test facilities are available at http://www.mainstreetsoftworks.com/.
Additional documentation about MCVE's PHP API can be found at http://www.mainstreetsoftworks.com/docs/phpapi.pdf. Main Street's documentation is complete and should be the primary reference for functions.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_completeauthorizations -- Number of complete authorizations in queue, returning an array of their identifiers
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
mcve_connectionerror -- Get a textual representation of why a connection failed
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_getcell -- Get a specific cell from a comma delimited response by column name
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_getcellbynum -- Get a specific cell from a comma delimited response by column number
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_getcommadelimited -- Get the RAW comma delimited data returned from MCVE
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
mcve_maxconntimeout -- The maximum amount of time the API will attempt a connection to MCVE
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_monitor -- Perform communication with MCVE (send/receive data) Non-blocking
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_parsecommadelimited -- Parse the comma delimited response so mcve_getcell, etc will work
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_preauthcompletion -- Complete a PREAUTHORIZATION... Ready it for settlement
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.3, PHP 5)
mcve_setssl_files -- Set certificate key files and certificates if server requires client certificate verification
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_transactionauth -- Get the authorization number returned for the transaction (alpha-numeric)
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_transactionbatch -- Get the batch number associated with the transaction
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_transactionitem -- Get the ITEM number in the associated batch for this transaction
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_transactiontext -- Get verbiage (text) return from MCVE or processing institution
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
mcve_verifyconnection -- Set whether or not to PING upon connect to verify connection
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
mcve_verifysslcert -- Set whether or not to verify the server ssl certificate
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.
More information about memcached can be found at http://www.danga.com/memcached/.
This module uses functions of zlib to support on-the-fly data compression. Zlib is required to install this module.
PHP 4.3.3 or newer is required to use memcache extension.
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:
Windows users can download the extension dll php_memcache.dll here: http://snaps.php.net/win32/PECL_STABLE/.
There is only one resource type used in memcache module - it's the link identifier for a cache server connection.
Used to turn on-the-fly data compression on with Memcache::set(), Memcache::add() and Memcache::replace().
Esempio 2. memcache extension overview example
|
In the above example, an object is being saved in the cache and then retrieved back. Object and other non-scalar types are serialized before saving, so it's impossible to store resources (i.e. connection identifiers and others) in the cache.
Memcache::add() stores variable var with key only if such key doesn't exist at the server yet. Memcache::add() returns FALSE if such key already exist. For the rest Memcache::add() behaves similarly to Memcache::set().
Also you can use memcache_add() function. See example below.
Memcache::add() returns TRUE on success or FALSE on failure.
See also Memcache::set(), Memcache::replace().
Memcache::close() closes connection to memcached server. This function doesn't close persistent connections, which are closed only during web-server shutdown/restart.
Also you can use memcache_close() function. See example below.
Esempio 1. Memcache::close() example
|
Memcache::close() returns FALSE if an error occured.
See also Memcache::connect(), Memcache::pconnect().
Memcache::connect() establishes a connection to the memcached server. Parameters host and port point to the host and port, where memcached is listening for connections. Parameter port is optional, it's default value is 11211. Also you can define a timeout, which will be used when connecting to the daemon. Think twice before changing the default value - you can loose all the advantages of caching if your connection is too slow.
The connection, which was opened using Memcache::connect() will be automatically closed at the end of script execution. Also you can close it with Memcache::close().
Also you can use memcache_connect() function. See example below.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also Memcache::pconnect() and Memcache::close().
Memcache::decrement() decrements value of the item by value. Similarly to Memcache::increment(), current value of the item is being converted to numerical and after that value is substracted.
Parameter value is optional. It's default is 1.
Nota: New item's value will not be less than zero.
Nota: Do not use Memcache::decrement() with item, which was stored compressed, because consequent call to Memcache::get() will fail.
Also you can use memcache_decrement() function. See example below.
Esempio 1. Memcache::decrement() example
|
Memcache::decrement() does not create an item if it didn't exist.
Memcache::decrement() returns item's new value on success or FALSE on failure.
See also Memcache::increment(), Memcache::replace().
Memcache::delete() deletes item with the key. If parameter timeout is specified, the item will expire after timeout seconds.
Also you can use memcache_delete() function. See example below.
Esempio 1. Memcache::delete() example
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
Memcache::flush -- Flush all existing items at the serverMemcache::flush() immediately invalidates all existing items. Memcache::flush() doesn't actually free any resources, it only marks all the items as expired, so occupied memory will be overwritten by new items.
Also you can use memcache_flush() function. See example below.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Memcache::get() returns previously stored data if an item with such key exists on the server at this moment.
Memcache::get() returns FALSE on failure.
Memcache::getStats() returns an associative array with server's statistics. Array keys correspond to stats parameters and values to parameter's values.
Also you can use memcache_get_stats() function.
Memcache::getStats() returns FALSE in case of an error.
See also Memcache::getVersion().
Memcache::getVersion() returns a string with server's version number.
Also you can use memcache_get_version() function. See example below.
Memcache::getVersion() returns FALSE if an error occured.
See also Memcache::getStats().
Memcache::increment() increments value of the item on the specified value. If item with key key was not numeric and cannot be converted to number, it will change it's value to value.
Parameter value is optional. It's default value is 1.
Nota: Do not use Memcache::increment() with item, which was stored compressed, because consequent call to Memcache::get() will fail.
Also you can use memcache_increment() function. See example below.
Esempio 1. Memcache::increment() example
|
Memcache::increment() returns new item's value on success or FALSE on failure.
Memcache::increment() does not create an item if it didn't exist.
See also Memcache::decrement(), Memcache::replace().
(no version information, might be only in CVS)
Memcache::pconnect -- Open memcached server persistent connectionMemcache::pconnect() is similar to Memcache::connect() with the difference, that the connection it establishes is persistent. This connection is not closed after the end of script execution and by Memcache::close() function.
Also you can use memcache_pconnect() function. See example below.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also Memcache::connect().
(no version information, might be only in CVS)
Memcache::replace -- Replace value of the existing itemMemcache::replace() should be used to replace value of existing item with key. In case if item with such key doesn't exists, Memcache::replace() returns FALSE. For the rest Memcache::replace() behaves similarly to Memcache::set().
Also you can use memcache_replace() function. See example below.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also Memcache::set(), Memcache::add().
Memcache::set() stores an item var with key on the memcached server. Parameter expire is expiration time in seconds. If it's 0, the item never expires (but memcached server doesn't guarantee this item to be stored all the time, it could be deleted from the cache to make place for other items).
You can use MEMCACHE_COMPRESSED constant as flag value if you want to use on-the-fly compression (uses zlib).
Also you can use memcache_set() function. See example below.
Nota: Remember that resource variables (i.e. file and connection descriptors) cannot be stored in the cache, because they cannot be adequately represented in serialized state.
Esempio 1. Memcache::set() example
|
Esempio 2. Memcache::set() example
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also Memcache::add(), Memcache::replace().
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.
These functions are intended to work with mhash. Mhash can be used to create checksums, message digests, message authentication codes, and more.
This is an interface to the mhash library. mhash supports a wide variety of hash algorithms such as MD5, SHA1, GOST, and many others. For a complete list of supported hashes, refer to the documentation of mhash. The general rule is that you can access the hash algorithm from PHP with MHASH_HASHNAME. For example, to access TIGER you use the PHP constant MHASH_TIGER.
To use it, download the mhash distribution from its web site and follow the included installation instructions.
You need to compile PHP with the --with-mhash[=DIR] parameter to enable this extension. DIR is the mhash install directory.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Here is a list of hashes which are currently supported by mhash. If a hash is not listed here, but is listed by mhash as supported, you can safely assume that this documentation is outdated.
MHASH_MD5
MHASH_SHA1
MHASH_HAVAL256
MHASH_HAVAL192
MHASH_HAVAL160
MHASH_HAVAL128
MHASH_RIPEMD160
MHASH_GOST
MHASH_TIGER
MHASH_CRC32
MHASH_CRC32B
Esempio 1. Compute the MD5 digest and hmac and print it out as hex
This will produce:
|
mhash_count() returns the highest available hash id. Hashes are numbered from 0 to this hash id.
mhash_get_block_size() is used to get the size of a block of the specified hash.
mhash_get_block_size() takes one argument, the hash and returns the size in bytes or FALSE, if the hash does not exist.
mhash_get_hash_name() is used to get the name of the specified hash.
mhash_get_hash_name() takes the hash id as an argument and returns the name of the hash or FALSE, if the hash does not exist.
mhash_keygen_s2k() generates a key that is bytes long, from a user given password. This is the Salted S2K algorithm as specified in the OpenPGP document (RFC 2440). That algorithm will use the specified hash algorithm to create the key. The salt must be different and random enough for every key you generate in order to create different keys. That salt must be known when you check the keys, thus it is a good idea to append the key to it. Salt has a fixed length of 8 bytes and will be padded with zeros if you supply less bytes.
Keep in mind that user supplied passwords are not really suitable to be used as keys in cryptographic algorithms, since users normally choose keys they can write on keyboard. These passwords use only 6 to 7 bits per character (or less). It is highly recommended to use some kind of transformation (like this function) to the user supplied key.
mhash() applies a hash function specified by hash to the data and returns the resulting hash (also called digest). If the key is specified it will return the resulting HMAC. HMAC is keyed hashing for message authentication, or simply a message digest that depends on the specified key. Not all algorithms supported in mhash can be used in HMAC mode. In case of an error returns FALSE.
Avvertimento |
This extension has been deprecated as the PECL extension fileinfo provides the same functionality (and more) in a much cleaner way. |
The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.
This extension is derived from Apache mod_mime_magic, which is itself based on the file command maintained by Ian F. Darwin. See the source code for further historic and copyright information.
You must compile PHP with the configure switch --with-mime-magic to get support for mime-type functions. The extension needs a copy of the simplified magic file that is distributed with the Apache httpd.
Nota: The configure option has been changed from --enable-mime-magic to --with-mime-magic since PHP 4.3.2
Nota: This extension is not capable of handling the fully decorated magic file that generally comes with standard Linux distro's and is supposed to be used with recent versions of file command.
Note to Win32 Users: In order to use this module on a Windows environment, you must set the path to the bundled magic.mime file in your php.ini.
Remember to substitute the $PHP_INSTALL_DIR for your actual path to PHP in the above example. e.g. c:\php
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Mimetype configuration options
Name | Default | Changeable |
---|---|---|
mime_magic.magicfile | "/usr/share/misc/magic.mime" | PHP_INI_SYSTEM |
Queste funzioni permettono di accedere ad un database MS SQL Server.
Requisiti per le piattaforme Win32
Per potere funzionare è richiesto che sia installato il MS SQL Client Tools sullo stesso sistema su cui è il installato il PHP. Il Client Tools può essere installato o dal cd di MS SQL Server, o copiando il file ntwdblib.dll dalla directory \winnt\system32 del server alla directory \winnt\system32 della macchina su cui è installato il PHP. La copia del file ntwdblib.dll permette solo l'accesso al database. La configurazione del client richiede comunque l'installazione di tutto il pacchetto MS SQL Client Tools.
Requisiti per le piattaforme Unix/Linux
Per potere utilizzare l'estensione MSSQl su piattaforme Unix/Linux, occorre compilare ed installare la libreria FreeTDS. Il codice sorgente e le istruzioni per l'installazione sono disponibili nel sito di FreeTDS: http://www.freetds.org/
Nota: Nella piattaforma Windows si utilizzano le DBLIB di Microsoft. Quindi le funzioni che restituiscono il nome della colonna si basano sulla funzione dbcolname() della DBLIB. La DBLIB è stata sviluppata per SQL Server 6.x che ammetteva nomi di colonna lunghi al massimo 30 caratteri. Per questo motivo il numero massimo di caratteri per il nome colonna ammessi sono 30. Nelle piattaforme in cui si utilizza FreeTDS (Linux) non si ha questo problema.
Il modulo MSSQL si abilita aggiungendo extension=php_mssql.dll al file di configurazione php.ini.
Per attivare queste funzionalità occorre compilare il PHP con --with-mssql[=DIR], dove DIR è la directory in cui è installato FreeTDS. Il pacchetto FreeTDS dovrebbe essere compilato utilizzando --enable-msdblib.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Parametri di configurazione per il modulo MS SQL Server
Nome | Default | Modificabile |
---|---|---|
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 |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
(PHP 4 >= 4.1.0, PHP 5)
mssql_bind -- Aggiunge un parametro ad una procedura memorizzata (stored procedure) locale o remotaAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche mssql_execute(), mssql_free_statement() e mssql_init().
La funzione mssql_close() chiude la connessione ad un database MS SQL Server che è associata all' argomento id_connessione. Se l' id_connessione non viene indicato, si fa riferimento all'ultima connessione aperta.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: solitamente non è necessario l'uso della funzione, dato che tutte le connessioni non-persistenti sono chiuse automaticamente al termine dell'esecuzione dello script.
mssql_close() non chiude i collegamenti persistenti aperti utilizzando mssql_pconnect().
Vedere anche: mssql_connect() e mssql_pconnect().
Restituisce: un identificativo di connessione 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().
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().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Se le stored procedure restituiscono parametri oppure valori, questi saranno disponibili successivamente all'esecuzione della funzione mssql_execute() a meno che non sia restituito più di un set di risultati. In questo caso occorre utilizzare mssql_next_result() per spostarsi tra i risultati. Una volta terminato lo scorrimento dei set di risultati, sia i parametri di output sia i valori di ritorno saranno disponibili.
Vedere anche mssql_bind(), mssql_free_statement() e mssql_init().
(PHP 3, PHP 4 , PHP 5)
mssql_fetch_array -- Restituisce una riga in un array associativo, numerico o entrambiLa funzione restituisce: un array corrispondente alla riga estratta, oppure falso se non vi sono più righe.
La funzione mssql_fetch_array() è un' estensione della funzione mssql_fetch_row(). Oltre a memorizzare i dati in un array con indice numerico, la funzione memorizza i dati in un array associativo in cui la chiave è costituita dal nome del campo.
Un aspetto da notare è che la funzione mssql_fetch_array() NON è significativamente più lenta rispetto a mssql_fetch_row(), mentre nel contempo fornisce funzionalità maggiori.
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Per ulteriori dettagli vedere anche mssql_fetch_row().
(PHP 4 >= 4.2.0, PHP 5)
mssql_fetch_assoc -- Restituisce un array associativo con i dati di una riga dal set di risultati indicato da id_risultatoAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione restituisce un oggetto contenente le informazioni sul campo.
La funzione mssql_fetch_field() può essere utilizzata per ottenere informazioni sui campi presenti nel risultato di una certa query. Se non viene specificato l'argomento offset_campo, la funzione restituisce il campo successivo che non è ancora stato restituito da mssql_fetch_field().
Le proprietà dell'oggetto sono:
name - nome della colonna. Se la colonna è il risultato di una funzione, questa proprietà è valorizzata con "computed#N", dove #N è un numero progressivo.
column_source - tabella da cui sono ricavate le colonne
max_length - lunghezza massima della colonna
numeric - 1 se la colonna è numerica
type - tipo di colonna.
Vedere anche mssql_field_seek().
La funzione restituisce un oggetto le cui proprietà corrispondono alla riga estratta, oppure falso se non vi sono più righe.
La funzione mssql_fetch_object() è simile a mssql_fetch_array(), tranne che per una differenza, la prima restituisce un oggetto, la seconda un array. Indirettamente questo significa che si può accedere ai dati solo attraverso il nome dei campi e non tramite il loro offset (i numeri non sono dei validi nomi di proprietà).
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
A livello di velocità il comportamento è simile a mssql_fetch_array(), e quasi veloce come mssql_fetch_row() (la differenza è insignificante ).
Vedere anche mssql_fetch_array() e mssql_fetch_row().
La funzione restituisce un array che corrisponde alla riga estratta, oppure falso se non vi sono più righe.
La funzione mssql_fetch_row() estrae una riga di dati dal risultato associato all'identificativo di risultato passato. La riga viene restituita in un array. Ciascuna colonna è memorizzata in un campo dell'array. Il primo ha indice 0.
Esecuzione successive di mssql_fetch_row() restituiscono le righe successive presenti nel risultato, oppure falso se non vi sono più righe.
Vedere anche mssql_fetch_array(), mssql_fetch_object(), mssql_data_seek(), mssql_fetch_lengths() e mssql_result().
Questa funzione restituisce il valore del campo numero offset dalla query indicata da result. Se si omette offset la funzione resituisce il valore per il campo corrente.
Nota per gli utenti Win32: A causa delle limitazione delle sottostanti API utilizzate dal PHP (MS DbLib C API), la lunghezza dei campi VARCHAR è limitata a 255. Se si ha necessità di memorizzare maggiori informazioni, utilizzare il tipo TEXT
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Si posiziona sul campo richiesto. Eseguendo successivamente la funzione mssql_fetch_field() senza indicare alcun campo, quest'ultima restituirà il campo richiesto tramite mssql_fetch_field().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche mssql_fetch_field().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
E' necessario l'utilizzo della funzione mssql_free_result() solo quando si è preoccupati dell'occupazione di memoria durante l'esecuzione dello script. Normalmente tutti i dati verranno rimossi automaticamente dalla memoria al termine dell'esecuzione dello script.E' tuttavia possibile eseguire mssql_free_result(), per liberare la memoria occupata dai dati indicati dal parametro id_risultato
mssql_free_statement() only needs to be called if you are worried about using too much memory while your script is running. All statement memory will automatically be freed when the script ends. You may call mssql_free_statement() with the statement identifier as an argument and the associated statement memory will be freed.
See also mssql_bind(), mssql_execute(), and mssql_init()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
mssql_guid_string -- Converte il GUID dal formato binario a 16 bit al formato stringaAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche: mssql_bind(), mssql_execute() e mssql_free_statement()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nel caso in cui si eseguano più di una istruzione SQL al server, oppure si eseguano delle procedure memorizzate (stored procedure) con possibilità di molteplici risultati, il server restituirà un set di diversi risultati. Questa funzione verifica se esistono ulteriori risultati dal server. Se effettivamente esiste un'altro risultato, questa funzione libera la memoria dal risultato corrente e si predispone per la ricezione del risultato successivo. La funzione restituisce TRUE se è disponibile un'altro risultato, FALSE in caso contrario.
Esempio 1. mssql_next_result() Esempio di utilizzo
|
La funzione mssql_num_fields() restituisce il numero di campi presenti in un risultato.
Vedere anche: mssql_query(), mssql_fetch_field() e mssql_num_rows().
La funzione mssql_num_rows() restituisce il numero di righe presenti in un risultato.
Vedere anche: mssql_query() e mssql_fetch_row().
La funzione restituisce: o un identificativo di connessione persistente, o FALSE se si verifica un errore.
La funzione mssql_pconnect() agisce come mssql_connect() tranne che per due differenze.
Prima differenza, quando si cerca di stabilire la connessione, la funzione per prima cosa cerca di trovare una connessione (persistente) già aperta verso lo stesso server, con i medesimi utenti e password. Se ne viene trovata una, la funzione restituisce l'identificativo di quella connessione, invece di stabilirne una nuova.
Seconda differenza, la connessione con il server SQL non verrà chiusa al termine dello script. Il collegamento resterà aperto per utilizzi futuri (la funzione mssql_close() non chiude i collegamenti aperti da mssql_pconnect()).
Per questo motivo questo tipo di collegamento viene definito 'persistente'.
La funzione restituisce un identificativo di risultato in caso di esecuzione corretta, oppure falso in caso di errore.
La funzione mssql_query() invia una query al database attivo sul server attraverso la connessione specificata da id_connessione. Se l'argomento id_connessione non viene fornito, si utilizza l'ultima connessione aperta in ordine di tempo. Se non vi sono connessioni aperte, la funzione tenta di stabilire una connessione, come se fosse utilizzata la funzione mssql_connect(), e utilizza quella.
Vedere anche: mssql_select_db() e mssql_connect().
La funzione mssql_result() restituisce il contenuto di una cella da un risultato di una query a MS SQL. L'argomento campo può essere la posizione di un campo, oppure il suo nome, oppure nome tabella punto nome campo ( nome_tabella.nome_campo ). Se il nome della colonna ha un sostituto, ('select foo as bar from...'), usare quello anzichè il nome originale.
Quando si lavora con risultati abbastanza grossi, si dovrebbe considerare l'utilizzo di funzioni che restituiscono l'intera riga ( indicate di seguito ), dato che queste restituiscono il contenuto di molte celle in una chiamata sola. Pertanto sono MOLTO più veloci di mssql_result(). Da notare inoltre, che specificando la posizione per l'argomento campo, la funzione è molto più veloce rispetto al caso in cui si indica il nome del campo o della tabella.
Le alternative più veloci raccomandate sono: mssql_fetch_row(), mssql_fetch_array(), e mssql_fetch_object().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione mssql_select_db() setta il database attivo sul server attraverso la connessione specificata da id_connessione. Se l'argomento id_connessione non viene fornito, si utilizza l'ultima connessione aperta in ordine di tempo. Se non vi sono connessioni aperte, la funzione tenta di stabilire una connessione, come se fosse utilizzata la funzione mssql_connect(), e utilizza quella.
Ciascuna esecuzione di mssql_query() sarà fatta sul database attivo.
Per potere selezionare un database contenente un nome o un trattivo ("-") nel nome occorre racchiudere il nome stesso tra parantesi quadre, come illustrato nell'esempio seguente:
Vedere anche: mssql_connect(), mssql_pconnect(), e mssql_query()
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
First of all: Ming is not an acronym. Ming is an open-source (LGPL) library which allows you to create SWF ("Flash") format movies. Ming supports almost all of Flash 4's features, including: shapes, gradients, bitmaps (pngs and jpegs), morphs ("shape tweens"), text, buttons, actions, sprites ("movie clips"), streaming mp3, and color transforms --the only thing that's missing is sound events.
Note that all values specifying length, distance, size, etc. are in "twips", twenty units per pixel. That's pretty much arbitrary, though, since the player scales the movie to whatever pixel size is specified in the embed/object tag, or the entire frame if not embedded.
Ming offers a number of advantages over the existing PHP/libswf module. You can use Ming anywhere you can compile the code, whereas libswf is closed-source and only available for a few platforms, Windows not one of them. Ming provides some insulation from the mundane details of the SWF file format, wrapping the movie elements in PHP objects. Also, Ming is still being maintained; if there's a feature that you want to see, just let us know ming@opaque.net.
Ming was added in PHP 4.0.5.
To use Ming with PHP, you first need to build and install the Ming library. Source code and installation instructions are available at the Ming home page: http://ming.sourceforge.net/ along with examples, a small tutorial, and the latest news.
Download the ming archive. Unpack the archive. Go in the Ming directory. make. make install.
This will build libming.so and install it into /usr/lib/, and copy ming.h into /usr/include/. Edit the PREFIX= line in the Makefile to change the installation directory.
Now either just add extension=php_ming.so to your php.ini file, or put dl('php_ming.so'); at the head of all of your Ming scripts.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Queste classi sono definite da questa estensione, e sono disponibili solo quando l'estensione è stata compilata nel PHP o caricata come modulo dinamico al runtime.
Ming introduces 13 new objects in PHP, all with matching methods and attributes. To use them, you need to know about objects.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfaction() creates a new Action, and compiles the given script into an SWFAction object.
The script syntax is based on the C language, but with a lot taken out- the SWF bytecode machine is just too simpleminded to do a lot of things we might like. For instance, we can't implement function calls without a tremendous amount of hackery because the jump bytecode has a hardcoded offset value. No pushing your calling address to the stack and returning- every function would have to know exactly where to return to.
So what's left? The compiler recognises the following tokens:
break
for
continue
if
else
do
while
There is no typed data; all values in the SWF action machine are stored as strings. The following functions can be used in expressions:
Returns the number of milliseconds (?) elapsed since the movie started.
Returns a pseudo-random number in the range 0-seed.
Returns the length of the given expression.
Returns the given number rounded down to the nearest integer.
Returns the concatenation of the given expressions.
Returns the ASCII code for the given character
Returns the character for the given ASCII code
Returns the substring of length length at location location of the given string string.
Additionally, the following commands may be used:
Duplicate the named movie clip (aka sprite). The new movie clip has name name and is at depth depth.
Removes the named movie clip.
Write the given expression to the trace log. Doubtful that the browser plugin does anything with this.
Start dragging the movie clip target. The lock argument indicates whether to lock the mouse (?)- use 0 (FALSE) or 1 (TRUE). Optional parameters define a bounding area for the dragging.
Stop dragging my heart around. And this movie clip, too.
Call the named frame as a function.
Load the given URL into the named target. The target argument corresponds to HTML document targets (such as "_top" or "_blank"). The optional method argument can be POST or GET if you want to submit variables back to the server.
Load the given URL into the named target. The target argument can be a frame name (I think), or one of the magical values "_level0" (replaces current movie) or "_level1" (loads new movie on top of current movie).
Go to the next frame.
Go to the last (or, rather, previous) frame.
Start playing the movie.
Stop playing the movie.
Toggle between high and low quality.
Stop playing all sounds.
Go to frame number num. Frame numbers start at 0.
Go to the frame named name. Which does a lot of good, since I haven't added frame labels yet.
Sets the context for action. Or so they say- I really have no idea what this does.
Movie clips (all together now- aka sprites) have properties. You can read all of them (or can you?), you can set some of them, and here they are:
x
y
xScale
yScale
currentFrame - (read-only)
totalFrames - (read-only)
alpha - transparency level
visible - 1=on, 0=off (?)
width - (read-only)
height - (read-only)
rotation
target - (read-only) (???)
framesLoaded - (read-only)
name
dropTarget - (read-only) (???)
url - (read-only) (???)
highQuality - 1=high, 0=low (?)
focusRect - (???)
soundBufTime - (???)
This simple example will move the red square across the window.
Esempio 1. swfaction() example
|
This simple example tracks down your mouse on the screen.
Esempio 2. swfaction() example
|
Same as above, but with nice colored balls...
Esempio 3. swfaction() example
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbitmap->getheight() returns the bitmap's height in pixels.
See also swfbitmap->getwidth().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbitmap->getwidth() returns the bitmap's width in pixels.
See also swfbitmap->getheight().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbitmap() creates a new SWFBitmap object from the Jpeg or DBL file 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
|
And you can put an alpha mask on a jpeg fill.
Esempio 2. swfbitmap() example
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbutton->addaction() adds the action action to this button for the given conditions. The following flags are valid: SWFBUTTON_MOUSEOVER, SWFBUTTON_MOUSEOUT, SWFBUTTON_MOUSEUP, SWFBUTTON_MOUSEUPOUTSIDE, SWFBUTTON_MOUSEDOWN, SWFBUTTON_DRAGOUT and SWFBUTTON_DRAGOVER.
See also swfbutton->addshape() and swfaction().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbutton->addshape() adds the shape shape to this button. The following flags' values are valid: SWFBUTTON_UP, SWFBUTTON_OVER, SWFBUTTON_DOWN or SWFBUTTON_HIT. SWFBUTTON_HIT isn't ever displayed, it defines the hit region for the button. That is, everywhere the hit shape would be drawn is considered a "touchable" part of the button.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbutton->setaction() sets the action to be performed when the button is clicked. Alias for addAction(shape, SWFBUTTON_MOUSEUP). action is a swfaction().
See also swfbutton->addshape() and swfaction().
(no version information, might be only in CVS)
SWFbutton->setdown -- Alias for addShape(shape, SWFBUTTON_DOWN)Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbutton->setdown() alias for addShape(shape, SWFBUTTON_DOWN).
See also swfbutton->addshape() and swfaction().
(no version information, might be only in CVS)
SWFbutton->setHit -- Alias for addShape(shape, SWFBUTTON_HIT)Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbutton->sethit() alias for addShape(shape, SWFBUTTON_HIT).
See also swfbutton->addshape() and swfaction().
(no version information, might be only in CVS)
SWFbutton->setOver -- Alias for addShape(shape, SWFBUTTON_OVER)Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbutton->setover() alias for addShape(shape, SWFBUTTON_OVER).
See also swfbutton->addshape() and swfaction().
(no version information, might be only in CVS)
SWFbutton->setUp -- Alias for addShape(shape, SWFBUTTON_UP)Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbutton->setup() alias for addShape(shape, SWFBUTTON_UP).
See also swfbutton->addshape() and swfaction().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbutton() creates a new Button. Roll over it, click it, see it call action code. Swank.
SWFButton has the following methods : swfbutton->addshape(), swfbutton->setup(), swfbutton->setover() swfbutton->setdown(), swfbutton->sethit() swfbutton->setaction() and swfbutton->addaction().
This simple example will show your usual interactions with buttons : rollover, rollon, mouseup, mousedown, noaction.
Esempio 1. swfbutton() example
|
This simple example will enables you to drag draw a big red button on the windows. No drag-and-drop, just moving around.
Esempio 2. swfbutton->addaction() example
|
(no version information, might be only in CVS)
SWFDisplayItem->addColor -- Adds the given color to this item's color transform.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->addcolor() adds the color to this item's color transform. The color is given in its RGB form.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
(no version information, might be only in CVS)
SWFDisplayItem->move -- Moves object in relative coordinates.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->move() moves the current object by (dx,dy) from its current position.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->moveto().
(no version information, might be only in CVS)
SWFDisplayItem->moveTo -- Moves object in global coordinates.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->moveto() moves the current object to (x,y) in global coordinates.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->move().
(no version information, might be only in CVS)
SWFDisplayItem->multColor -- Multiplies the item's color transform.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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
|
(no version information, might be only in CVS)
SWFDisplayItem->remove -- Removes the object from the movieAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->remove() removes this object from the movie's display list.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfmovie->add().
(no version information, might be only in CVS)
SWFDisplayItem->Rotate -- Rotates in relative coordinates.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->rotate() rotates the current object by ddegrees degrees from its current rotation.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->rotateto().
(no version information, might be only in CVS)
SWFDisplayItem->rotateTo -- Rotates the object in global coordinates.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->rotateto() set the current object rotation to degrees degrees in global coordinates.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
This example bring three rotating string from the background to the foreground. Pretty nice.
Esempio 1. swfdisplayitem->rotateto() example
|
See also swfdisplayitem->rotate().
(no version information, might be only in CVS)
SWFDisplayItem->scale -- Scales the object in relative coordinates.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->scale() scales the current object by (dx,dy) from its current size.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->scaleto().
(no version information, might be only in CVS)
SWFDisplayItem->scaleTo -- Scales the object in global coordinates.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->scaleto() scales the current object to (x,y) in global coordinates.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->scale().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->setname() sets the object's name to name, for targetting with action script. Only useful on sprites.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->setratio() sets the object's ratio to ratio. Obviously only useful for morphs.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
This simple example will morph nicely three concentric circles.
Esempio 1. swfdisplayitem->setname() example
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->skewx() adds ddegrees to current x-skew.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->skewx(), swfdisplayitem->skewy() and swfdisplayitem->skewyto().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->skewxto() sets the x-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is more forward, less is more backward.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->skewx(), swfdisplayitem->skewy() and swfdisplayitem->skewyto().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->skewy() adds ddegrees to current y-skew.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->skewyto(), swfdisplayitem->skewx() and swfdisplayitem->skewxto().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->skewyto() sets the y-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is more upward, less is more downward.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->skewy(), swfdisplayitem->skewx() and swfdisplayitem->skewxto().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem() creates a new swfdisplayitem object.
Here's where all the animation takes place. After you define a shape, a text object, a sprite, or a button, you add it to the movie, then use the returned handle to move, rotate, scale, or skew the thing.
SWFDisplayItem has the following methods : swfdisplayitem->move(), swfdisplayitem->moveto(), swfdisplayitem->scaleto(), swfdisplayitem->scale(), swfdisplayitem->rotate(), swfdisplayitem->rotateto(), swfdisplayitem->skewxto(), swfdisplayitem->skewx(), swfdisplayitem->skewyto() swfdisplayitem->skewyto(), swfdisplayitem->setdepth() swfdisplayitem->remove(), swfdisplayitem->setname() swfdisplayitem->setratio(), swfdisplayitem->addcolor() and swfdisplayitem->multcolor().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swffill->moveto() moves fill's origin to (x,y) in global coordinates.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swffill->rotateto() sets fill's rotation to degrees degrees.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swffill->scaleto() sets fill's scale to x in the x-direction, y in the y-direction.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swffill->skewxto() sets fill x-skew to x. For x is 1.0, it is a 45-degree forward slant. More is more forward, less is more backward.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swffill->skewyto() sets fill y-skew to y. For y is 1.0, it is a 45-degree upward slant. More is more upward, less is more downward.
The swffill() object allows you to transform (scale, skew, rotate) bitmap and gradient fills. swffill() objects are created by the swfshape->addfill() methods.
SWFFill has the following methods : swffill->moveto() and swffill->scaleto(), swffill->rotateto(), swffill->skewxto() and swffill->skewyto().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swffont->getwidth() returns the string string's width, using font's default scaling. You'll probably want to use the swftext() version of this method which uses the text object's scale.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
If filename is the name of an FDB file (i.e., it ends in ".fdb"), load the font definition found in said file. Otherwise, create a browser-defined font reference.
FDB ("font definition block") is a very simple wrapper for the SWF DefineFont2 block which contains a full description of a font. One may create FDB files from SWT Generator template files with the included makefdb utility- look in the util directory off the main ming distribution directory.
Browser-defined fonts don't contain any information about the font other than its name. It is assumed that the font definition will be provided by the movie player. The fonts _serif, _sans, and _typewriter should always be available. For example:
<?php $f = newSWFFont("_sans"); ?> |
swffont() returns a reference to the font definition, for use in the swftext->setfont() and the swftextfield->setfont() methods.
SWFFont has the following methods : swffont->getwidth().
(no version information, might be only in CVS)
SWFGradient->addEntry -- Adds an entry to the gradient list.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfgradient->addentry() adds an entry to the gradient list. ratio is a number between 0 and 1 indicating where in the gradient this color appears. Thou shalt add entries in order of increasing ratio.
red, green, blue is a color (RGB mode). Last parameter a is optional.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfgradient() creates a new SWFGradient object.
After you've added the entries to your gradient, you can use the gradient in a shape fill with the swfshape->addfill() method.
SWFGradient has the following methods : swfgradient->addentry().
This simple example will draw a big black-to-white gradient as background, and a reddish disc in its center.
Esempio 1. swfgradient() example
|
(no version information, might be only in CVS)
SWFMorph->getshape1 -- Gets a handle to the starting shapeAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmorph->getshape1() gets a handle to the morph's starting shape. swfmorph->getshape1() returns an swfshape() object.
(no version information, might be only in CVS)
SWFMorph->getshape2 -- Gets a handle to the ending shapeAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmorph->getshape2() gets a handle to the morph's ending shape. swfmorph->getshape2() returns an swfshape() object.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmorph() creates a new SWFMorph object.
Also called a "shape tween". This thing lets you make those tacky twisting things that make your computer choke. Oh, joy!
The methods here are sort of weird. It would make more sense to just have newSWFMorph(shape1, shape2);, but as things are now, shape2 needs to know that it's the second part of a morph. (This, because it starts writing its output as soon as it gets drawing commands- if it kept its own description of its shapes and wrote on completion this and some other things would be much easier.)
SWFMorph has the following methods : swfmorph->getshape1() and swfmorph->getshape1().
This simple example will morph a big red square into a smaller blue black-bordered square.
Esempio 1. swfmorph() example
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->add() adds instance to the current movie. instance is any type of data : Shapes, text, fonts, etc. must all be added to the movie to make this work.
For displayable types (shape, text, button, sprite), this returns an swfdisplayitem(), a handle to the object in a display list. Thus, you can add the same shape to a movie multiple times and get separate handles back for each separate instance.
See also all other objects (adding this later), and swfmovie->remove()
See examples in : swfdisplayitem->rotateto() and swfshape->addfill().
(no version information, might be only in CVS)
SWFMovie->nextframe -- Moves to the next frame of the animation.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->nextframe() moves to the next frame of the animation.
(no version information, might be only in CVS)
SWFMovie->output -- Dumps your lovingly prepared movie out.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->output() dumps your lovingly prepared movie out. In PHP, preceding this with the command
<?php header('Content-type: application/x-shockwave-flash'); ?> |
The compression level can be a value between 0 and 9, defining the swf compression similar to gzip compression.
See also swfmovie->save().
See examples in : swfmovie->streammp3(), swfdisplayitem->rotateto(), swfaction()... Any example will use this method.
(no version information, might be only in CVS)
swfmovie->remove -- Removes the object instance from the display list.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->remove() removes the object instance instance from the display list.
See also swfmovie->add().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->save() saves your movie to the file named filename.
The compression level can be a value between 0 and 9, defining the swf compression similar to gzip compression.
See also swfmovie->output().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->setbackground() sets the background color. Why is there no rgba version? Think about it. (Actually, that's not such a dumb question after all- you might want to let the HTML background show through. There's a way to do that, but it only works on IE4. Search the http://www.macromedia.com/ site for details.)
(no version information, might be only in CVS)
SWFMovie->setdimension -- Sets the movie's width and 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.
(no version information, might be only in CVS)
SWFMovie->setframes -- Sets the total number of frames in the animation.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->setframes() sets the total number of frames in the animation to numberofframes.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->setrate() sets the frame rate to rate, in frame per seconds. Animation will slow down if the player can't render frames fast enough- unless there's a streaming sound, in which case display frames are sacrificed to keep sound from skipping.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->streammp3() streams the mp3 file 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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie() creates a new movie object, representing an SWF version 4 movie.
SWFMovie has the following methods : swfmovie->output(),swfmovie->save(), swfmovie->add(), swfmovie->remove(), swfmovie->nextframe(), swfmovie->setbackground(), swfmovie->setrate(), swfmovie->setdimension(), swfmovie->setframes() and swfmovie->streammp3().
See examples in : swfdisplayitem->rotateto(), swfshape->setline(), swfshape->addfill()... Any example will use this object.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfshape->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
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfshape->drawline() draws a line (using the current line style set by swfshape->setline()) from the current pen position to displacement (dx,dy).
See also swfshape->movepento(), swfshape->drawcurveto(), swfshape->movepen() and swfshape->drawlineto().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfshape->setrightfill() draws a line (using the current line style, set by swfshape->setline()) from the current pen position to point (x,y) in the shape's coordinate space.
See also swfshape->movepento(), swfshape->drawcurveto(), swfshape->movepen() and swfshape->drawline().
(no version information, might be only in CVS)
SWFShape->movePen -- Moves the shape's pen (relative).Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfshape->setrightfill() move the shape's pen from coordinates (current x,current y) to (current x + dx, current y + dy) in the shape's coordinate space.
See also swfshape->movepento(), swfshape->drawcurveto(), swfshape->drawlineto() and swfshape->drawline().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfshape->setrightfill() move the shape's pen to (x,y) in the shape's coordinate space.
See also swfshape->movepen(), swfshape->drawcurveto(), swfshape->drawlineto() and swfshape->drawline().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
What this nonsense is about is, every edge segment borders at most two fills. When rasterizing the object, it's pretty handy to know what those fills are ahead of time, so the swf format requires these to be specified.
swfshape->setleftfill() sets the fill on the left side of the edge- that is, on the interior if you're defining the outline of the shape in a counter-clockwise fashion. The fill object is an SWFFill object returned from one of the addFill functions above.
This seems to be reversed when you're defining a shape in a morph, though. If your browser crashes, just try setting the fill on the other side.
Shortcut for swfshape->setleftfill($s->addfill($r, $g, $b [, $a]));.
See also swfshape->setrightfill().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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
|
(no version information, might be only in CVS)
SWFShape->setRightFill -- Sets right rasterizing color.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
See also swfshape->setleftfill().
Shortcut for swfshape->setrightfill($s->addfill($r, $g, $b [, $a]));.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfshape() creates a new shape object.
SWFShape has the following methods : swfshape->setline(), swfshape->addfill(), swfshape->setleftfill(), swfshape->setrightfill(), swfshape->movepento(), swfshape->movepen(), swfshape->drawlineto(), swfshape->drawline(), swfshape->drawcurveto() and swfshape->drawcurve().
This simple example will draw a big red elliptic quadrant.
Esempio 1. swfshape() example
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfsprite->add() adds a swfshape(), a swfbutton(), a swftext(), a swfaction() or a swfsprite() object.
For displayable types (swfshape(), swfbutton(), swftext(), swfaction() or swfsprite()), this returns a handle to the object in a display list.
(no version information, might be only in CVS)
SWFSprite->nextframe -- Moves to the next frame of the animation.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfsprite->setframes() moves to the next frame of the animation.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfsprite->remove() remove a swfshape(), a swfbutton(), a swftext(), a swfaction() or a swfsprite() object from the sprite.
(no version information, might be only in CVS)
SWFSprite->setframes -- Sets the total number of frames in the animation.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfsprite->setframes() sets the total number of frames in the animation to numberofframes.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfsprite() are also known as a "movie clip", this allows one to create objects which are animated in their own timelines. Hence, the sprite has most of the same methods as the movie.
swfsprite() has the following methods : swfsprite->add(), swfsprite->remove(), swfsprite->nextframe() and swfsprite->setframes().
This simple example will spin gracefully a big red square.
Esempio 1. swfsprite() example
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext->addstring() draws the string string at the current pen (cursor) location. Pen is at the baseline of the text; i.e., ascending text is in the -y direction.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext->addstring() returns the rendered width of the string string at the text object's current font, scale, and spacing settings.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext->moveto() moves the pen (or cursor, if that makes more sense) to (x,y) in text object's coordinate space. If either is zero, though, value in that dimension stays the same. Annoying, should be fixed.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext->setspacing() changes the current text color. Default is black. I think. Color is represented using the RGB system.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext->setfont() sets the current font to font.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext->setheight() sets the current font height to height. Default is 240.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext->setspacing() sets the current font spacing to spacingspacing. Default is 1.0. 0 is all of the letters written at the same point. This doesn't really work that well because it inflates the advance across the letter, doesn't add the same amount of spacing between the letters. I should try and explain that better, prolly. Or just fix the damn thing to do constant spacing. This was really just a way to figure out how letter advances work, anyway.. So nyah.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext() creates a new SWFText object, fresh for manipulating.
SWFText has the following methods : swftext->setfont(), swftext->setheight(), swftext->setspacing(), swftext->setcolor(), swftext->moveto(), swftext->addstring() and swftext->getwidth().
This simple example will draw a big yellow "PHP generates Flash with Ming" text, on white background.
Esempio 1. swftext() example
|
(no version information, might be only in CVS)
SWFTextField->addstring -- Concatenates the given string to the text fieldAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setname() concatenates the string string to the text field.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->align() sets the text field alignment to alignement. Valid values for alignement are : SWFTEXTFIELD_ALIGN_LEFT, SWFTEXTFIELD_ALIGN_RIGHT, SWFTEXTFIELD_ALIGN_CENTER and SWFTEXTFIELD_ALIGN_JUSTIFY.
(no version information, might be only in CVS)
SWFTextField->setbounds -- Sets the text field width and heightAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setbounds() sets the text field width to width and height to height. If you don't set the bounds yourself, Ming makes a poor guess at what the bounds are.
(no version information, might be only in CVS)
SWFTextField->setcolor -- Sets the color of the text field.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setcolor() sets the color of the text field. Default is fully opaque black. Color is represented using RGB system.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setfont() sets the text field font to the [browser-defined?] font font.
(no version information, might be only in CVS)
SWFTextField->setHeight -- Sets the font height of this text field 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->setheight() sets the font height of this text field font to the given height height. Default is 240.
(no version information, might be only in CVS)
SWFTextField->setindentation -- Sets the indentation of the first line.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setindentation() sets the indentation of the first line in the text field, to width.
(no version information, might be only in CVS)
SWFTextField->setLeftMargin -- Sets the left margin width of the text field.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setleftmargin() sets the left margin width of the text field to width. Default is 0.
(no version information, might be only in CVS)
SWFTextField->setLineSpacing -- Sets the line spacing of the text field.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setlinespacing() sets the line spacing of the text field to the height of height. Default is 40.
(no version information, might be only in CVS)
SWFTextField->setMargins -- Sets the margins width of the text field.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setmargins() set both margins at once, for the man on the go.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setname() sets the variable name of this text field to name, for form posting and action scripting purposes.
(no version information, might be only in CVS)
SWFTextField->setrightMargin -- Sets the right margin width of the text field.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setrightmargin() sets the right margin width of the text field to width. Default is 0.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield() creates a new text field object. Text Fields are less flexible than swftext() objects- they can't be rotated, scaled non-proportionally, or skewed, but they can be used as form entries, and they can use browser-defined fonts.
The optional flags change the text field's behavior. It has the following possibles values :
SWFTEXTFIELD_DRAWBOX draws the outline of the textfield
SWFTEXTFIELD_HASLENGTH
SWFTEXTFIELD_HTML allows text markup using HTML-tags
SWFTEXTFIELD_MULTILINE allows multiple lines
SWFTEXTFIELD_NOEDIT indicates that the field shouldn't be user-editable
SWFTEXTFIELD_NOSELECT makes the field non-selectable
SWFTEXTFIELD_PASSWORD obscures the data entry
SWFTEXTFIELD_WORDWRAP allows text to wrap
<?php $t = newSWFTextField(SWFTEXTFIELD_PASSWORD | SWFTEXTFIELD_NOEDIT); ?> |
SWFTextField has the following methods : swftextfield->setfont(), swftextfield->setbounds(), swftextfield->align(), swftextfield->setheight(), swftextfield->setleftmargin(), swftextfield->setrightmargin(), swftextfield->setmargins(), swftextfield->setindentation(), swftextfield->setlinespacing(), swftextfield->setcolor(), swftextfield->setname() and swftextfield->addstring().
These functions were placed here because none of the other categories seemed to fit.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Misc. Configuration Options
Name | Default | Changeable |
---|---|---|
ignore_user_abort | "0" | PHP_INI_ALL |
highlight.string | #DD0000 | PHP_INI_ALL |
highlight.comment | #FF9900 | PHP_INI_ALL |
highlight.keyword | #007700 | PHP_INI_ALL |
highlight.bg | #FFFFFF | PHP_INI_ALL |
highlight.default | #0000BB | PHP_INI_ALL |
highlight.html | #000000 | PHP_INI_ALL |
browscap | NULL | PHP_INI_SYSTEM |
Breve descrizione dei parametri di configurazione.
TRUE by default. If changed to FALSE scripts will be terminated as soon as they try to output something after a client has aborted their connection.
See also ignore_user_abort().
Colors for Syntax Highlighting mode. Anything that's acceptable in <font color="??????"> would work.
Name (e.g.: browscap.ini) and location of browser capabilities file. See also get_browser().
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Returns TRUE if client disconnected. See the Connection Handling description in the Features chapter for a complete explanation.
See also connection_status(), and ignore_user_abort().
Returns the connection status bitfield. See the Connection Handling description in the Features chapter for a complete explanation.
See also connection_aborted(), and ignore_user_abort().
Returns TRUE if script timed out.
Deprecated |
This function is deprecated, and doesn't even exist anymore as of 4.0.5. |
See the Connection Handling description in the Features chapter for a complete explanation.
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.
Defines a named constant. See the section on constants for more details.
The name of the constant is given by name; the value is given by value.
The optional third parameter case_insensitive is also available. If the value TRUE is given, then the constant will be defined case-insensitive. The default behaviour is case-sensitive; i.e. CONSTANT and Constant represent different values.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also defined(), constant() and the section on Constants.
Returns TRUE if the named constant given by name has been defined, FALSE otherwise.
Nota: If you want to see if a variable exists, use isset() as defined() only applies to constants. If you want to see if a function exists, use function_exists().
See also define(), constant(), get_defined_constants(), function_exists(), and the section on Constants.
eval() evaluates the string given in code_str as PHP code. Among other things, this can be useful for storing code in a database text field for later execution.
There are some factors to keep in mind when using eval(). Remember that the string passed must be valid PHP code, including things like terminating statements with a semicolon so the parser doesn't die on the line after the eval(), and properly escaping things in code_str.
Also remember that variables given values under eval() will retain these values in the main script afterwards.
A return statement will terminate the evaluation of the string immediately. 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
The above example will show:
|
Suggerimento: Come con qualsiasi cosa che invia il risultato direttamente al browser, è possibile utilizzare la funzione output-control per catturare l'uscita di questa funzione e salvarla - per esempio - in una stringa.
See also call_user_func().
Nota: This is not a real function, but a language construct.
Nota: PHP >= 4.2.0 does NOT print the status if it is an integer.
The exit() function terminates execution of the script. It prints status just before exiting.
If status is an integer, that value will also be used as the exit status. Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully.
Nota: The die() function is an alias for exit().
See also: register_shutdown_function().
get_browser() attempts to determine the capabilities of the user's browser. This is done by looking up the browser's information in the browscap.ini file. By default, the value of $_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
The output of the above script would look something like this:
|
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'].
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
And then make a file named source and put it in your web root directory.
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.
|
See also highlight_string().
The highlight_string() function outputs a syntax highlighted version of str using the colors defined in the built-in syntax highlighter for PHP.
If the second parameter return is set to TRUE then highlight_string() will return the highlighted code as a string instead of printing it out. If the second parameter is not set to TRUE then highlight_string() will return TRUE on success, FALSE on failure.
Esempio 1. highlight_string() example
The above example will output (in PHP 4):
The above example will output (in PHP 5):
|
Nota: The return parameter became available in PHP 4.2.0. Before this time it behaved like the default, which is FALSE
See also highlight_file().
(PHP 3>= 3.0.7, PHP 4 , PHP 5)
ignore_user_abort -- Set whether a client disconnect should abort script executionThis function sets whether a client disconnect should cause a script to be aborted. It will return the previous setting and can be called without an argument to not change the current setting and only return the current setting. See the Connection Handling section in the Features chapter for a complete description of connection handling in PHP.
See also connection_aborted(), and connection_status().
Pack given arguments into binary string according to format. Returns binary string containing data.
The idea to this function was taken from Perl and all formatting codes work the same as there, however, there are some formatting codes that are missing such as Perl's "u" format code. The format string consists of format codes followed by an optional repeater argument. The repeater argument can be either an integer value or * for repeating to the end of the input data. For a, A, h, H the repeat count specifies how many characters of one data argument are taken, for @ it is the absolute position where to put the next data, for everything else the repeat count specifies how many data arguments are consumed and packed into the resulting binary string. Currently implemented are
Tabella 1. pack() format characters
Code | Description |
---|---|
a | NUL-padded string |
A | SPACE-padded string |
h | Hex string, low nibble first |
H | Hex string, high nibble first |
c | signed char |
C | unsigned char |
s | signed short (always 16 bit, machine byte order) |
S | unsigned short (always 16 bit, machine byte order) |
n | unsigned short (always 16 bit, big endian byte order) |
v | unsigned short (always 16 bit, little endian byte order) |
i | signed integer (machine dependent size and byte order) |
I | unsigned integer (machine dependent size and byte order) |
l | signed long (always 32 bit, machine byte order) |
L | unsigned long (always 32 bit, machine byte order) |
N | unsigned long (always 32 bit, big endian byte order) |
V | unsigned long (always 32 bit, little endian byte order) |
f | float (machine dependent size and representation) |
d | double (machine dependent size and representation) |
x | NUL byte |
X | Back up one byte |
@ | NUL-fill to absolute position |
Note that the distinction between signed and unsigned values only affects the function unpack(), where as function pack() gives the same result for signed and unsigned format codes.
Also note that PHP internally stores integer values as signed values of a machine dependent size. If you give it an unsigned integer value too large to be stored that way it is converted to a float which often yields an undesired result.
See also unpack().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
The sleep() function delays program execution for the given number of seconds.
See also usleep() and set_time_limit()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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() from binary string into array according to format. Returns array containing unpacked elements of binary string.
unpack() works slightly different from Perl as the unpacked data is stored in an associative array. To accomplish this you have to name the different format codes and separate them by a slash /.
Attenzione |
Note that PHP internally stores integral values as signed. If you unpack a large unsigned long and it is of the same size as PHP internally stored values the result will be a negative number even though unsigned unpacking was specified. |
See also pack() for an explanation of the format codes.
The usleep() function delays program execution for the given number of micro_seconds. A microsecond is one millionth of a second.
Nota: This function did not work on Windows systems until PHP 5.0.0
See also sleep() and set_time_limit().
These functions allow you to access the mnoGoSearch (former UdmSearch) free search engine. mnoGoSearch is a full-featured search engine software for intranet and internet servers, distributed under the GNU license. mnoGoSearch has a number of unique features, which makes it appropriate for a wide range of applications from search within your site to a specialized search system such as cooking recipes or newspaper search, FTP archive search, news articles search, etc. It offers full-text indexing and searching for HTML, PDF, and text documents. mnoGoSearch consists of two parts. The first is an indexing mechanism (indexer). The purpose of the indexer is to walk through HTTP, FTP, NEWS servers or local files, recursively grabbing all the documents and storing meta-data about that documents in a SQL database in a smart and effective manner. After every document is referenced by its corresponding URL, meta-data is collected by the indexer for later use in a search process. The search is performed via Web interface. C, CGI, PHP and Perl search front ends are included.
More information about mnoGoSearch can be found at http://www.mnogosearch.ru/.
Nota: Questo modulo non è disponibile su piattaforme Windows.
Download mnoGosearch from http://www.mnogosearch.ru/ and install it on your system. You need at least version 3.1.10 of mnoGoSearch installed to use these functions.
In order to have these functions available, you must compile PHP with mnoGosearch support by using the --with-mnogosearchoption. If you use this option without specifying the path to mnoGosearch, PHP will look for mnoGosearch under /usr/local/mnogosearch path by default. If you installed mnoGosearch at a different location you should specify it: --with-mnogosearch=DIR.
Nota: PHP contains built-in MySQL access library, which can be used to access MySQL. It is known that mnoGoSearch is not compatible with this built-in library and can work only with generic MySQL libraries. Thus, if you use mnoGoSearch with MySQL, during PHP configuration you have to indicate the directory of your MySQL installation, that was used during mnoGoSearch configuration, i.e. for example: --with-mnogosearch --with-mysql=/usr.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
udm_add_search_limit() adds search restrictions. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
agent - a link to Agent, received after call to udm_alloc_agent().
var - defines parameter, indicating limit.
val - defines the value of the current parameter.
Possible var values:
UDM_LIMIT_URL - defines document URL limitations to limit the search through subsection of the database. It supports SQL % and _ LIKE wildcards, where % matches any number of characters, even zero characters, and _ matches exactly one character. E.g. http://www.example.___/catalog may stand for http://www.example.com/catalog and http://www.example.net/catalog.
UDM_LIMIT_TAG - defines site TAG limitations. In indexer-conf you can assign specific TAGs to various sites and parts of a site. Tags in mnoGoSearch 3.1.x are lines, that may contain metasymbols % and _. Metasymbols allow searching among groups of tags. E.g. there are links with tags ABCD and ABCE, and search restriction is by ABC_ - the search will be made among both of the tags.
UDM_LIMIT_LANG - defines document language limitations.
UDM_LIMIT_CAT - defines document category limitations. Categories are similar to tag feature, but nested. So you can have one category inside another and so on. You have to use two characters for each level. Use a hex number going from 0-F or a 36 base number going from 0-Z. Therefore a top-level category like 'Auto' would be 01. If it has a subcategory like 'Ford', then it would be 01 (the parent category) and then 'Ford' which we will give 01. Put those together and you get 0101. If 'Auto' had another subcategory named 'VW', then it's id would be 01 because it belongs to the 'Ford' category and then 02 because it's the next category. So it's id would be 0102. If VW had a sub category called 'Engine' then it's id would start at 01 again and it would get the 'VW' id 02 and 'Auto' id of 01, making it 010201. If you want to search for sites under that category then you pass it cat=010201 in the URL.
UDM_LIMIT_DATE - defines limitation by date the document was modified.
Format of parameter value: a string with first character < or >, then with no space - date in unixtime format, for example:
If > character is used, then the search will be restricted to those documents having a modification date greater than entered, if <, then smaller.
udm_alloc_agent_array() will create an agent with multiple database connections. The array databases must contain one database URL per element, analog to the first parameter of udm_alloc_agent().
See also: udm_alloc_agent().
Returns a mnogosearch agent identifier on success, FALSE on failure. This function creates a session with database parameters.
dbaddr - URL-style database description, with options (type, host, database name, port, user and password) to connect to SQL database. Do not matter for built-in text files support. Format for dbaddr: DBType:[//[DBUser[:DBPass]@]DBHost[:DBPort]]/DBName/. Currently supported DBType values are: mysql, pgsql, msql, solid, mssql, oracle, and ibase. Actually, it does not matter for native libraries support, but ODBC users should specify one of the supported values. If your database type is not supported, you may use unknown instead.
dbmode - You may select the SQL database mode of words storage. Possible values of dbmode are: single, multi, crc, or crc-multi. When single is specified, all words are stored in the same table. If multi is selected, words will be located in different tables depending of their lengths. "multi" mode is usually faster, but requires more tables in the database. If "crc" mode is selected, mnoGoSearch will store 32 bit integer word IDs calculated by CRC32 algorithm instead of words. This mode requires less disk space and it is faster comparing with "single" and "multi" modes. crc-multi uses the same storage structure with the "crc" mode, but also stores words in different tables depending on words lengths like in "multi" mode.
Nota: dbaddr and dbmode must match those used during indexing.
Nota: In fact this function does not open a connection to the database and thus does not check the entered login and password. Establishing a connection to the database and login/password verification is done by udm_find().
udm_api_version() returns the mnoGoSearch API version number. E.g. if mnoGoSearch 3.1.10 API is used, this function will return 30110.
This function allows the user to identify which API functions are available, e.g. udm_get_doc_count() function is only available in mnoGoSearch 3.1.11 or later.
(PHP 4 >= 4.0.6, PHP 5)
udm_cat_list -- Get all the categories on the same level with the current one.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 ... |
See also udm_cat_path().
Returns an array describing the path in the categories tree from the tree root to the current one, specified by category. agent is the agent identifier returned by a previous call to >udm_alloc_agent().
The returned array consists of pairs. Elements with even index numbers contain the category paths, odd elements contain the corresponding category names.
For example, the call $array=udm_cat_path($agent, '02031D'); may return the following array:
$array[0] will contain '' $array[1] will contain 'Root' $array[2] will contain '02' $array[3] will contain 'Sport' $array[4] will contain '0203' $array[5] will contain 'Auto' $array[4] will contain '02031D' $array[5] will contain 'Ferrari' |
Esempio 1. Specifying path to the current category in the following format: '> Root > Sport > Auto > Ferrari'
|
See also udm_cat_list().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
udm_clear_search_limits() resets defined search limitations and returns TRUE.
See also udm_add_search_limit().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
udm_errno() returns mnoGoSearch error number, zero if no error.
agent - link to agent identifier, received after call to udm_alloc_agent().
Receiving numeric agent error code.
udm_error() returns mnoGoSearch error message, empty string if no error.
agent - link to agent identifier, received after call to udm_alloc_agent().
Receiving agent error message.
Returns a result link identifier on success, or FALSE on failure.
The search itself. The first argument - session, the next one - query itself. To find something just type words you want to find and press SUBMIT button. For example, "mysql odbc". You should not use quotes " in query, they are written here only to divide a query from other text. mnoGoSearch will find all documents that contain word "mysql" and/or word "odbc". Best documents having bigger weights will be displayed first. If you use search mode ALL, search will return documents that contain both (or more) words you entered. In case you use mode ANY, the search will return list of documents that contain any of the words you entered. If you want more advanced results you may use query language. You should select "bool" match mode in the search from.
mnoGoSearch understands the following boolean operators:
& - logical AND. For example, "mysql & odbc". mnoGoSearch will find any URLs that contain both "mysql" and "odbc".
| - logical OR. For example "mysql|odbc". mnoGoSearch will find any URLs, that contain word "mysql" or word "odbc".
~ - logical NOT. For example "mysql & ~odbc". mnoGoSearch will find URLs that contain word "mysql" and do not contain word "odbc" at the same time. Note that ~ just excludes given word from results. Query "~odbc" will find nothing!
() - group command to compose more complex queries. For example "(mysql | msql) & ~postgres". Query language is simple and powerful at the same time. Just consider query as usual boolean expression.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
agent - link to agent identifier, received ` after call to udm_alloc_agent().
Freeing up memory allocated for agent session.
udm_free_ispell_data() always returns TRUE.
agent - agent link identifier, received after call to udm_alloc_agent().
Nota: This function is supported beginning from version 3.1.12 of mnoGoSearch and it does not do anything in previous versions.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
res - a link to result identifier, received after call to udm_find().
Freeing up memory allocated for results.
udm_get_doc_count() returns the number of documents in the database.
agent - link to agent identifier, received after call to udm_alloc_agent().
Nota: This function is supported only in mnoGoSearch 3.1.11 or later.
udm_get_res_field() returns result field value on success, FALSE on error.
res - a link to result identifier, received after call to udm_find().
row - the number of the link on the current page. May have values from 0 to UDM_PARAM_NUM_ROWS-1.
field - field identifier, may have the following values:
UDM_FIELD_URL - document URL field
UDM_FIELD_CONTENT - document Content-type field (for example, text/html).
UDM_FIELD_CATEGORY - document category field. Use udm_cat_path() to get full path to current category from the categories tree root. (This parameter is available only in PHP 4.0.6 or later).
UDM_FIELD_TITLE - document title field.
UDM_FIELD_KEYWORDS - document keywords field (from META KEYWORDS tag).
UDM_FIELD_DESC - document description field (from META DESCRIPTION tag).
UDM_FIELD_TEXT - document body text (the first couple of lines to give an idea of what the document is about).
UDM_FIELD_SIZE - document size.
UDM_FIELD_URLID - unique URL ID of the link.
UDM_FIELD_RATING - page rating (as calculated by mnoGoSearch).
UDM_FIELD_MODIFIED - last-modified field in unixtime format.
UDM_FIELD_ORDER - the number of the current document in set of found documents.
UDM_FIELD_CRC - document CRC.
udm_get_res_param() returns result parameter value on success, FALSE on error.
res - a link to result identifier, received after call to udm_find().
param - parameter identifier, may have the following values:
UDM_PARAM_NUM_ROWS - number of received found links on the current page. It is equal to UDM_PARAM_PAGE_SIZE for all search pages, on the last page - the rest of links.
UDM_PARAM_FOUND - total number of results matching the query.
UDM_PARAM_WORDINFO - information on the words found. E.g. search for "a good book" will return "a: stopword, good:5637, book: 120"
UDM_PARAM_SEARCHTIME - search time in seconds.
UDM_PARAM_FIRST_DOC - the number of the first document displayed on current page.
UDM_PARAM_LAST_DOC - the number of the last document displayed on current page.
udm_hash32() will take a string str and return a quite unique 32-bit hash number from it. Requires an allocated agent.
See also: udm_alloc_agent().
udm_load_ispell_data() loads ispell data. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
agent - agent link identifier, received after call to udm_alloc_agent().
var - parameter, indicating the source for ispell data. May have the following values:
After using this function to free memory allocated for ispell data, please use udm_free_ispell_data(), even if you use UDM_ISPELL_TYPE_SERVER mode.
The fastest mode is UDM_ISPELL_TYPE_SERVER. UDM_ISPELL_TYPE_TEXT is slower and UDM_ISPELL_TYPE_DB is the slowest. The above pattern is TRUE for mnoGoSearch 3.1.10 - 3.1.11. It is planned to speed up DB mode in future versions and it is going to be faster than TEXT mode.
UDM_ISPELL_TYPE_DB - indicates that ispell data should be loaded from SQL. In this case, parameters val1 and val2 are ignored and should be left blank. flag should be equal to 1.
Nota: flag indicates that after loading ispell data from defined source it should be sorted (it is necessary for correct functioning of ispell). In case of loading ispell data from files there may be several calls to udm_load_ispell_data(), and there is no sense to sort data after every call, but only after the last one. Since in db mode all the data is loaded by one call, this parameter should have the value 1. In this mode in case of error, e.g. if ispell tables are absent, the function will return FALSE and code and error message will be accessible through udm_error() and udm_errno().
UDM_ISPELL_TYPE_AFFIX - indicates that ispell data should be loaded from file and initiates loading affixes file. In this case val1 defines double letter language code for which affixes are loaded, and val2 - file path. Please note, that if a relative path entered, the module looks for the file not in UDM_CONF_DIR, but in relation to current path, i.e. to the path where the script is executed. In case of error in this mode, e.g. if file is absent, the function will return FALSE, and an error message will be displayed. Error message text cannot be accessed through udm_error() and udm_errno(), since those functions can only return messages associated with SQL. Please, see flag parameter description in UDM_ISPELL_TYPE_DB.
Esempio 2. udm_load_ispell_data() example
|
Nota: flag is equal to 1 only in the last call.
UDM_ISPELL_TYPE_SPELL - indicates that ispell data should be loaded from file and initiates loading of ispell dictionary file. In this case val1 defines double letter language code for which affixes are loaded, and val2 - file path. Please note, that if a relative path entered, the module looks for the file not in UDM_CONF_DIR, but in relation to current path, i.e. to the path where the script is executed. In case of error in this mode, e.g. if file is absent, the function will return FALSE, and an error message will be displayed. Error message text cannot be accessed through udm_error() and udm_errno(), since those functions can only return messages associated with SQL. Please, see flag parameter description in UDM_ISPELL_TYPE_DB.
<?php if ((! Udm_Load_Ispell_Data($udm, UDM_ISPELL_TYPE_AFFIX, 'en', '/opt/ispell/en.aff', 0)) || (! Udm_Load_Ispell_Data($udm, UDM_ISPELL_TYPE_AFFIX, 'ru', '/opt/ispell/ru.aff', 0)) || (! Udm_Load_Ispell_Data($udm, UDM_ISPELL_TYPE_SPELL, 'en', '/opt/ispell/en.dict', 0)) || (! Udm_Load_Ispell_Data($udm, UDM_ISPELL_TYPE_SPELL, 'ru', '/opt/ispell/ru.dict', 1))) { exit; } ?> |
Nota: flag is equal to 1 only in the last call.
UDM_ISPELL_TYPE_SERVER - enables spell server support. val1 parameter indicates address of the host running spell server. val2 ` is not used yet, but in future releases it is going to indicate number of port used by spell server. flag parameter in this case is not needed since ispell data is stored on spellserver already sorted.
Spelld server reads spell-data from a separate configuration file (/usr/local/mnogosearch/etc/spelld.conf by default), sorts it and stores in memory. With clients server communicates in two ways: to indexer all the data is transferred (so that indexer starts faster), from search.cgi server receives word to normalize and then passes over to client (search.cgi) list of normalized word forms. This allows fastest, compared to db and text modes processing of search queries (by omitting loading and sorting all the spell data).
udm_load_ispell_data() function in UDM_ISPELL_TYPE_SERVER mode does not actually load ispell data, but only defines server address. In fact, server is automatically used by udm_find() function when performing search. In case of errors, e.g. if spellserver is not running or invalid host indicated, there are no messages returned and ispell conversion does not work.
Nota: This function is available in mnoGoSearch 3.1.12 or later.
Example:
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. Defines mnoGoSearch session parameters.
The following parameters and their values are available:
UDM_PARAM_PAGE_NUM - used to choose search results page number (results are returned by pages beginning from 0, with UDM_PARAM_PAGE_SIZE results per page).
UDM_PARAM_PAGE_SIZE - number of search results displayed on one page.
UDM_PARAM_SEARCH_MODE - search mode. The following values available: UDM_MODE_ALL - search for all words; UDM_MODE_ANY - search for any word; UDM_MODE_PHRASE - phrase search; UDM_MODE_BOOL - boolean search. See udm_find() for details on boolean search.
UDM_PARAM_CACHE_MODE - turns on or off search result cache mode. When enabled, the search engine will store search results to disk. In case a similar search is performed later, the engine will take results from the cache for faster performance. Available values: UDM_CACHE_ENABLED, UDM_CACHE_DISABLED.
UDM_PARAM_TRACK_MODE - turns on or off trackquery mode. Since version 3.1.2 mnoGoSearch has a query tracking support. Note that tracking is implemented in SQL version only and not available in built-in database. To use tracking, you have to create tables for tracking support. For MySQL, use create/mysql/track.txt. When doing a search, front-end uses those tables to store query words, a number of found documents and current Unix timestamp in seconds. Available values: UDM_TRACK_ENABLED, UDM_TRACK_DISABLED.
UDM_PARAM_PHRASE_MODE - defines whether index database using phrases ("phrase" parameter in indexer.conf). Possible values: UDM_PHRASE_ENABLED and UDM_PHRASE_DISABLED. Please note, that if phrase search is enabled (UDM_PHRASE_ENABLED), it is still possible to do search in any mode (ANY, ALL, BOOL or PHRASE). In 3.1.10 version of mnoGoSearch phrase search is supported only in sql and built-in database modes, while beginning with 3.1.11 phrases are supported in cachemode as well.
Examples of phrase search:
"Arizona desert" - This query returns all indexed documents that contain "Arizona desert" as a phrase. Notice that you need to put double quotes around the phrase
UDM_PARAM_CHARSET - defines local charset. Available values: set of charsets supported by mnoGoSearch, e.g. koi8-r, cp1251, ...
UDM_PARAM_STOPFILE - Defines name and path to stopwords file. (There is a small difference with mnoGoSearch - while in mnoGoSearch if relative path or no path entered, it looks for this file in relation to UDM_CONF_DIR, the module looks for the file in relation to current path, i.e. to the path where the PHP script is executed.)
UDM_PARAM_STOPTABLE - Load stop words from the given SQL table. You may use several StopwordTable commands. This command has no effect when compiled without SQL database support.
UDM_PARAM_WEIGHT_FACTOR - represents weight factors for specific document parts. Currently body, title, keywords, description, url are supported. To activate this feature please use degrees of 2 in *Weight commands of the indexer.conf. Let's imagine that we have these weights:
URLWeight 1
BodyWeight 2
TitleWeight 4
KeywordWeight 8
DescWeight 16
As far as indexer uses bit OR operation for word weights when some word presents several time in the same document, it is possible at search time to detect word appearance in different document parts. Word which appears only in the body will have 00000010 aggregate weight (in binary notation). Word used in all document parts will have 00011111 aggregate weight.
This parameter's value is a string of hex digits ABCDE. Each digit is a factor for corresponding bit in word weight. For the given above weights configuration:
E is a factor for weight 1 (URL Weight bit)
D is a factor for weight 2 (BodyWeight bit)
C is a factor for weight 4 (TitleWeight bit)
B is a factor for weight 8 (KeywordWeight bit)
A is a factor for weight 16 (DescWeight bit)
Examples:
UDM_PARAM_WEIGHT_FACTOR=00001 will search through URLs only.
UDM_PARAM_WEIGHT_FACTOR=00100 will search through Titles only.
UDM_PARAM_WEIGHT_FACTOR=11100 will search through Title,Keywords,Description but not through URL and Body.
UDM_PARAM_WEIGHT_FACTOR=F9421 will search through:
Description with factor 15 (F hex)
Keywords with factor 9
Title with factor 4
Body with factor 2
URL with factor 1
If UDM_PARAM_WEIGHT_FACTOR variable is omitted, original weight value is taken to sort results. For a given above weight configuration it means that document description has a most big weight 16.
UDM_PARAM_WORD_MATCH - word match. You may use this parameter to choose word match type. This feature works only in "single" and "multi" modes using SQL based and built-in database. It does not work in cachemode and other modes since they use word CRC and do not support substring search. Available values:
UDM_MATCH_BEGIN - word beginning match;
UDM_MATCH_END - word ending match;
UDM_MATCH_WORD - whole word match;
UDM_MATCH_SUBSTR - word substring match.
UDM_PARAM_MIN_WORD_LEN - defines minimal word length. Any word shorter this limit is considered to be a stopword. Please note that this parameter value is inclusive, i.e. if UDM_PARAM_MIN_WORD_LEN=3, a word 3 characters long will not be considered a stopword, while a word 2 characters long will be. Default value is 1.
UDM_PARAM_ISPELL_PREFIXES - Possible values: UDM_PREFIXES_ENABLED and UDM_PREFIXES_DISABLED, that respectively enable or disable using prefixes. E.g. if a word "tested" is in search query, also words like "test", "testing", etc. Only suffixes are supported by default. Prefixes usually change word meanings, for example if somebody is searching for the word "tested" one hardly wants "untested" to be found. Prefixes support may also be found useful for site's spelling checking purposes. In order to enable ispell, you have to load ispell data with udm_load_ispell_data().
UDM_PARAM_CROSS_WORDS - enables or disables crosswords support. Possible values: UDM_CROSS_WORDS_ENABLED and UDM_CROSS_WORDS_DISABLED.
The crosswords feature allows to assign words between <a href="xxx"> and </a> also to a document this link leads to. It works in SQL database mode and is not supported in built-in database and Cachemode.
Nota: Crosswords are supported only in mnoGoSearch 3.1.11 or later.
UDM_PARAM_VARDIR - specifies a custom path to directory where indexer stores data when using built-in database and in cache mode. By default /var directory of mnoGoSearch installation is used. Can have only string values. The parameter is available in PHP 4.1.0 or later.
These functions allow you to access mSQL database servers. More information about mSQL can be found at http://www.hughes.com.au/.
In order to have these functions available, you must compile PHP with msql support by using the --with-msql[=DIR] option. DIR is the mSQL base install directory, defaults to /usr/local/msql3.
Note to Win32 Users: In order to enable this module on a Windows environment, you must copy msql.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. mSQL configuration options
Name | Default | Changeable |
---|---|---|
msql.allow_persistent | "On" | PHP_INI_SYSTEM |
msql.max_persistent | "-1" | PHP_INI_SYSTEM |
msql.max_links | "-1" | PHP_INI_SYSTEM |
Breve descrizione dei parametri di configurazione.
There are two resource types used in the mSQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
This simple example shows how to connect, execute a query, print resulting rows and disconnect from a mSQL database.
Esempio 1. mSQL usage example
|
Returns number of affected ("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() 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() 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() 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_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().
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().
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() 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().
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().
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().
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().
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() 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() returns the length of the specified field or FALSE on error.
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.
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().
Returns the name of the table field was fetched from.
This function returns FALSE on failure.
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_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() 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() 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() 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() 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() 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_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() 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
|
See also msql_db_query(), msql_select_db(), and msql_connect().
Returns the contents of the cell at the row and offset in the specified mSQL result set.
msql_result() returns the contents of one cell from a mSQL result set. The field argument can be the field's offset, or the field's name, or the field's table dot field's name (fieldname.tablename). If the column name has been aliased ('select foo as bar from ...'), use the alias instead of the column name.
When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they 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() 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().
Queste funzioni consentono l'accesso ai server di database MySQL. Maggiori informazioni riguardo MySQL possono essere trovate su http://www.mysql.com/.
La documentazione su MySQL può essere trovata su http://dev.mysql.com/doc/.
Al fine di rendere queste funzioni disponibili, si deve compilare PHP con il supporto MySQL.
Usando l'opzione di configurazione --with-mysql[=DIR] si abilita PHP l'accesso ai database MySQL. 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. |
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Opzioni di configurazione di MySQL
Nome | Predefinito | Modificabile in |
---|---|---|
mysql.allow_persistent | "On" | PHP_INI_SYSTEM |
mysql.max_persistent | "-1" | PHP_INI_SYSTEM |
mysql.max_links | "-1" | PHP_INI_SYSTEM |
mysql.default_port | NULL | PHP_INI_ALL |
mysql.default_socket | NULL | PHP_INI_ALL |
mysql.default_host | NULL | PHP_INI_ALL |
mysql.default_user | NULL | PHP_INI_ALL |
mysql.default_password | NULL | PHP_INI_ALL |
mysql.connect_timeout | "0" | PHP_INI_SYSTEM |
Qui c'è una breve spiegazione delle direttive di configurazione.
Determina se consentire le connessioni persistenti a MySQL.
Il numero massimo di connessioni persistenti MySQL per processo.
Il numero massimo di connessioni MySQL per processo, incluse le connessioni persistenti.
Il numero di porta TCP predefinito da usare per connettersi ad un server di database se nessuna altra porta viene specificata. Se nessun valore predefinito e specificato, la porta sarà ottenuta dalla variabile d'ambiente MYSQL_TCP_PORT, dalla voce mysql-tcp in /etc/services o dalla costante MYSQL_PORT in fase di compilazione, in questo ordine. Win32 userà solo la costante MYSQL_PORT.
Il nome del socket predefinito da usare per connettersi ad un server di database locale se nessun altro nome di socket viene specificato.
L'host di default del server da usare per connettersi al server di database se nessun altro host viene specificato. Non si applica in safe mode.
Il nome utente predefinito da usare per connettersi al server di database se nessun altro nome viene specificato. Non si applica in safe mode.
La password predefinita da usare per connettrsi al server di database se nessuna altra password viene specificata. Non si appplica in safe mode.
Timeout di connessione in secondi. Per Linux questo timeout è usato anche per attendere la prima risposta dal server.
Ci sono due tipi di risorsa usati nel modulo MySQL. Il primo è l'identificativo di connessione per una connessione ad un database, del secondo tipo sono le risorse che contengono i risultati di una query.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Fin dal PHP 4.3.0 è possibile specificare flag addizionali per il client per le funzioni mysql_connect() e mysql_pconnect(). Sono definite le seguenti costanti:
Tabella 2. Costanti client MySQL
Costante | Descrizione |
---|---|
MYSQL_CLIENT_COMPRESS | Usa la compressione del protocollo |
MYSQL_CLIENT_IGNORE_SPACE | Consente lo spazio dopo i nomi delle funzioni |
MYSQL_CLIENT_INTERACTIVE | Lascia trascorrere interactive_timeout secondi (anziché wait_timeout) di inattività prima di chiudere la connessione |
La funzione mysql_fetch_array() usa una costante per i diversi tipi di array risultato. Sono definite le seguenti costanti:
Tabella 3. Costanti caricamento MySQL
Costante | Descrizione |
---|---|
MYSQL_ASSOC | Le colonne sono restituite in un array avente il nome del campo come indice dell'array |
MYSQL_BOTH | Le colonne sono restituite in un array avente sia un indice numerico sia un indice costituito dal nome del campo |
MYSQL_NUM | Le colonne sono restituite in un array avente un indice numerico per i campi. Questo indice inizia da 0, il primo campo nel risultato |
Questo esempio mostra come connettersi, eseguire una query, stampare le righe risultanti e disconnettersi dal database MySQL.
Esempio 1. Esempio dell'estensione MySQL
|
(PHP 3, PHP 4 , PHP 5)
mysql_affected_rows -- Ottiene il numero di righe coinvolte nelle precedenti operazioni MySQLmysql_affected_rows() restituisce il numero di righe coinvolte nell'ultima query INSERT, UPDATE o DELETE associata a identificativo_connessione. Se l'identificativo di connessione non è specificato, viene considerata l'ultima connessione aperta con mysql_connect().
Nota: Se sono usate le transazioni, è necessario richiamare mysql_affected_rows() dopo le query INSERT, UPDATE, o DELETE e non dopo il commit.
Se l'ultima query era una query DELETE senza clausola WHERE, tuti i record saranno cancellati dalla tabella ma questa funzione restituirà zero.
Nota: Usando UPDATE, MySQL non aggiornerà le colonne nelle quali il nuovo valore è uguale al vecchio valore. Questo crea la possibilità che mysql_affected_rows() può non uguagliare realmente il numero di righe corrispondenti ma solo il numero di righe effettivamente coinvolte dalla query.
mysql_affected_rows() non funziona con l'istruzione SELECT ma solo con le istruzioni che modificano i record. Per ricavare il numero di righe restituite da SELECT, usare mysql_num_rows().
Se l'ultima query fallisce, questa funzione restituisce -1.
Esempio 1. Query di eliminazione
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Esempio 2. Query di aggiornamento
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_num_rows(), mysql_info().
mysql_change_user() cambia l'utente dell'attuale connessione attiva o della connessione specificata dal parametro opzionale identificativo_connessione. Se un database is specificato, questo sarà il database corrente dopo che l'utente è stato cambiato. Se l'autorizzazione del nuovo utente e password falllisce, l'attuale utente connesso rimane attivo. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Questa funzione è stata introdotta nel PHP 3.0.13 e richiede MySQL 3.23.3 o successivo. Non è disponibile nel PHP 4.
mysql_client_encoding() restituisce il nome del set di caratteri predefinito per l'attuale connessione.
Esempio 1. Esempio di mysql_client_encoding()
L'esempio riportato sopra produce il seguente output:
|
Vedere anche: mysql_real_escape_string()
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
mysql_close() chiude la connessione al server MySQL associata all'identificativo di connessione specificato. Se identificativo_connessione non è specificato, viene usata l'ultima connessione aperta.
L'uso di mysql_close() non è normalmente necessario, dal momento che le connessioni non persistenti sono chiuse automaticamente alla fine dell'esecuzione dello script. Vedere anche freeing resources.
Nota: mysql_close() non chiude le connessioni persistenti create da mysql_pconnect().
Vedere anche: mysql_connect(), e mysql_pconnect().
Restituisce un identificativo di connessione MySQL in caso di successo oppure FALSE in caso di fallimento.
mysql_connect() stabilice una connessione ad un server MySQL. I seguenti valore predefiniti sono assunti per i parametri opzionali mancanti: server = 'localhost:3306', nome_utente = nome dell'utente proprietario del processo server e password = password vuota.
Il parametro server può anche includere un numero di porta. Es. "hostname:porta" o un percorso ad un socket es. ":/percorso/al/socket" per il localhost.
Nota: il supporto per ":porta" è stato aggiunto nel PHP 3.0B4.
Il supporto per ":/percorso/al/socket" è stato aggiunto nel PHP 3.0.10.
Si può eliminare il messaggio di errore nel caso di fallimento aggiungendo il prefisso @ al un nome della funzione.
Se si fa una seconda chiamata a mysql_connect() con gli stessi argomenti, nessuna nuova connessione sarà stabilita, ma sarà restituito l'identificativo della connessione già aperta. Il paramentro nuova_connessione modifica questo comportamento e fa sì che mysql_connect() apra sempre una nuova connessione, anche se mysql_connect() era stata chiamata prima con gli stessi parametri. il parametro client_flags può essere combinato con le costanti MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE o MYSQL_CLIENT_INTERACTIVE.
Nota: Il paramentro nuova_connessione è stato indrodotto dal PHP 4.2.0
Il parametro client_flags è stato introdotto dal PHP 4.3.0
La connessione al server sarà chiusa prima della fine dell'esecuzione dello script, a meno che questa non sia precedentemente chiusa esplicitamente richiamando mysql_close().
Vedere anche mysql_pconnect() e mysql_close().
mysql_create_db() tenta di creare un nuovo database nel server associato all'identificativo di conmnessione specificato.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. Esempio creazione database MySQL
|
Per motivi di compatibilità con il passato, anche mysql_createdb() può essere usata. Questo è comunque sconsigliato.
Nota: La funzione mysql_create_db() è sconsigliata. Al suo posto è preferibile usare mysql_query() per inviare un'istruzione SQL CREATE DATABASE.
Vedere anche: mysql_drop_db(), mysql_query().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
mysql_data_seek() muove il puntatore di riga interno del risultato MySQL associato all'identificativo specificato per puntare ad un determinato numero di riga. La successiva chiamata a mysql_fetch_row() dovrebbe restituire questa riga.
numero_riga inizia da 0. numero_riga dovrebbe essere un valore nell'intervallo che va da 0 a mysql_num_rows - 1.
Nota: La funzione mysql_data_seek() può essere usata solo insieme a mysql_query(), non con mysql_unbuffered_query().
Esempio 1. Esempio seek dati MySQL
|
Vedere anche: mysql_query(), mysql_num_rows().
mysql_db_name() accetta come primo paramentro il puntatore al risultato dalla chiamata a mysql_list_dbs(). Il parametro riga è un indice compreso nell'intervallo del risultato.
Se intercorre un errore, viene restituito FALSE. Usare mysql_errno() e mysql_error() per determinare la natura dell'errore.
Per motivi di compatibilità con il passato, anche mysql_dbname() è è accettata. Questo comunque è sconsigliato.
Restituisce una risorsa risultato della query se è stato possibile eseguire quest'ultima, oppure FALSE in caso d'errore. La funzione restituisce TRUE/FALSE anche per le query INSERT/UPDATE/DELETE per indicarne il successo/fallimento.
mysql_db_query() seleziona un database ed esegue una query su di esso. Se l'identificativo di connessione opzionale non è specificato, la funzione proverà a cercare una connessione aperta al server MySQL e se tale connessione non viene trovata cercherà di crearne una come se mysql_connect() fosse chiamata senza argomenti.
Si informa che questa funzione NON commuta al database al quale si era connessi prima. in altre parole, non si può usare questa funzione per eseguire temporaneamente una query sql su un altro database, si deve commutare manualmente. Gli utenti sono fortemente incoraggiati ad usare la sintassi database.tabella nelle loro query sql in questa funzione.
Vedere anche mysql_connect() e mysql_query().
Nota: Questa funzione è stata sconsigliata a partire dal PHP 4.0.6. Non usare questa funzione.Usare invece mysql_select_db() e mysql_query().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
mysql_drop_db() tenta di eliminare (cancellare) un intero database dal server associato all'identificativo di connessione specificato.
Per motivi di compatibilità con il passato, anche mysql_dropdb() può essere usato. Questa è comunque sconsigliato.
Nota: La funzione mysql_drop_db() è sconsigliata. Al suo posto è preferibile usare mysql_query() per inviare una istruzione SQL DROP DATABASE.
Vedere anche: mysql_create_db(), mysql_query().
(PHP 3, PHP 4 , PHP 5)
mysql_errno -- Restituisce il valore numerico del messaggio di errore della precedente operazione MySQLRestituisce il numero di errore dall'ultima funzione MySQL, oppure 0 (zero) se nessun errore è intercorso.
Gli errori ritornano dal database MySQL senza visualizzare i messaggi di avvertimento. Usando invece mysql_errno() si recupera il codice di errore. Notare che questa funzione restituisce solo il codice errore della più recente funzione MySQL eseguita (ad esclusione di mysql_error() e mysql_errno()), quindi se la si vuole usare, assicurarsi di controllare il valore prima di richiamare un'altra funzione MySQL.
Esempio 1. Esempio di mysql_errno
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Nota: Se l'argomento opzionale è specificato la connessione indicata viene usata per recuperare il codice d'erroe. Altrimenti viene usata l'ultima connessione aperta.
Vedere anche: mysql_error()
(PHP 3, PHP 4 , PHP 5)
mysql_error -- Restituisce il testo del messagio di errore della precedente operazione MySQLRestituisce il testo dell'errore dall'ultima funzione MySQL, oppure '' (la stringa vuota) se nessun errore intercorre.
Gli errori ritornano dal database MySQL senza visualizzare i messaggi di avvertimento. Si usa invece mysql_error() per recuperare il testo dell'errore. Notare che questa funzione restituisce solo il testo dell'errore della più recente funzione MySQL eseguita (ad esclusione di mysql_error() e mysql_errno()), quindi se la si vuole usare, assicurarsi di controllare il valore prima di richiamare un'altra funzione MySQL.
Esempio 1. mysql_error Example
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Nota: Se l'argomento opzionale è specificato la connessione indicata viene usata per recuperare il codice d'erroe. Altrimenti viene usata l'ultima connessione aperta.
Vedere anche: mysql_errno()
(PHP 4 >= 4.0.3, PHP 5)
mysql_escape_string -- Aggiunge le sequenze di escape in una stringa per l'uso in mysql_query.Questa funzione aggiunge le sequenze di escape a stringa_senza_escape, in modo che sia sicuro usarla in mysql_query().
Nota: mysql_escape_string() non aggiunge le sequenze di escape a % ed a _.
Questa funzione è identica a mysql_real_escape_string() eccetto che mysql_real_escape_string() accetta un identificativo di connessione ed aggiunge le sequenze di escape alla stringa in base al set di caratteri corrente. mysql_escape_string() non accetta come argomento un identificativo di connessione e non rispetta le impostazioni del corrente set di caratteri.
Esempio 1. Esempio di mysql_escape_string()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_real_escape_string(), addslashes(), e la direttiva magic_quotes_gpc .
(PHP 3, PHP 4 , PHP 5)
mysql_fetch_array -- Carica una riga del risultato come un array associativo, un array numerico o entrambi.Restituisce un array che corrisponde alla riga caricata o FALSE se non ci sono più righe.
mysql_fetch_array() è una versione estesa di mysql_fetch_row(). Oltre a memorizzare i dati del risultato in array con indice numerico, questa li memorizza anche con indici associativi usando i nomi dei campi come chiavi.
Se due o più colonne del risultato hanno gli stessi nomi di campo, l'ultima colonna avrà la precedenza. Per accedere alle altre colonne con lo stesso nome, si deve usare l'indice numerico della colonna o farne un alias. Per le colonne-alias, non si può accedere al contenuto con il nome della colonna originale (in questo esempio si usa 'campo').
Una cosa importante da notare è che l'uso di mysql_fetch_array() non è significativamente più lento dell'uso di mysql_fetch_row(); questo fornisce un significativo valore aggiunto.
Il secondo argomento opzionale tipo_risultato in mysql_fetch_array() è una costante e può assumere i seguenti valori: MYSQL_ASSOC, MYSQL_NUM e MYSQL_BOTH. Questa caratteristica è stata aggiunta nel PHP 3.0.7. MYSQL_BOTH è il valore predefinito per questo argomento.
Usando MYSQL_BOTH, si ottiene un array con entrambe gli indici (associativo e numerico). Usando MYSQL_ASSOC, si ottengono solo gli indici associativi (stesso funzionamento di mysql_fetch_assoc()), usando MYSQL_NUM, si ottengono solo gli indici numerici (stesso funzionamento di mysql_fetch_row()).
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Esempio 2. mysql_fetch_array() con MYSQL_NUM
|
Esempio 3. mysql_fetch_array() con MYSQL_ASSOC
|
Esempio 4. mysql_fetch_array() con MYSQL_BOTH
|
Per maggiori dettagli, vedere anche mysql_fetch_row() e mysql_fetch_assoc().
Restituisce un array associativo che corrisponde alla riga caricata o FALSE se non ci sono più righe.
mysql_fetch_assoc() è equivalente alla chiamata di mysql_fetch_array() con MYSQL_ASSOC come secondo parametro opzionale. Questa restituisce solo un array associativo. Questo è il modo incui mysql_fetch_array() funzionava originalmente. Se è necessario l'indice numerico al posto di quello associativo, usare mysql_fetch_array().
Se due o più colonne del risultato hanno gli stessi nomi di campo, l'ultima colonna avrà la precedenza. Per accedere alle altre colonne con lo stesso nome, si deve accedere al risultato con l'indice numerico usando mysql_fetch_row() oppure aggiunger degli alias. Vedere l'esempio nella descrizione di mysql_fetch_array() per quanto concerne gli alias.
Una cosa importante da notare è che l'uso di mysql_fetch_assoc() non è significativamente più lento dell'uso di mysql_fetch_row(); questo fornisce un significativo valore aggiunto.
Esempio 1. Un esteso esempio di mysql_fetch_assoc()
|
Vedere anche mysql_fetch_row(), mysql_fetch_array(), mysql_query() e mysql_error().
(PHP 3, PHP 4 , PHP 5)
mysql_fetch_field -- Ottiene informazioni sulla colonna da un risultato e le restituisce come oggettoRestituisce un oggetto contenente le informazioni di un campo.
mysql_fetch_field() può essere usata al fine di ottenere informazioni circa i campi di un determinato risultato di una query. Se l'indice del campo non è specificato, il successivo campo non ancora recuperato da mysql_fetch_field() viene considerato.
Le proprietà dell'oggetto sono:
name - nome della colonna
table - nome della tabella a cui appartiene la colonna
max_length - massima lunghezza della colonna
not_null - 1 se la colonna non può essere NULL
primary_key - 1 se la colonna è una chiave primaria
unique_key - 1 se la colonna è una chiave unica
multiple_key - 1 se la colonna è una chiave non-unica
numeric - 1 se la colonna è numerica
blob - 1 se la colonna è un BLOB
type - il tipo della colonna
unsigned - 1 se la colonna è senza segno
zerofill - 1 se la colonna è completata da zeri
Esempio 1. mysql_fetch_field()
|
Vedere anche mysql_field_seek().
Restituisce un array che corrisponde alle lunghezze di ogni campo nell'ultima riga caricata da mysql_fetch_row() oppure FALSE in caso di errore.
mysql_fetch_lengths() memorizza le lunghezze di ogni colonna dell'ultima riga restituita da mysql_fetch_row(), mysql_fetch_array() e mysql_fetch_object() in un array, iniziando con un indice pari a 0.
Vedere anche: mysql_fetch_row().
Restituisce un oggetto con proprietà che corrispondono alla riga caricata oppure FALSE se non ci sono più righe.
mysql_fetch_object() è simile a mysql_fetch_array(), con una differenza - viene restituito un oggetto invece che un array. Indirettamente, questo significa che si ha solo accesso ai dati attraverso i nomi dei campi e non attraverso il loro indice (i mumeri sono nomi di proprietà illeciti).
<?php /* questo è valido */ echo $riga->campo; /* questo non è valido */ echo $riga->0; ?> |
In termini di velocità, la funzione è identica a mysql_fetch_array() e quasi veloce come mysql_fetch_row() (la differenza è insignificante).
Esempio 1. Esempio di mysql_fetch_object()
|
Vedere anche: mysql_fetch_array() e mysql_fetch_row().
Restituisce un array che corrisponde ad una riga caricata oppure FALSE se non ci sono più righe.
mysql_fetch_row() carica una riga di dati dal risultato associato all'identificativo specificato. La riga è restituita com un array. Ogni colonna del risultato è memorizzata in un indice dell'array, partendo dall'indice 0.
La susseguente chiamata a mysql_fetch_row() restituisce la successiva riga nell'intervallo del risultato oppure FALSE se non ci sono più righe.
Vedere anche: mysql_fetch_array(), mysql_fetch_object(), mysql_data_seek(), mysql_fetch_lengths() e mysql_result().
(PHP 3, PHP 4 , PHP 5)
mysql_field_flags -- Ottine i flag associati al campo specificato di un risultatomysql_field_flags() restituisce i flag del campo specificato. I flag sono restituiti come singole parole per flag separate da un singolo spazio, in modo che sia possibile suddividere il valore restituito usando explode().
I seguenti flag sono restituiti, se la versione di MySQL è abbastanza aggiornata da supportarli: "not_null", "primary_key", "unique_key", "multiple_key", "blob", "unsigned", "zerofill", "binary", "enum", "auto_increment", "timestamp".
Per motivi di compatibilità con il passato, anche mysql_fieldflags() può essere usata. Questo comunque è sconsigliato.
mysql_field_len() restituisce la lunghezza del campo specificato.
Per motivi di compatibilità con il passato, anche mysql_fieldlen() può essere usata. Questo comunque è sconsigliato.
mysql_field_name() restituisce il nome del campo specificato dall'indice. risultato deve essere un identificativo di risultato valido e indice_campo è lo spiazzamento numerico del campo.
Nota: indice_campo inizia da 0.
Es. L'indice del terzo campo è in realtà 2, l'indice del quarto campo è 3 e così via.
Esempio 1. Esempio di mysql_field_name()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Per motivi di compatibilità con il passato, anche mysql_fieldname() può essere usata. Questo comunque è sconsigliato.
(PHP 3, PHP 4 , PHP 5)
mysql_field_seek -- Imposta il puntatore al risultato ad un determinato indice di campoEsegue il seek ad uno specifico indice di campo. Se la successiva chiamata a mysql_fetch_field() non include un indice di campo, quello specificato in mysql_field_seek() viene restituito.
Vedere anche: mysql_fetch_field().
(PHP 3, PHP 4 , PHP 5)
mysql_field_table -- Ottiene il nome della tabella in cui si trova il campo specificatoOttiene il nome della tabella in cui si trova il campo specificato.
Per motivi di compatibilità con il passato, anche mysql_fieldtable() può essere usata. Questo comunque è sconsigliato.
mysql_field_type() è simile alla funzione mysql_field_name(). Gli argomenti sono identici, ma viene restituito il tipo del campo. Il tipo del campo sarà uno dei seguenti: "int", "real", "string", "blob" ed altri come dettagliati nella Documentazione di MySQL.
Esempio 1. Tipi di campo MySQL
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Per motivi di compatibilità con il passato, anche mysql_fieldtype() può essere usata. Questo comunque è sconsigliato.
mysql_free_result() libera utuuta la memoria associata all'identificativo del risultato risultato.
mysql_free_result() deve essere richiamata solo se si è preoccupati sulla quantità di memoria usata dalle query che restituiscono dei grandi risultati. Tutta la memoria associata al risultato è automaticamente liberata al termine dell'esecuzione dello script.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Per motivi di compatibilità con il passato, anche mysql_freeresult() può essere usata. Questo comunque è sconsigliato.
mysql_get_client_info() restituisce una stringa che rappresenta la versione della libraria client.
Vedere anche: mysql_get_host_info(), mysql_get_proto_info() e mysql_get_server_info().
mysql_get_host_info() restituisce una stringa che descrive il tipo di connessione in uso per identificativo_connessione, includendo il nome dell'host del server. Se identificativo_connessione è omesso, sarà usata l'ultima connessione aperta.
Esempio 1. Esempio di mysql_get_host_info
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_get_client_info(), mysql_get_proto_info() e mysql_get_server_info().
mysql_get_proto_info() restituisce la versione del protocollo usata dalla connessione identificativo_connessione. Se identificativo_connessione è omesso, sarà usata l'ultima connessione aperta.
Esempio 1. Esempio di mysql_get_proto_info
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_get_client_info(), mysql_get_host_info() e mysql_get_server_info().
mysql_get_server_info() restituisce la versione del server usato dalla connessione identificativo_connessione. Se identificativo_connessione è omesso, sarà usata l'ultima connessione aperta.
Esempio 1. Esempio di mysql_get_server_info
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_get_client_info(), mysql_get_host_info() e mysql_get_proto_info().
mysql_info() restituisce informazioni dettagliate relative all'ultima query usando lo specifico identificativo_connessione. Se identificativo_connessione non è specificato, viene considerata l'ultima connessione aperta.
mysql_info() restituisce una stringa per tutte le istruzioni elencate di seguito. Per tutte le altre restituisce FALSE. Il formato della stringa dipende dall'istruzione data.
Esempio 1. Istruzioni MySQL significative
|
Nota: mysql_info() restituisce un valore non FALSE per le istruzioni INSERT ... VALUES solo se nell'istruzione sono specificate liste di valori multipli.
Vedere anche: mysql_affected_rows()
(PHP 3, PHP 4 , PHP 5)
mysql_insert_id -- Ottiene l'identificativo generato dalla precedente operazione INSERTmysql_insert_id() restituisce l'identificativo generato per una colonna AUTO_INCREMENT dal precedente query INSERT usando lo specifico identificativo_connessione. Se identificativo_connessione non è specificato, viene considerata l'ultima connessione aperta.
mysql_insert_id() restituisce 0 se la precedente query non ha generato un valore AUTO_INCREMENT. Se è necessario salvare il valore per usarlo in seguito, assicurarsi di richiamare mysql_insert_id() immediatamente dopo la query che ha generato il valore.
Nota: Il valore della funzione SQL LAST_INSERT_ID() di MySQL contiene sempre il più recente valore AUTO_INCREMENT generato e non è azzerato dalle query.
Avvertimento |
mysql_insert_id() converte il tipo restituito dalla funzione nativa dell'API C di MySQL mysql_insert_id() al tipo long (chiamata int nel PHP). Se la colonna AUTO_INCREMENT è del tipo BIGINT, il valore restituito da mysql_insert_id() sarà inesatto. In questo caso si usi la funzione SQL di MySQL LAST_INSERT_ID() in una query SQL. |
Esempio 1. Esempio di mysql_insert_id
|
Vedere anche: mysql_query().
mysql_list_dbs() restituirà un risultato puntatore contenete i database resi disponibili dal demone mysql. Usare la funzione mysql_tablename() per esplorare questo risultato puntatore o qualsiasi funzione per i risultati delle tabelle, come mysql_fetch_array().
Esempio 1. Esempio di mysql_list_dbs()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Nota: Il codice riportato sopra dovrebbe funzionare facilmente con mysql_fetch_row() o altre funzioni simili.
Per motivi di compatibilità con il passato, anche mysql_listdbs() può essere usata. Questo comunque è sconsigliato.
Vedere anche mysql_db_name().
mysql_list_fields() recupera le informazioni relative ad una data tabella. Gli argomenti sono il nome del database ed il nome della tabella. Viene restituito un risultato puntatore che può essere usato con mysql_field_flags(), mysql_field_len(), mysql_field_name() e mysql_field_type().
Esempio 1. Esempio di mysql_list_fields()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Per motivi di compatibilità con il passato, anche mysql_listfields() può essere usata. Questo comunque è sconsigliato.
mysql_list_processes() restituisce un risultato puntatore che descrive i thread attuali del server.
Esempio 1. Esempio di mysql_list_processes()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_thread_id()
mysql_list_tables() accetta un nome di database e restituisce un risultato puntatore in modo molto simile alla funzione mysql_query(). Usare la funzione mysql_tablename() per esplorare questo risultato puntatore o qualsiasi funzione per i risultati delle tabelle, come mysql_fetch_array().
Il parametro database è il nome del database da cui recuperare la lista di tabelle. in caso di errore, mysql_list_tables() restituisce FALSE.
Per motivi di compatibilità con il passato, anche mysql_listtables() può essere usata. Questo comunque è sconsigliato.
Esempio 1. mysql_list_tables() example
|
Vedere anche: mysql_list_dbs() e mysql_tablename().
mysql_num_fields() restituisce il numero di campi in un risultato.
Vedere anche: mysql_select_db(), mysql_query(), mysql_fetch_field() e mysql_num_rows().
Per motivi di compatibilità con il passato, anche mysql_numfields() può essere usata. Questo comunque è sconsigliato.
mysql_num_rows() restituisce il numero di righe in un risultato. Questo comando è valido solo per le istruzioni SELECT. Per recuperare il numero di righe coinvolte dalle query INSERT, UPDATE o DELETE, usare mysql_affected_rows().
Esempio 1. Esempio di mysql_num_rows()
|
Nota: Se si usa mysql_unbuffered_query(), mysql_num_rows() non restituirà il valore corretto finché non sono recuperate tutte le righe del risultato.
Vedere anche: mysql_affected_rows(), mysql_connect(), mysql_data_seek(), mysql_select_db() e mysql_query().
Per motivi di compatibilità con il passato, anche mysql_numrows() può essere usata. Questo comunque è sconsigliato.
Restituisce un identificativo di connessione MySQL valido in caso di successo oppure FALSE in caso di errore.
mysql_pconnect() stabilisce una connessione ad un server MySQL. I seguenti valori predefiniti sono usati per i parametri opzionali mancanti: server = 'localhost:3306', nome_utente = nome dell'utente prprietario del processo server e password = password vuota. Il parametro flag_client può essere una combinatione delle costanti MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE o MYSQL_CLIENT_INTERACTIVE.
Il parametro server può includere una numero di porta. Es. "hostname:porta" o un percorso ad un socket es. ":/percorso/a/socket" per il localhost.
Nota: Il supporto per ":porta" è stato aggiunto nel PHP 3.0B4.
Il supportp per ":/percorso/a/socket" è stato aggiunto nel PHP 3.0.10.
mysql_pconnect() agisce in modo molto simile a mysql_connect() con due differenze principali.
Primo, quando si connette, la funzione tenta innanzitutto di trovare una connessione (persistente) già aperta avente gli stessi host, username e password. Se viene trovata una connessione, viene restituito un identificativo a questa anziché aprirne una nuova.
Secondo, la connessione al server SQL non sarà chiusa quando l'esecuzione dello script termina. La connessione rimane invece aperta per usi futuri (mysql_close() non chiuderà le connessioni stabilite da mysql_pconnect()).
Il parametro opzionale flag_client è diventato disponibile nel PHP 4.3.0.
Questo tipo di link è perciò chiamato 'persistente'.
Nota: Notare che questo tipo di connessione funziona solo se si usa PHP come modulo. Vedere la sezione Persistent Database Connections per maggiori informazioni.
Avvertimento |
L'uso di connessioni persistenti può richiedere un po' di messa a punto delle configurazioni di Apache e MySQL per assicurarsi di non eccedere il numero di connessioni consentite da MySQL. |
(PHP 4 >= 4.3.0, PHP 5)
mysql_ping -- Esegue un ping su una connessione al server o riconnette se non non esiste la connessionemysql_ping() controlla se una connessione al server funziona o meno. Se questa è caduta, viene tentata una riconnessione automatica. Questa funzione può essere usata dagli script che rimangono inattivi per un lungo periodo per controllare se il server ha chiuso la connessione o meno e riconnettersi se necessario. mysql_ping() restituisce TRUE se la connessione al server è funzionante, altrimenti FALSE.
Vedere anche: mysql_thread_id() e mysql_list_processes().
mysql_query() invia una query al database attualmente attivo sul server associato all'identificativo di conmnessione specificato. Se identificativo_connessione non è specificato, viene considerata l'ultima connessione aperta. Se nessuna connessione è aperta, la funzione prova a stabilire una connessione come se mysql_connect() fosse richiamata senza argomenti ed usa questa.
Il paramentro opzionale modo_risultato può essere MYSQL_USE_RESULT e MYSQL_STORE_RESULT. Il valore predefinito MYSQL_STORE_RESULT, così il risultato è bufferato. Vedere anche mysql_unbuffered_query() per la controparte di questo comportamento.
Nota: La stringa della query non dovrebbe terminare con un punto e virgola.
Solo per le istruzioni SELECT, SHOW, EXPLAIN o DESCRIBE mysql_query() restituisce un identificativo di risorsa o FALSE se la query non è stata eseguita correttamente. Per altri tipi di istruzioni SQL, mysql_query() restituisce TRUE in caso di successo e FALSE in caso di errore. Un valore restituito diverso da FALSE indica che la query era lecita ed è stata eseguita dal server. Questo non indica niente riguardo il numero di righe coinvolte o restituite. è assolutamente possibile che una query abbia successo ma che non coinvolga o restituisca nessuna riga.
La seguente query non è valida sintatticamente, quindi mysql_query() fallisce e restituisce FALSE:
La seguente query non è semanticamente valida se mia_colonna non è una colonna della tabella mia_tabella, quindi mysql_query() fallisce e retituisce FALSE:
mysql_query() fallisce e restituisce FALSE anche se non si hanno i permessi per accedere alle tabelle cui la query fa riferimento.
Assumendo che la query abbia succeesso, si può richiamare mysql_num_rows() per scoprire quante righe sono state restituite da un'istruzione SELECT o mysql_affected_rows() per scoprire quante righe sono state coinvolte da un'istruzione DELETE, INSERT, REPLACE o UPDATE.
Solo per le istruzioni SELECT, SHOW, DESCRIBE o EXPLAIN, mysql_query() restituisce un nuovo identificativo di risultato che si può passare a mysql_fetch_array() e ad altre funzioni che si occupano dei risultati delle tabelle. Quando si conclude il trattamento del risultato, si possono liberare le risorse associate ad esso richiamando mysql_free_result(). Comunqe la memoria sarà liberata automaticamente Al termnine dell'esecuzione dello script.
Vedere anche: mysql_num_rows(), mysql_affected_rows(), mysql_unbuffered_query(), mysql_free_result(), mysql_fetch_array(), mysql_fetch_row(), mysql_fetch_assoc(), mysql_result(), mysql_select_db() e mysql_connect().
(PHP 4 >= 4.3.0, PHP 5)
mysql_real_escape_string -- Aggiunge le sequenze di escape ai caratteri speciali in una stringa per l'uso in una istruzione SQL, tenendo conto dell'attuale set di caratteri della connessione.Questa funzione aggiunge le sequenza di escape ai caratteri speciali in stringa_senza_escape, tenendo conto dell'attuale set di caratteri della connessione in modo che sia sicuro usarla in mysql_query().
Nota: mysql_real_escape_string() non aggiunge le sequenze di escape a % ed a _.
Esempio 1. Esempio di mysql_real_escape_string()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche : mysql_escape_string() e mysql_character_set_name().
mysql_result() restituisce i contenuti di una cella da un risultato MySQL. L'argomento campo può essere l'indice o il nome del campo oppure il nome della tabella ed il nome del campo separati da un punto (nome_tabella.nome_campo). Se il nome della colonna ha un alias ('select foo as bar from...'), usare l'alias al posto del nome della colonna.
Quando si lavora con un risultato di grandi dimensioni, si dovrebbero considerare l'uso delle funzioni che caricano l'intera riga (specificate di seguito). Poiché queste funzioni restituiscono i contenuti di celle multiple in una chiamata a funzione, sono MOLTO più veloci di mysql_result(). Notare anche che specificare un indice numerico per l'argomento campo è molto più veloce che specificare un argomento del tipo nome_di_campo o nome_tabella.nome_campo.
Le chiamate a mysql_result() non dovrebbero esserse mescolate con chiamate ad altre funzioni che hanno a che fare con i risultati.
Alternative raccomandate per alte prestazioni: mysql_fetch_row(), mysql_fetch_array() e mysql_fetch_object().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
mysql_select_db() imposta il database attualmente attivo sul server associato all'identificativo di connessione specificato. Se nessin identificativo di connesione è specificato, viene considerata l'ultima connessione aperta. Se nessuna connessione è aperta, la funzione proverà a stabilire una connessione come se mysql_connect() fosse richiamata senza argomenti ed userà questa.
Ogni chiamata successiva a mysql_query() sarà fatta sul database attivo.
Vedere anche: mysql_connect(), mysql_pconnect() e mysql_query().
Per motivi di compatibilità con il passato, anche mysql_selectdb() può essere usata. Questo comunque è sconsigliato.
mysql_stat() restituisce l'attuale stato del server.
Nota: mysql_stat() attualmente restituisce solo le seguenti informazioni: uptime, thread, query, tabelle aperte, tabelle svuotate e query al secondo. Per una lista completa delle altre variabili di stato si usi il comando SQL SHOW STATUS.
Esempio 1. mysql_stat() example
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
mysql_tablename() prende il puntatore risultato dalla funzione mysql_list_tables() come un indice intero e restituisce il nome di una tabella. La funzione mysql_num_rows() può essere usata per determinare il numero di tabelle nel risultato puntatore. Usare la funzione mysql_tablename() per esplorare questo risultato puntatore o qualsiasi funzione per i risultati delle tabelle, come mysql_fetch_array().
Vedere anche: mysql_list_tables().
mysql_thread_id() restituisce l'attuale thread ID. Se La connessione è persa a ci si riconnette con mysql_ping(), il thread ID cambia. Questo significa che non si dovrebbe ottenere il thread ID e memorizzarlo per impieghi successivi. Si dovrebbe rilevare il thread ID quando è necessario.
Esempio 1. Esempio di mysql_thread_id()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_ping() e mysql_list_processes().
(PHP 4 >= 4.0.6, PHP 5)
mysql_unbuffered_query -- Invia una query SQL a MySQL senza caricare e bufferare le righe risultantimysql_unbuffered_query() invia una query SQL query a MySQL senza caricare e bufferare le righe risultanti automaticamente come fa mysql_query(). Da una parte, questo risparmia un considerevole quantità di memoria con le query SQL che producono risulati di grandi dimensioni. Dall'altra parte, si può iniziare l'elaborazione dei risultati immediatamente dopo che la prima riga è stata recuperata: non si deve attendere finché la query SQL sia completamente eseguita. Quando si usano diverse connessioni a database, si deve specificare il paramentro opzionale identificativo_connessione.
Il parametro opzionale modo_risultato può essere MYSQL_USE_RESULT e MYSQL_STORE_RESULT. Il valore predefinito è MYSQL_USE_RESULT, quindi il risultato non è bufferato. Vedere anche mysql_query() per la controparte di questo comportamento.
Nota: I benefici di mysql_unbuffered_query() hanno un costo: non si può usare mysql_num_rows() su un risultato restituito da mysql_unbuffered_query(). Inoltre si debbono caricare tutte le righe risultanti da una query SQL non bufferata prima di poter inviare una nuova query SQL a MySQL.
vedere anche: mysql_query().
The mysqli extension allows you to access the functionality provided by MySQL 4.1 and above. More information about the MySQL Database server can be found at http://www.mysql.com/
Documentation for MySQL can be found at http://dev.mysql.com/doc/.
Parts of this documentation included from MySQL manual with permissions of MySQL AB.
In order to have these functions available, you must compile PHP with support for the mysqli extension.
Nota: The mysqli extension is designed to work with the version 4.1.2 or above of MySQL. For previous versions, please see the MySQL extension documentation.
To install the mysqli extension for PHP, use the --with-mysqli=mysql_config_path/mysql_config configuration option where mysql_config_path represents the location of the mysql_config program that comes with MySQL versions greater than 4.1.
If you would like to install the mysql extension along with the mysqli extension you have to use the same client library to avoid any conflicts.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. MySQLi Configuration Options
Name | Default | Changeable |
---|---|---|
mysqli.max_links | "-1" | PHP_INI_SYSTEM |
mysqli.default_port | NULL | PHP_INI_ALL |
mysqli.default_socket | NULL | PHP_INI_ALL |
mysqli.default_host | NULL | PHP_INI_ALL |
mysqli.default_user | NULL | PHP_INI_ALL |
mysqli.default_pw | NULL | PHP_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.
The maximum number of MySQL connections per process.
The default TCP port number to use when connecting to the database server if no other port is specified. If no default is specified, the port will be obtained from the MYSQL_TCP_PORT environment variable, the mysql-tcp entry in /etc/services or the compile-time MYSQL_PORT constant, in that order. Win32 will only use the MYSQL_PORT constant.
The default socket name to use when connecting to a local database server if no other socket name is specified.
The default server host to use when connecting to the database server if no other host is specified. Doesn't apply in safe mode.
The default user name to use when connecting to the database server if no other name is specified. Doesn't apply in safe mode.
The default password to use when connecting to the database server if no other password is specified. Doesn't apply in safe mode.
Represents a connection between PHP and a MySQL database.
autocommit() - turns on or off auto-commiting database modifications
change_user() - changes the user of the specified database connection
character_set_name - returns the default character set for the database connection
close - closes a previously opened connection
commit - commits the current transaction
connect - opens a new connection to MySQL database server
debug - performs debugging operations
dump_debug_info - dumps debug information
get_client_info - returns client version
get_host_info - returns type of connection used
get_server_info - returns version of the MySQL server
get_server_version - returns version of the MySQL server
init - initializes mysqli object
info - retrieves information about the most recently executed query
kill - asks the server to kill a mysql thread
multi_query - performs multiple queries
more_results - check if more results 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
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
Represents a prepared statement.
bind_param - Binds variables to a prepared statement
bind_result - Binds variables to a prepared statement for result storage
close - Closes a prepared statement
data-seek - Seeks to an arbitrary row in a statement result set
execute - Executes a prepared statement
fetch - Fetches result from a prepared statement into bound variables
free_result - Frees stored result memory for the given statement handle
result_metadata - Retrieves a resultset from a prepared statement for metadata information
prepare - prepares a SQL query
send_long_data - Sends data in chunks
reset - resets a prepared statement
store_result - Buffers complete resultset from a prepared statement
affected_rows - Returns affected rows from last statement execution
errno - Returns errorcode for last statement function
errno - Returns errormessage for last statement function
param_count - Returns number of parameter for a given prepare statement
sqlstate - returns a string containing the SQLSTATE error code for the last statement function
Represents the result set obtained from a query against the database.
close - closes resultset
data_seek - moves internal result pointer
fetch_field - gets column information from a resultset
fetch_fields - gets information for all columns from a resulset
fetch_field_direct - gets column information for specified column
fetch_array - fetches a result row as an associative array, a numeric array, or both.
fetch_assoc - fetches a result row as an associative array
fetch_object - fetches a result row as an object
fetch_row - gets a result row as an enumerated array
close - frees result memory
field_seek - set result pointer to a specified field offset
current_field - returns offset of current fieldpointer
field_count - returns number of fields in resultset
lengths - returns an array of columnlengths
num_rows - returns number of rows in resultset
Tabella 2. MySQLi Constants
Name | Description |
---|---|
MYSQLI_READ_DEFAULT_GROUP (integer) | Read options from the named group from `my.cnf' or the file specified with MYSQLI_READ_DEFAULT_FILE |
MYSQLI_READ_DEFAULT_FILE (integer) | Read options from the named option file instead of from my.cnf |
MYSQLI_OPT_CONNECT_TIMEOUT (integer) | Connect timeout in seconds |
MYSQLI_OPT_LOCAL_INFILE (integer) | Enables command LOAD LOCAL INFILE |
MYSQLI_INIT_COMMAND (integer) | Command to execute when connecting to MySQL server. Will automatically be re-executed when reconnecting. |
MYSQLI_CLIENT_SSL (integer) | Use SSL (encrypted protocol). This option should not be set by application programs; it is set internally in the MySQL client library |
MYSQLI_CLIENT_COMPRESS (integer) | Use compression protocol |
MYSQLI_CLIENT_INTERACTIVE (integer) | Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection. The client's session wait_timeout variable will be set to the value of the session interactive_timeout variable. |
MYSQLI_CLIENT_IGNORE_SPACE (integer) | Allow spaces after function names. Makes all functions names reserved words. |
MYSQLI_CLIENT_NO_SCHEMA (integer) | Don't allow the db_name.tbl_name.col_name syntax. |
MYSQLI_CLIENT_MULTI_QUERIES (integer) | |
MYSQLI_STORE_RESULT (integer) | For using buffered resultsets |
MYSQLI_USE_RESULT (integer) | For using unbuffered resultsets |
MYSQLI_ASSOC (integer) | Columns are returned into the array having the fieldname as the array index. |
MYSQLI_NUM (integer) | Columns are returned into the array having an enumerated index. |
MYSQLI_BOTH (integer) | Columns are returned into the array having both a numerical index and the fieldname as the associative index. |
MYSQLI_NOT_NULL_FLAG (integer) | Indicates that a field is defined as NOT NULL |
MYSQLI_PRI_KEY_FLAG (integer) | Field is part of a primary index |
MYSQLI_UNIQUE_KEY_FLAG (integer) | Field is part of 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 |
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
(PHP 5)
mysqli_affected_rows(no version information, might be only in CVS)
mysqli->affected_rows -- Gets the number of affected rows in a previous MySQL operationProcedural style:
mixed mysqli_affected_rows ( object link)Object oriented style (property):
class mysqli {mysqli_affected_rows() returns the number of rows affected by the last INSERT, UPDATE, or DELETE query associated with the provided link parameter. If the last query was invalid, this function will return -1.
Nota: For SELECT statements mysqli_affected_rows() works like mysqli_num_rows().
The mysqli_affected_rows() function only works with queries which modify a table. In order to return the number of rows from a SELECT query, use the mysqli_num_rows() function instead.
An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error.
Nota: If the number of affected rows is greater than maximal int value, the number of affected rows will be returned as a string.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Affected rows (INSERT): 984 Affected rows (UPDATE): 168 Affected rows (DELETE): 815 Affected rows (SELECT): 169 |
(PHP 5)
mysqli_autocommit(no version information, might be only in CVS)
mysqli->auto_commit -- Turns on or off auto-commiting database modificationsProcedural style:
bool mysqli_autocommit ( object link, bool mode)Object oriented style (method)
class mysqli {mysqli_autocommit() is used to turn on or off auto-commit mode on queries for the database connection represented by the link object.
Nota: mysqli_autocommit() doesn't work with non transactional table types (like MyISAM or ISAM).
To determine the current state of autocommit use the SQL command 'SELECT @@autocommit'.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Autocommit is 1 |
This function is an alias of mysqli_stmt_bind_param(). For a detailled descripton see description of mysqli_stmt_bind_param().
Nota: mysqli_bind_param() is deprecated and will be removed.
This function is an alias of mysqli_stmt_bind_result(). For a detailled descripton see description of mysqli_stmt_bind_result().
Nota: mysqli_bind_result() is deprecated and will be removed.
(PHP 5)
mysqli_change_user(no version information, might be only in CVS)
mysqli->change_user -- Changes the user of the specified database connectionProcedural style:
bool mysqli_change_user ( object link, string user, string password, string database)Object oriented style (method):
class mysqli {mysqli_change_user() is used to change the user of the specified database connection as given by the link parameter and to set the current database to that specified by the database parameter.
If desired, the NULL value may be passed in place of the database parameter resulting in only changing the user and not selecting a database. To select a database in this case use the mysqli_select_db() function.
In order to successfully change users a valid username and password parameters must be provided and that user must have sufficient permissions to access the desired database. If for any reason authorization fails, the current user authentication will remain.
Nota: Using this command will always cause the current database connection to behave as if was a completely new database connection, regardless of if the operation was completed successfully. This reset includes performing a rollback on any active transactions, closing all temporary tables, and unlocking all locked tables.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Default database: world Value of variable a is NULL |
(PHP 5)
mysqli_character_set_name(no version information, might be only in CVS)
mysqli->character_set_name -- Returns the default character set for the database connectionProcedural style:
string mysqli_character_set_name ( object link)Object oriented style (method):
class mysqli {Returns the current character set for the database connection specified by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would be produce the following output:
Current character set is latin1_swedish_ci |
This function is an alias of mysqli_character_set_name(). For a detailled descripton see description of mysqli_character_set_name().
(PHP 5)
mysqli_close(no version information, might be only in CVS)
mysqli->close -- Closes a previously opened database connectionProcedural style:
bool mysqli_close ( object link)Object oriented style (method):
class mysqli {The mysqli_close() function closes a previously opened database connection specified by the link parameter.
(PHP 5)
mysqli_commit(no version information, might be only in CVS)
mysqli->commit -- Commits the current transactionProcedural style:
bool mysqli_commit ( object link)Object oriented style (method)
class mysqli {Commits the current transaction for the database connection specified by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The mysqli_connect_errno() function will return the last error code number for last call to mysqli_connect(). If no errors have occured, this function will return zero.
Nota: Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.
An error code value for the last call to mysqli_connect(), if it failed. zero means no error occurred.
mysqli_connect(), mysqli_connect_error(), mysqli_errno(), mysqli_error(), mysqli_sqlstate()
The mysqli_connect_error() function is identical to the corresponding mysqli_connect_errno() function in every way, except instead of returning an integer error code the mysqli_connect_error() function will return a string representation of the last error to occur for the last mysqli_connect() call. If no error has occured, this function will return an empty string.
mysqli_connect(), mysqli_connect_errno(), mysqli_errno(), mysqli_error(), mysqli_sqlstate()
(PHP 5)
mysqli_connect(no version information, might be only in CVS)
mysqli() -- Open a new connection to the MySQL serverProcedural style
object mysqli_connect ( [string host [, string username [, string passwd [, string dbname [, int port [, string socket]]]]]])Object oriented style (constructor):
class mysqli {The mysqli_connect() function attempts to open a connection to the MySQL Server running on host which can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol. If successful, the mysqli_connect() will return an object representing the connection to the database, or FALSE on failure.
The username and password parameters specify the username and password under which to connect to the MySQL server. If the password is not provided (the NULL value is passed), the MySQL server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password as provided or not).
The dbname parameter if provided will specify the default database to be used when performing queries.
The port and socket parameters are used in conjunction with the host parameter to further control how to connect to the database server. The port parameter specifies the port number to attempt to connect to the MySQL server on, while the socket parameter specifies the socket or named pipe that should be used.
Nota: Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by the host parameter.
Returns a object which represents the connection to a MySQL Server or FALSE if the connection failed.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Host information: Localhost via UNIX socket |
(PHP 5)
mysqli_data_seek(no version information, might be only in CVS)
result->data_seek -- Adjusts the result pointer to an arbitary row in the resultProcedural style:
bool mysqli_data_seek ( object result, int offset)Object oriented style (method):
class result {The mysqli_data_seek() function seeks to an arbitrary result pointer specified by the offset in the result set represented by result. The offset parameter must be between zero and the total number of rows minus one (0..mysqli_num_rows() - 1).
Nota: This function can only be used with unbuffered results attained from the use of the mysqli_store_result() or mysqli_query() functions.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
City: Benin City Countrycode: NGA |
The mysqli_debug() function is used to perform debugging operations using the Fred Fish debugging library. The debug parameter is a string representing the debugging operation to perform.
Nota: To use the mysqli_debug() function you must complile the MySQL client library to support debugging.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
(PHP 5)
mysqli_dump_debug_info(no version information, might be only in CVS)
mysqli->dump_debug_info -- Dump debugging information into the logThis function is designed to be executed by an user with the SUPER privlege and is used to dump debugging information into the log for the MySQL Server relating to the connection specified by the link parameter.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
(PHP 5)
mysqli_errno(no version information, might be only in CVS)
mysqli->errno -- Returns the error code for the most recent function callProcedural style:
int mysqli_errno ( object link)Object oriented style (property):
class mysqli {The mysqli_errno() function will return the last error code for the most recent MySQLi function call that can succeed or fail with respect to the database link defined by the link parameter. If no errors have occured, this function will return zero.
Nota: Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Errorcode: 1193 |
Procedural style:
string mysqli_error ( object link)Object oriented style (property)
class mysqli {The mysqli_error() function is identical to the corresponding mysqli_errno() function in every way, except instead of returning an integer error code the mysqli_error() function will return a string representation of the last error to occur for the database connection represented by the link parameter. If no error has occured, this function will return an empty string.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Errormessage: Unknown system variable 'a' |
This function is an alias of mysqli_stmt_execute(). For a detailled descripton see description of mysqli_stmt_execute().
Nota: mysqli_execute() is deprecated and will be removed.
(PHP 5)
mysqli_fetch_array(no version information, might be only in CVS)
result->fetch_array -- Fetch a result row as an associative, a numeric array, or both.Procedural style:
mixed mysqli_fetch_array ( object result [, int resulttype])Object oriend style (method):
class result {Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.
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.
Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Kabul (AFG) Qandahar (AFG) Herat (AFG) |
(PHP 5)
mysqli_fetch_assoc(no version information, might be only in CVS)
mysqli->fetch_assoc -- Fetch a result row as an associative arrayProcedural style:
array mysqli_fetch_assoc ( object result)Object oriend style (method):
class result {Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.
The mysqli_fetch_assoc() function is used to return an associative array representing the next row in the result set for the result represented by the result parameter, where each key in the array represents the name of one of the result set's columns.
If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using mysqli_fetch_row() or add alias names.
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA) |
(PHP 5)
mysqli_fetch_field_direct(no version information, might be only in CVS)
result->fetch_field_direct -- Fetch meta-data for a single fieldProcedural style:
mixed mysqli_fetch_field_direct ( object result, int fieldnr)Object oriented style (method):
class result {mysqli_fetch_field_direct() returns an object which contains field definition informations from specified resultset. The value of fieldnr must be in the range from 0 to number of fields - 1.
Returns an object which contains field definition informations or FALSE if no field information for specified fieldnr is available.
Tabella 1. Object attributes
Attribute | Description |
---|---|
name | The name of the column |
orgname | Original column name if an alias was specified |
table | The name of the table this field belongs to (if not calculated) |
orgtable | Original table name if an alias was specified |
def | The default value for this field, represented as a string |
max_length | The maximum width of the field for the result set. |
flags | An integer representing the bit-flags for the field. |
type | The data type used for this field |
decimals | The number of decimals used (for integer fields) |
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Name: SurfaceArea Table: Country max. Len: 10 Flags: 32769 Type: 4 |
(PHP 5)
mysqli_fetch_field(no version information, might be only in CVS)
result->fetch_field -- Returns the next field in the result setProcedural style:
mixed mysqli_fetch_field ( object result)Object oriented style (method):
class result {The mysqli_fetch_field() returns the definition of one column of a result set as an object. Call this function repeatedly to retrieve information about all columns in the result set. mysqli_fetch_field() returns FALSE when no more fields are left.
Returns an object which contains field definition informations or FALSE if no field information is available.
Tabella 1. Object properties
Property | Description |
---|---|
name | The name of the column |
orgname | Original column name if an alias was specified |
table | The name of the table this field belongs to (if not calculated) |
orgtable | Original table name if an alias was specified |
def | The default value for this field, represented as a string |
max_length | The maximum width of the field for the result set. |
flags | An integer representing the bit-flags for the field. |
type | The data type used for this field |
decimals | The number of decimals used (for integer fields) |
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
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 |
(PHP 5)
mysqli_fetch_fields(no version information, might be only in CVS)
result->fetch_fields -- Returns an array of objects representing the fields in a result setProcedural Style:
mixed mysqli_fetch_fields ( object result)Object oriented style (method):
class result {This function serves an identical purpose to the mysqli_fetch_field() function with the single difference that, instead of returning one object at a time for each field, the columns are returned as an array of objects.
Returns an array of objects which contains field definition informations or FALSE if no field information is available.
Tabella 1. Object properties
Property | Description |
---|---|
name | The name of the column |
orgname | Original column name if an alias was specified |
table | The name of the table this field belongs to (if not calculated) |
orgtable | Original table name if an alias was specified |
def | The default value for this field, represented as a string |
max_length | The maximum width of the field for the result set. |
flags | An integer representing the bit-flags for the field. |
type | The data type used for this field |
decimals | The number of decimals used (for integer fields) |
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
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 |
(PHP 5)
mysqli_fetch_lengths(no version information, might be only in CVS)
result->lengths -- Returns the lengths of the columns of the current row in the result setProcedural style:
mixed mysqli_fetch_lengths ( object result)Object oriented style (property):
class result {The mysqli_fetch_lengths() function returns an array containing the lengths of every column of the current row within the result set represented by the result parameter. If successful, a numerically indexed array representing the lengths of each column is returned or FALSE on failure.
An array of integers representing the size of each column (not including any terminating null characters). FALSE if an error occurred.
mysqli_fetch_lengths() is valid only for the current row of the result set. It returns FALSE if you call it before calling mysqli_fetch_row/array/object or after retrieving all rows in the result.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
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 |
(PHP 5)
mysqli_fetch_object(no version information, might be only in CVS)
result->fetch_object -- Returns the current row of a result set as an objectProcedural style:
mixed mysqli_fetch_object ( object result)Object oriented style (method):
class result {The mysqli_fetch_object() will return the current row result set as an object where the attributes of the object represent the names of the fields found within the result set. If no more rows exist in the current result set, NULL is returned.
Returns an object that corresponds to the fetched row or NULL if there are no more rows in resultset.
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA) |
(PHP 5)
mysqli_fetch_row(no version information, might be only in CVS)
result->fetch_row -- Get a result row as an enumerated arrayProcedural style:
mixed mysqli_fetch_row ( object result)Object oriented style (method):
class result {Returns an array that corresponds to the fetched row, or NULL if there are no more rows.
mysqli_fetch_row() fetches one row of data from the result set represented by result and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to the mysqli_fetch_row() function will return the next row within the result set, or FALSE if there are no more rows.
mysqli_fetch_row() returns an array that corresponds to the fetched row or NULL if there are no more rows in result set.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA) |
This function is an alias of mysqli_stmt_fetch(). For a detailled descripton see description of mysqli_stmt_fetch().
Nota: mysqli_fetch() is deprecated and will be removed.
(PHP 5)
mysqli_field_count(no version information, might be only in CVS)
mysqli->field_count -- Returns the number of columns for the most recent queryProcedural style:
int mysqli_field_count ( object link)Object oriented style (method):
class mysql {Returns the number of columns for the most recent query on the connection represented by the link parameter. This function can be useful when using the mysqli_store_result() function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
(PHP 5)
mysqli_field_seek(no version information, might be only in CVS)
result->field_seek -- Set result pointer to a specified field offsetProcedural style:
int mysqli_field_seek ( object result, int fieldnr)Object oriented style (method):
class result {Sets the field cursor to the given offset. The next call to mysqli_fetch_field() will retrieve the field definition of the column associated with that offset.
Nota: To seek to the beginning of a row, pass an offset value of zero.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Name: SurfaceArea Table: Country max. Len: 10 Flags: 32769 Type: 4 |
(PHP 5)
mysqli_field_tell(no version information, might be only in CVS)
result->current_field -- Get current field offset of a result pointerProcedural style:
int mysqli_field_tell ( object result)Object oriented style (property):
class result {Returns the position of the field cursor used for the last mysqli_fetch_field() call. This value can be used as an argument to mysqli_field_seek().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
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 |
(PHP 5)
mysqli_free_result(no version information, might be only in CVS)
result->free -- Frees the memory associated with a resultProcedural style:
void mysqli_free_result ( object result)Object oriented style (method):
class result {The mysqli_free_result() function frees the memory associated with the result represented by the result parameter, which was allocated by mysqli_query(), mysqli_store_result() or mysqli_use_result().
Nota: You should always free your result with mysqli_free_result(), when your result object is not needed anymore.
mysqli_query(), mysqli_stmt_store_result(), mysqli_store_result(), mysqli_use_result().
The mysqli_get_client_info() function is used to return a string representing the client version being used in the MySQLi extension.
A number that represents the MySQL client library version in format: main_version*10000 + minor_version *100 + sub_version. For example, 4.1.0 is returned as 40100.
This is useful to quickly determine the version of the client library to know if some capability exits.
(PHP 5)
mysqli_get_host_info(no version information, might be only in CVS)
mysqli->get_host_info -- Returns a string representing the type of connection usedProcdural style:
string mysqli_get_host_info ( object link)Object oriented style (property):
class mysqli {The mysqli_get_host_info() function returns a string describing the connection represented by the link parameter is using (including the server host name).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Host info: Localhost via UNIX socket |
This function is an alias of mysqli_stmt_result_metadata(). For a detailled descripton see description of mysqli_stmt_result_metadata().
Nota: mysqli_get_metadata() is deprecated and will be removed.
(PHP 5)
mysqli_get_proto_info(no version information, might be only in CVS)
mysqli->protocol_version -- Returns the version of the MySQL protocol usedProcedural style:
int mysqli_get_proto_info ( object link)Object oriented style (property):
class mysqli {Returns an integer representing the MySQL protocol version used by the connection represented by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Protocol version: 10 |
(PHP 5)
mysqli_get_server_info(no version information, might be only in CVS)
mysqli->server_info -- Returns the version of the MySQL serverProcedural style:
string mysqli_get_server_info ( object link)Object oriented style (property):
class mysqli {Returns a string representing the version of the MySQL server that the MySQLi extension is connected to (represented by the link parameter).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Server version: 4.1.2-alpha-debug |
Procedural style:
int mysqli_get_server_version ( object link)Object oriented style (property):
class mysqli {The mysqli_get_server_version() function returns the version of the server connected to (represented by the link parameter) as an integer.
The form of this version number is main_version * 10000 + minor_version * 100 + sub_version (i.e. version 4.1.0 is 40100).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Server version: 40102 |
(PHP 5)
mysqli_info(no version information, might be only in CVS)
mysqli->info -- Retrieves information about the most recently executed queryProcedural style:
string mysqli_info ( object link)Object oriented style (property)
class mysqli {The mysqli_info() function returns a string providing information about the last query executed. The nature of this string is provided below:
Tabella 1. Possible mysqli_info return values
Query type | Example result string |
---|---|
INSERT INTO...SELECT... | Records: 100 Duplicates: 0 Warnings: 0 |
INSERT INTO...VALUES (...),(...),(...) | Records: 3 Duplicates: 0 Warnings: 0 |
LOAD DATA INFILE ... | Records: 1 Deleted: 0 Skipped: 0 Warnings: 0 |
ALTER TABLE ... | Records: 3 Duplicates: 0 Warnings: 0 |
UPDATE ... | Rows matched: 40 Changed: 40 Warnings: 0 |
Nota: Queries which do not fall into one of the above formats are not supported. In these situations, mysqli_info() will return an empty string.
A character string representing additional information about the most recently executed query.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Records: 150 Duplicates: 0 Warnings: 0 |
Allocates or initializes a MYSQL object suitable for mysqli_options() and mysqli_real_connect().
Nota: Any subsequent calls to any mysqli function (except mysqli_options()) will fail until mysqli_real_connect() was called.
(PHP 5)
mysqli_insert_id(no version information, might be only in CVS)
mysqli->insert_id -- Returns the auto generated id used in the last queryProcedural style:
mixed mysqli_insert_id ( object link)Object oriented style (property):
class mysqli {The mysqli_insert_id() function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.
Nota: Performing an INSERT or UPDATE statement using the LAST_INSERT_ID() function will also modify the value returned by the mysqli_insert_id() function.
The value of the AUTO_INCREMENT field that was updated by the previous query. Returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value.
Nota: If the number is greater than maximal int value, mysqli_insert_id() will return a string.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
New Record has id 1. |
(PHP 5)
mysqli_kill(no version information, might be only in CVS)
mysqli->kill -- Asks the server to kill a MySQL threadProcedural style:
bool mysqli_kill ( object link, int processid)Object oriented style (method)
class mysqli {This function is used to ask the server to kill a MySQL thread specified by the processid parameter. This value must be retrieved by calling the mysqli_thread_id() function.
Nota: To stop a running query you should use the SQL command KILL QUERY processid.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Error: MySQL server has gone away |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
(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.mysqli_more_results() indicates if one or more result sets are available from a previous call to mysqli_multi_query().
(PHP 5)
mysqli_multi_query(no version information, might be only in CVS)
mysqli->multi_query -- Performs a query on the databaseProcedural style:
bool mysqli_multi_query ( object link, string query)Object oriented style (method):
class mysqli {The mysqli_multi_query() executes one or multiple queries which are concatenated by a semicolon.
To retrieve the resultset from the first query you can use mysqli_use_result() or mysqli_store_result(). All subsequent query results can be processed using mysqli_more_results() and mysqli_next_result().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
my_user@localhost ----------------- Amersfoort Maastricht Dordrecht Leiden Haarlemmermeer |
(PHP 5)
mysqli_next_result(no version information, might be only in CVS)
mysqli->next_result -- prepare next result from multi_query.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().
(PHP 5)
mysqli_num_fields(no version information, might be only in CVS)
result->field_count -- Get the number of fields in a resultProcedural style:
int mysqli_num_fields ( object result)Object oriented style (property):
class result {mysqli_num_fields() returns the number of fields from specified result set.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Result set has 5 fields. |
Procedural style:
mixed mysqli_num_rows ( object result)Object oriented style (property):
class mysqli {Returns the number of rows in the result set.
The use of mysqli_num_rows() depends on whether you use buffered or unbuffered result sets. In case you use unbuffered resultsets mysqli_num_rows() will not correct the correct number of rows until all the rows in the result have been retrieved.
Returns number of rows in the result set.
Nota: If the number of rows is greater than maximal int value, the number will be returned as a string.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Result set has 239 rows. |
Procedural style:
bool mysqli_options ( object link, int option, mixed value)Object oriented style (method)
class mysqli {mysqli_options() can be used to set extra connect options and affect behavior for a connection.
This function may be called multiple times to set several options.
mysqli_options() should be called after mysqli_init() and before mysqli_real_connect().
The parameter option is the option that you want to set, the value is the value for the option. The parameter option can be one of the following values:
Tabella 1. Valid options
Name | Description |
---|---|
MYSQLI_OPT_CONNECT_TIMEOUT | connection timeout in seconds |
MYSQLI_OPT_COMPRESS | use compression protocol |
MYSQLI_OPT_LOCAL_INFILE | enable/disable use of LOAD LOCAL INFILE |
MYSQLI_INIT_CMD | command to execute after when connecting to MySQL server |
MYSQLI_READ_DEFAULT_FILE | Read options from named option file instead of my.cnf |
MYSQLI_READ_DEFAULT_GROUP | Read options from the named group from my.cnf or the file specified with MYSQL_READ_DEFAULT_FILE. |
This function is an alias of mysqli_stmt_param_count(). For a detailled descripton see description of mysqli_stmt_param_count().
Nota: mysqli_param_count() is deprecated and will be removed.
(PHP 5)
mysqli_ping(no version information, might be only in CVS)
mysqli->ping -- Pings a server connection, or tries to reconnect if the connection has gone down.Procedural style:
bool mysqli_ping ( object link)Object oriented style (method):
class mysqli {Checks whether the connection to the server is working. If it has gone down, and global option mysqli.reconnect is enabled an automatic reconnection is attempted.
This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Our connection is ok! |
(PHP 5)
mysqli_prepare(no version information, might be only in CVS)
mysqli->prepare -- Prepare a SQL statement for executionProcedure style:
mixed mysqli_prepare ( object link, string query)Object oriented style (method)
class stmt {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.
mysqli_stmt_execute(), mysqli_stmt_fetch(), mysqli_stmt_bind_param(), mysqli_stmt_bind_result(), mysqli_stmt_close()
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Amersfoort is in district Utrecht |
(PHP 5)
mysqli_query(no version information, might be only in CVS)
mysqli->query -- Performs a query on the databaseProcedural style:
mixed mysqli_query ( object link, string query [, int resultmode])Object oriented style (method):
class mysqli {The mysqli_query() function is used to simplify the act of performing a query against the database represented by the link parameter.
Functionally, using this function is identical to calling mysqli_real_query() followed either by mysqli_use_result() or mysqli_store_result() where query is the query string itself and resultmode is either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, if the resultmode is not provided MYSQLI_STORE_RESULT is used.
If you execute mysqli_query() with resultmode MYSQLI_USE_RESULT all subsequent calls will return error Commands out of sync unless you call mysqli_free_result().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
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 |
(PHP 5)
mysqli_real_connect(no version information, might be only in CVS)
mysqli->real_connect -- Opens a connection to a mysql serverProcedural style
bool mysqli_real_connect ( object link [, string hostname [, string username [, string passwd [, string dbname [, int port [, string socket [, int flags]]]]]]])Object oriented style (method)
class mysqli {mysqli_real_connect() attempts to establish a connection to a MySQL database engine running on hostname.
This function differs from mysqli_connect():
mysqli_real_connect() needs a valid object which has to be created by function mysqli_init()
With function mysqli_options() you can set various options for connection.
With the parameter flags you can set different connection options:
Tabella 1. Supported flags
Name | Description |
---|---|
MYSQLI_CLIENT_COMPRESS | Use compression protocol |
MYSQLI_CLIENT_FOUND_ROWS | return number of matched rows, not the number of affected rows |
MYSQLI_CLIENT_IGNORE_SPACE | Allow spaces after function names. Makes all function names reserved words. |
MYSQLI_CLIENT_INTERACTIVE | Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection |
MYSQLI_CLIENT_SSL | Use SSL (encryption) |
Nota: For security reasons the MULTI_STATEMENT flag is not supported in PHP. If you want to execute multiple queries use the mysqli_multi_query() function.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Connection: Localhost via UNIX socket |
(PHP 5)
mysqli_real_escape_string(no version information, might be only in CVS)
mysqli->real_escape_string -- Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connectionProcedural style:
string mysqli_real_escape_string ( object link, string escapestr)Object oriented style (method):
class mysqli {This function is used to create a legal SQL string that you can use in a SQL statement. The string escapestr is encoded to an escaped SQL string, taking into account the current character set of the connection.
Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Error: 42000 1 Row inserted. |
(PHP 5)
mysqli_real_query(no version information, might be only in CVS)
mysqli->real_query -- Execute an SQL queryProcedural style
bool mysqli_real_query ( object link, string query)Object oriented style (method):
class mysqli {The mysqli_real_query() function is used to execute only a query against the database represented by the link whose result can then be retrieved or stored using the mysqli_store_result() or mysqli_use_result() functions.
Nota: In order to determine if a given query should return a result set or not, see mysqli_field_count().
mysqli_report() is a powerful function to improve your queries and code during development and testing phase. Depending on the flags it reports errors from mysqli function calls or queries which don't use an index (or use a bad index).
Esempio 1. Object oriented style
|
(PHP 5)
mysqli_rollback(no version information, might be only in CVS)
mysqli->rollback -- Rolls back current transactionRollbacks the current transaction for the database specified by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
0 rows in table myCity. 50 rows in table myCity (after rollback). |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
(PHP 5)
mysqli_select_db(no version information, might be only in CVS)
mysqli->select_db -- Selects the default database for database queriesThe mysqli_select_db() function selects the default database (specified by the dbname parameter) to be used when performing queries against the database connection represented by the link parameter.
Nota: This function should only be used to change the default database for the connection. You can select the default database with 4th parameter in mysqli_connect().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Default database is test. Default database is world. |
This function is an alias of mysqli_stmt_send_long_data(). For a detailled descripton see description of mysqli_stmt_send_long_data().
Nota: mysqli_send_long_data() is deprecated and will be removed.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
(PHP 5)
mysqli_sqlstate(no version information, might be only in CVS)
mysqli->sqlstate -- Returns the SQLSTATE error from previous MySQL operation.Procedural style:
string mysqli_sqlstate ( object link)Object oriented style (property):
class mysqli {Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see http://dev.mysql.com/doc/mysql/en/Error-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.
Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Error - SQLSTATE 42S01. |
(PHP 5)
mysqli_ssl_set(no version information, might be only in CVS)
mysqli->ssl_set -- Used for establishing secure connections using SSL.Procedural style:
bool mysqli_ssl_set ( object link [, string key [, string cert [, string ca [, string capath [, string cipher]]]]])Object oriented style (method):
class mysqli {The function mysqli_ssl_set() is used for establishing secure connections using SSL. It must be called before mysqli_real_connect(). This function does nothing unless OpenSSL support is enabled.
key is the pathname to the key file. cert is the pathname to the certificate file. ca is the pathname to the certificate authority file. capath is the pathname to a directory that contains trusted SSL CA certificates in pem format. cipher is a list of allowable ciphers to use for SSL encryption. Any unused SSL parameters may be given as NULL
This function always returns TRUE value. If SSL setup is incorrect mysqli_real_connect() will return an error when you attempt to connect.
(PHP 5)
mysqli_stat(no version information, might be only in CVS)
mysqli->stat -- Gets the current system statusProcedural style:
mixed mysqli_stat ( object link)Object oriented style (method):
class mysqli {mysqli_stat() returns a string containing information similar to that provided by the 'mysqladmin status' command. This includes uptime in seconds and the number of running threads, questions, reloads, and open tables.
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 |
(PHP 5)
mysqli_stmt_affected_rows(no version information, might be only in CVS)
mysqli_stmt->affected_rows -- Returns the total number of rows changed, deleted, or inserted by the last executed statementProcedural style :
mixed mysqli_stmt_affected_rows ( object stmt)Object oriented style (property):
class stmt {mysqli_stmt_affected_rows() returns the number of rows affected by INSERT, UPDATE, or DELETE query. If the last query was invalid, this function will return -1.
The mysqli_stmt_affected_rows() function only works with queries which update a table. In order to return the number of rows from a SELECT query, use the mysqli_stmt_num_rows() function instead.
An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE/DELETE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query has returned an error.
Nota: If the number of affected rows is greater than maximal PHP int value, the number of affected rows will be returned as a string value.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
rows inserted: 17 |
(PHP 5)
mysqli_stmt_bind_param(no version information, might be only in CVS)
stmt->bind_param -- Binds variables to a prepared statement as parametersProcedural style:
bool mysqli_stmt_bind_param ( object stmt, string types, mixed var1 [, mixed var2, ...])Object oriented style (method):
class stmt {mysqli_stmt_bind_param() is used to bind variables for the parameter markers in the SQL statement that was passed to mysqli_prepare(). The string types contains one or more characters which specify the types for the corresponding bind variables
Tabella 1. Type specification chars
Character | Description |
---|---|
i | corresponding variable has type integer |
d | corresponding variable has type double |
s | corresponding variable has type string |
b | corresponding variable is a blob and will be send in packages |
Nota: If data size of a variable exceeds max. allowed package size (max_allowed_package), you have to specify b in types and use mysqli_stmt_send_long_data() to send the data in packages.
The number of variables and length of string types must match the parameters in the statement.
mysqli_stmt_bind_result(), mysqli_stmt_execute(), mysqli_stmt_fetch(), mysqli_prepare(), mysqli_stmt_send_long_data(), mysqli_stmt_errno(), mysqli_stmt_error()
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
1 Row inserted. 1 Row deleted. |
(PHP 5)
mysqli_stmt_bind_result(no version information, might be only in CVS)
stmt->bind_result -- Binds variables to a prepared statement for result storageProcedural style:
bool mysqli_stnt_bind_result ( object stmt, mixed var1 [, mixed var2, ...])Object oriented style (method):
class stmt {mysqli_stmt_bind_result() is used to associate (bind) columns in the result set to variables. When mysqli_stmt_fetch() is called to fetch data, the MySQL client/server protocol places the data for the bound columns into the specified variables var1, ....
Nota: Note that all columns must be bound prior to calling mysqli_stmt_fetch(). Depending on column types bound variables can silently change to the corresponding PHP type.
A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time mysqli_stmt_fetch() is called.
mysqli_stmt_bind_param(), mysqli_stmt_execute(), mysqli_stmt_fetch(), mysqli_prepare(), mysqli_stmt_prepare(), mysqli_stmt_init(), mysqli_stmt_errno(), mysqli_stmt_error()
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
AFG Afghanistan ALB Albania DZA Algeria ASM American Samoa AND Andorra |
(PHP 5)
mysqli_stmt_close(no version information, might be only in CVS)
mysqli_stmt->close -- Closes a prepared statementProcedural style:
bool mysqli_stmt_close ( object stmt)Object oriented style (method):
class mysqli_stmt {Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle pointed to by stmt. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.
(PHP 5)
mysqli_stmt_data_seek(no version information, might be only in CVS)
stmt->data_seek -- Seeks to an arbitray row in statement result setProcedural style:
bool mysqli_stmt_data_seek ( object statement, int offset)Object oriented style (method):
class stmt {The mysqli_stmt_data_seek() function seeks to an arbitrary result pointer specified by the offset in the statement result set represented by statement. The offset parameter must be between zero and the total number of rows minus one (0..mysqli_stmt_num_rows() - 1).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
City: Benin City Countrycode: NGA |
(PHP 5)
mysqli_stmt_errno(no version information, might be only in CVS)
mysqli_stmt->errno -- Returns the error code for the most recent statement callProcedural style :
int mysqli_stmt_errno ( object stmt)Object oriented style (property):
class stmt {For the statement specified by stmt, mysqli_stmt_errno() returns the error code for the most recently invoked statement function that can succeed or fail.
Nota: Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Error: 1146. |
(PHP 5)
mysqli_stmt_error(no version information, might be only in CVS)
mysqli_stmt->error -- Returns a string description for last statement errorProcedural style:
string mysqli_stmt_error ( object stmt)Object oriented style (property):
class stmt {For the statement specified by stmt, mysqli_stmt_error() returns a containing the error message for the most recently invoked statement function that can succeed or fail.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Error: Table 'world.myCountry' doesn't exist. |
(PHP 5)
mysqli_stmt_execute(no version information, might be only in CVS)
stmt->execute -- Executes a prepared QueryProcedural style:
bool mysqli_stmt_execute ( object stmt)Object oriented style (method):
class stmt {The mysqli_stmt_execute() function executes a query that has been previously prepared using the mysqli_prepare() function represented by the stmt object. When executed any parameter markers which exist will automatically be replaced with the appropiate data.
If the statement is UPDATE, DELETE, or INSERT, the total number of affected rows can be determined by using the mysqli_stmt_affected_rows() function. Likewise, if the query yields a result set the mysqli_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.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Stuttgart (DEU,Baden-Wuerttemberg) Bordeaux (FRA,Aquitaine) |
(PHP 5)
mysqli_stmt_fetch(no version information, might be only in CVS)
stmt->fetch -- Fetch results from a prepared statement into the bound variablesProcedural style:
mixed mysqli_stmt_fetch ( object stmt)Object oriented style (method):
class stmt {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().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Rockford (USA) Tallahassee (USA) Salinas (USA) Santa Clarita (USA) Springfield (USA) |
(PHP 5)
mysqli_stmt_free_result(no version information, might be only in CVS)
stmt->free_result -- Frees stored result memory for the given statement handleProcedural style:
void mysqli_stmt_free_result ( object stmt)Object oriented style (method):
class stmt {The mysqli_stmt_free_result() function frees the result memory associated with the statement represented by the stmt parameter, which was allocated by mysqli_stmt_store_result().
(PHP 5)
mysqli_stmt-init(no version information, might be only in CVS)
mysqli->stmt_init -- Initializes a statement and returns an object for use with mysqli_stmt_prepareProcedural style :
object mysqli_stmt_init ( object link)Object oriented style (property):
class mysqli {Allocates and initializes a statement object suitable for mysqli_stmt_prepare().
Nota: Any subsequent calls to any mysqli_stmt function will fail until mysqli_stmt_prepare() was called.
(PHP 5)
mysqli_stmt_num_rows(no version information, might be only in CVS)
stmt->num_rows -- Return the number of rows in statements result set.Procedural style :
mixed mysqli_stmt_num_rows ( object stmt)Object oriented style (property):
class stmt {Returns the number of rows in the result set. The use of mysqli_stmt_num_rows() depends on whether or not you used mysqli_stmt_store_result() to buffer the entire result set in the statement handle.
If you use mysqli_stmt_store_result(), mysqli_stmt_num_rows() may be called immediately.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Number of rows: 20. |
(PHP 5)
mysqli_stmt_param_count(no version information, might be only in CVS)
stmt->param_count -- Returns the number of parameter for the given statementProcedural style:
int mysqli_stmt_param_count ( object stmt)Object oriented style (property):
class stmt {mysqli_stmt_param_count() returns the number of parameter markers present in the prepared statement.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Statement has 2 markers. |
(PHP 5)
mysqli_stmt_prepare(no version information, might be only in CVS)
stmt->prepare -- Prepare a SQL statement for executionProcedure style:
bool mysqli_stmt_prepare ( object stmt, string query)Object oriented style (method)
class stmt {mysqli_stmt_prepare() prepares the SQL query pointed to by the null-terminated string query. The statement object has to be allocated by mysqli_stmt_init(). The query must consist of a single SQL statement.
Nota: You should not add a terminating semicolon or \g to the statement.
The parameter query can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.
Nota: The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.
However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.
The parameter markers must be bound to application variables using mysqli_stmt_bind_param() and/or mysqli_stmt_bind_result() before executing the statement or fetching rows.
mysqli_stmt_init(), mysqli_stmt_execute(), mysqli_stmt_fetch(), mysqli_stmt_bind_param(), mysqli_stmt_bind_result(), mysqli_stmt_close()
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Amersfoort is in district Utrecht |
(PHP 5)
mysqli_stmt_reset(no version information, might be only in CVS)
stmt->reset -- Resets a prepared statementProcedural style:
bool mysqli_stmt_reset ( object stmt)Object oriented style (method):
class stmt {The mysqli_stmt_reset() resets a prepared statement on client and server to state after prepare. For now this is mainly used to reset data sent with mysqli_stmt_send_long_data().
Nota: To reprepare a statement with an other query use function mysqli_stmt_prepare().
Procedural style:
mixed mysqli_stmt_result_metadata ( object stmt)Object oriented style (method):
class stmt {If a statement passed to mysqli_prepare() is one that produces a result set, mysqli_stmt_result_metadata() returns the result object that can be used to process the meta information such as total number of fields and individual field information.
Nota: This result set pointer can be passed as an argument to any of the field-based functions that process result set metadata, such as:
The result set structure should be freed when you are done with it, which you can do by passing it to mysqli_free_result()
Nota: The result set returned by mysqli_stmt_result_metadata() contains only metadata. It does not contain any row results. The rows are obtained by using the statement handle with mysqli_fetch().
mysqli_stmt_result_metadata() returns a result object or FALSE if an error occured.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
(PHP 5)
mysqli_stmt_send_long_data(no version information, might be only in CVS)
stmt->send_long_data -- Send data in blocksProcedural style:
bool mysqli_stmt_send_long_data ( object stmt, int param_nr, string data)Object oriented style (method)
class stmt {Allows to send parameter data to the server in pieces (or chunks), e.g. if the size of a blob exceeds the size of max_allowed_packet. This function can be called multiple times to send the parts of a character or binary data value for a column, which must be one of the TEXT or BLOB datatypes.
param_nr indicates which parameter to associate the data with. Parameters are numbered beginning with 0. data is a string containing data to be sent.
Returns a string containing the SQLSTATE error code for the most recently invoked prepared statement function that can succeed or fail. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see http://dev.mysql.com/doc/mysql/en/Error-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.
Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Error: 42S02. |
(PHP 5)
mysqli_stmt_store_result(no version information, might be only in CVS)
mysqli_stmt->store_result -- Transfers a result set from a prepared statementProcedural style:
bool mysqli_stmt_store_result ( object stmt)Object oriented style (method):
class mysqli_stmt {You must call mysqli_stmt_store_result() for every query that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN), and only if you want to buffer the complete result set by the client, so that the subsequent mysqli_fetch() call returns buffered data.
Nota: It is unnecessary to call mysqli_stmt_store_result() for other queries, but if you do, it will not harm or cause any notable performance in all cases. You can detect whether the query produced a result set by checking if mysqli_stmt_result_metadata() returns NULL.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Number of rows: 20. |
(PHP 5)
mysqli_store_result(no version information, might be only in CVS)
mysqli->store_result -- Transfers a result set from the last queryProcedural style:
object mysqli_store_result ( object link)Object oriented style (method):
class mysqli {Transfers the result set from the last query on the database connection represented by the link parameter to be used with the mysqli_data_seek() function.
Nota: Although it is always good practice to free the memory used by the result of a query using the mysqli_free_result() function, when transfering large result sets using the mysqli_store_result() this becomes particularly important.
Nota: mysqli_store_result() returns FALSE in case the query didn't return a result set (if the query was, for example an INSERT statement). This function also returns FALSE if the reading of the result set failed. You can check if you have got an error by checking if mysqli_error() doesn't return an empty string, if mysqli_errno() returns a non zero value, or if mysqli_field_count() returns a non zero value. Also possible reason for this function returning FALSE after successfull call to mysqli_query() can be too large result set (memory for it cannot be allocated). If mysqli_field_count() returns a non-zero value, the statement should have produced a non-empty result set.
(PHP 5)
mysqli_thread_id(no version information, might be only in CVS)
mysqli->thread_id -- Returns the thread ID for the current connectionProcedural style:
int mysqli_thread_id ( object link)Object oriented style (property):
class mysqli {The mysqli_thread_id() function returns the thread ID for the current connection which can then be killed using the mysqli_kill() function. If the connection is lost and you reconnect with mysqli_ping(), the thread ID will be other. Therefore you should get the thread ID only when you need it.
Nota: The thread ID is assigned on a connection-by-connection basis. Hence, if the connection is broken and then re-established a new thread ID will be assigned.
To kill a running query you can use the SQL command KILL QUERY processid.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Error: MySQL server has gone away |
Procedural style:
bool mysqli_thread_safe ( void )mysqli_thread_safe() indicates whether the client library is compiled as thread-safe.
(PHP 5)
mysqli_use_result(no version information, might be only in CVS)
mysqli->use_result -- Initiate a result set retrievalProcedural style:
mixed mysqli_use_result ( object link)Object oriented style (method):
class mysqli {mysqli_use_result() is used to initiate the retrieval of a result set from the last query executed using the mysqli_real_query() function on the database connection specified by the link parameter. Either this or the mysqli_store_result() function must be called before the results of a query can be retrieved, and one or the other must be called to prevent the next query on that database connection from failing.
Nota: The mysqli_use_result() function does not transfer the entire result set from the database and hence cannot be used functions such as mysqli_data_seek() to move to a particular row within the set. To use this functionality, the result set must be stored using mysqli_store_result(). One should not use mysqli_use_result() if a lot of processing on the client side is performed, since this will tie up the server and prevent other threads from updating any tables from which the data is being fetched.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
my_user@localhost ----------------- Amersfoort Maastricht Dordrecht Leiden Haarlemmermeer |
(PHP 5)
mysqli_warning_count(no version information, might be only in CVS)
mysqli->warning_count -- Returns the number of warnings from the last query for the given linkProcedural style:
int mysqli_warning_count ( object link)Object oriented style (property):
class mysqli {mysqli_warning_count() returns the number of warnings from the last query in the connection represented by the link parameter.
Nota: For retrieving warning messages you can use the SQL command SHOW WARNINGS [limit row_count].
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Warning (1264): Data truncated for column 'Name' at row 1 |
msession is an interface to a high speed session daemon which can run either locally or remotely. It is designed to provide consistent session management for a PHP web farm. More Information about msession and the session server software itself can be found at http://devel.mohawksoft.com/msession.html.
Nota: Questo modulo non è disponibile su piattaforme Windows.
To enable Msession support configure PHP --with-msession[=DIR], where DIR is the Msession install directory.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Returns an associative array of value/session for all sessions with a variable named name.
Used for searching sessions with common attributes.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
msession_plugin -- Call an escape function within the msession personality pluginAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
(4.0.5 - 4.2.3 only)
muscat_close -- Shuts down the muscat session and releases any memory back to PHP.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
[Not back to the system, note!]
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
muscat_setup_net() creates a new muscat session and returns the handle.
muscat_host is the hostname to connect to. port is the port number to connect to.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
size is the amount of memory in bytes to allocate for muscat. muscat_dir is the muscat installation dir e.g. "/usr/local/empower", it defaults to the compile time muscat directory.
(PHP 3, PHP 4 , PHP 5)
checkdnsrr -- Controlla i record DNS relativi ad un host Internet o indirizzo IPCerca i record DNS del tipo type corrispondenti a host. Restituisce vero se dei records sono trovati; falso se nessun record viene trovato o in caso di errore.
type può essere uno dei seguenti: A, MX, NS, SOA, PTR, CNAME, oppure ANY. Il default è MX.
Host può essere sia l'indirizzo IP in notazione decimale o il nome dell'host.
Nota: Questa funzione non è implementata su piattaforme Windows
Vedere anche getmxrr(), gethostbyaddr(), gethostbyname(), gethostbynamel() e la man page named(8).
closelog() chiude il descrittore usato per scrivere al logger di sistema. L'uso di closelog() è facoltativo.
Vedere anche define_syslog_variables(), syslog() e openlog().
Disattiva il debugger interno PHP. Il debugger è ancora in fase di sviluppo.
Attiva il debugger interno PHP, connettendolo ad indirizzo. Il debugger è in fase di sviluppo.
Inizializza tutte le costanti usate nelle funzioni del syslog.
Vedere anche openlog(), syslog() e closelog().
Check DNS records corresponding to a given Internet host name or IP address
Get MX records corresponding to a given Internet host name.
This function returns an array of associative arrays. Each associative array contains at minimum the following keys:
Tabella 1. Basic DNS attributes
Attribute | Meaning |
---|---|
host | The record in the DNS namespace to which the rest of the associated data refers. |
class | dns_get_record() only returns Internet class records and as such this parameter will always return IN. |
type | String containing the record type. Additional attributes will also be contained in the resulting array dependant on the value of type. See table below. |
ttl | Time To Live remaining for this record. This will not equal the record's original ttl, but will rather equal the original ttl minus whatever length of time has passed since the authoritative name server was queried. |
hostname should be a valid DNS hostname such as "www.example.com". Reverse lookups can be generated using in-addr.arpa notation, but gethostbyaddr() is more suitable for the majority of reverse lookups.
By default, dns_get_record() will search for any resource records associated with hostname. To limit the query, specify the optional type parameter. type may be any one of the following: DNS_A, DNS_CNAME, DNS_HINFO, DNS_MX, DNS_NS, DNS_PTR, DNS_SOA, DNS_TXT, DNS_AAAA, DNS_SRV, DNS_NAPTR, DNS_ALL or DNS_ANY. The default is DNS_ANY.
Nota: Because of eccentricities in the performance of libresolv between platforms, DNS_ANY will not always return every record, the slower DNS_ALL will collect all records more reliably.
The optional third and fourth arguments to this function, authns and addtl are passed by reference and, if given, will be populated with Resource Records for the Authoritative Name Servers, and any Additional Records respectively. See the example below.
Tabella 2. Other keys in associative arrays dependant on 'type'
Type | Extra Columns |
---|---|
A | ip: An IPv4 addresses in dotted decimal notation. |
MX | pri: Priority of mail exchanger. Lower numbers indicate greater priority. target: FQDN of the mail exchanger. See also dns_get_mx(). |
CNAME | target: FQDN of location in DNS namespace to which the record is aliased. |
NS | target: FQDN of the name server which is authoritative for this hostname. |
PTR | target: Location within the DNS namespace to which this record points. |
TXT | txt: Arbitrary string data associated with this record. |
HINFO | cpu: IANA number designating the CPU of the machine referenced by this record. os: IANA number designating the Operating System on the machine referenced by this record. See IANA's Operating System Names for the meaning of these values. |
SOA | mname: FQDN of the machine from which the resource records originated. rname: Email address of the administrative contain for this domain. serial: Serial # of this revision of the requested domain. refresh: Refresh interval (seconds) secondary name servers should use when updating remote copies of this domain. retry: Length of time (seconds) to wait after a failed refresh before making a second attempt. expire: Maximum length of time (seconds) a secondary DNS server should retain remote copies of the zone data without a successful refresh before discarding. minimum-ttl: Minimum length of time (seconds) a client can continue to use a DNS resolution before it should request a new resolution from the server. Can be overridden by individual resource records. |
AAAA | ipv6: IPv6 address |
SRV | pri: (Priority) lowest priorities should be used first. weight: Ranking to weight which of commonly prioritized targets should be chosen at random. target and port: hostname and port where the requested service can be found. For additional information see: RFC 2782 |
NAPTR | order and pref: Equivalent to pri and weight above. flags, services, regex, and replacement: Parameters as defined by RFC 2915. |
Nota: Per DNS standards, email addresses are given in user.host format (for example: hostmaster.example.com as opposed to hostmaster@example.com), be sure to check this value and modify if necessary before using it with a functions such as mail().
Esempio 1. Using dns_get_record()
Produces output similar to the following:
|
Since it's very common to want the IP address of a mail server once the MX record has been resolved, dns_get_record() also returns an array in addtl which contains associate records. authns is returned as well containing a list of authoritative name servers.
Esempio 2. Using dns_get_record() and DNS_ANY
Produces output similar to the following:
|
See also dns_get_mx(), and dns_check_record()
(PHP 3, PHP 4 , PHP 5)
fsockopen -- Apre una connessione a un socket appartenente a un dominio Internet o UnixInizializza una connessione nel dominio Internet (AF_INET, usando TCP o UDP) o Unix (AF_UNIX). Per il dominio Internet, apre una connessione a un socket TCP verso l' hostname sulla porta port. hostname può essere in questo caso, sia un fully qualified domain name o un indirizzo IP. Per le connessioni UDP, è necessario specificare esplicitamente il protocollo, usando: 'udp://' come prefisso di hostname. Per il dominio Unix, hostname viene utilizzato come percorso verso il socket, in questo caso, porta deve essere impostato a 0. Il parametro opzionale timeout può essere usato per impostare un timeout in secondi per la chiamata di sistema connect.
A partire da PHP 4.3.0, se si è compilato con il supporto OpenSSL, si può prefissare hostname con 'ssl://' oppure 'tls://' per utilizzare una connessione client SSL o TLS su una connessione TCP/IP per connettersi all'host remoto.
fsockopen() restituisce un puntatore a file che può essere usato nelle altre funzioni orientate ai file (come fgets(), fgetss(), fputs(), fclose() e feof()).
Se la chiamata non ha successo, viene restituito FALSE e se gli argomenti opzionali errno e errstr sono presenti, vengono impostati a indicare l'errore a livello di sistema che è avvenuto nella chiamata alla funzione connect() del sistema operativo. Se il valore di errno restituito è 0 e la funzione restituisce FALSE, è un'indicazione che l'errore è avvenuto prima della chiamata di connect(). Questo è molto probabilmente legato ad un problema di inizializzazione del socket. Si noti che gli argomenti errno e errstr verranno sempre passati by reference.
A seconda dell'ambiente operativo, il dominio Unix o l'opzionale timeout della connect potrebbero non essere disponibili.
Il socket viene aperto di default in modo blocking. Si può passare al modo non-blocking usando socket_set_blocking().
Nota: Il parametro timeout è stato introdotto nel PHP 3.0.9 e il supporto UDP è stato aggiunto nel PHP 4.
(PHP 3, PHP 4 , PHP 5)
gethostbyaddr -- Ottiene l'host Internet corrispondente a un dato indirizzo IPRestituisce l'hostname dell'host Internet specificato da indirizzo_ip. Se occorre un errore, restituisce indirizzo_ip.
Vedere anche gethostbyname().
(PHP 3, PHP 4 , PHP 5)
gethostbyname -- Ottiene l'indirizzo IP corrispondente a un dato hostname InternetRestituisce l'indirizzo IP dell'host Internet specificato da hostname.
Vedere anche gethostbyaddr().
(PHP 3, PHP 4 , PHP 5)
gethostbynamel -- Ottiene la lista degli indirizzi IP corrispondenti a un dato hostname InternetRestituisce una lista di indirizzi IP che risolvono nei confronti dell'host Internet specificato da hostname.
Vedere anche gethostbyname(), gethostbyaddr(), checkdnsrr(), getmxrr() e la pagina man named(8).
Cerca nel DNS i record MX corrispondenti a hostname. Restituisce TRUE se ne vengono trovati. Restituisce FALSE se non ne vengono trovati o se avviene un errore.
La lista di record MX trovati viene messa nell'array mxhosts. Se viene indicato l'array weight, esso viene riempito con le informazioni ottenute sui vari pesi.
Vedere anche checkdnsrr(), gethostbyname(), gethostbynamel(), gethostbyaddr()e la pagina man named(8).
getprotobyname() restituisce il numero del protocollo associato al protocollo nome come in /etc/protocols.
Vedere anche: getprotobynumber().
(PHP 4 , PHP 5)
getprotobynumber -- Ottiene il nome del protocollo associato al numero del protocollogetprotobynumber() restituisce il nome del protocollo associato al protocollo numero come in /etc/protocols.
Vedere anche: getprotobyname().
(PHP 4 , PHP 5)
getservbyname -- Ottiene il numero di porta associato ad un servizio Internet e ad un protocollogetservbyname() restituisce la porta Internet corrispondente a servizio per il protocollo specificato come in /etc/services. protocollo può essere sia "tcp" che "udp" (scritti in minuscolo).
Vedere anche: getservbyport().
(PHP 4 , PHP 5)
getservbyport -- Ottiene il servizio Internet corrispondente ad una porta e ad un protocollogetservbyport() restituisce il servizio Internet associato a porta relativamente al protocollo specificato come in /etc/services. protocollo può essere sia "tcp" che "udp" (scritti in minuscolo).
Vedere anche: getservbyname().
(PHP 4 , PHP 5)
ip2long -- Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address. Converte una stringa contenente un indirizzo di rete del Protocollo Internet (IPv4) in un indirizzo espresso come tipo di dato int.La funzione ip2long() genera un indirizzo di rete Internet IPv4 a partire dalla rappresentazione in formato standard (stringa separata da punti).
Nota: Poiché il tipo di dato integer in PHP è signed e molti indirizzi IP risulterebbero essere interi negativi, è necessario usare il formattatore "%u" della funzione sprintf() e printf() per ottenere la rappresentazione in stringa dell'indirizzo IP in modo nsigned.
Vedere anche: long2ip()
(PHP 4 , PHP 5)
long2ip -- Converte un indirizzo di rete del Protocollo Internet (IPv4) in una stringa contenente un indirizzo espresso secondo la notazione standard di Internet.La funzione long2ip() genera un indirizzo Internet in formato separato da punti (es.: aaa.bbb.ccc.ddd) a partire dalla rappresentazione propria.
Vedere anche: ip2long()
openlog() apre una connessione al logger di sistema per un programma. La stringa ident viene aggiunta a ogni messaggio. Valori per option e facility sono dati di seguito. L'argomento option viene usato per indicare quali opzioni di loggin verranno usate durante la generazione di un messaggio di log. L'argomento facility viene usato per specificare quale tipo di programma sta loggando il messaggio. Questo permette di specificare (nella comfigurazione del syslog della macchina) come trattare i messaggi provenienti dalle diverse facility. L'uso di openlog() è opzionale. Viene chiamato automaticamente da syslog() se necessario, in tal caso ident sarà di default FALSE.
Tabella 1. Opzioni di openlog()
Costante | Descrizione |
---|---|
LOG_CONS | se si verifica un errore durante l'invio dei dati al logger di sistema, scrive direttamente sulla console di sistema |
LOG_NDELAY | apre immediatamente una connessione al logger |
LOG_ODELAY | (default) ritarda l'apertura della connessione fino a quando non viene loggato il primo messaggio |
LOG_PERROR | stampa un messaggio di log anche su standard error |
LOG_PID | include il PID in ciascun messaggio |
Tabella 2. Facility di openlog()
Costante | Descrizione |
---|---|
LOG_AUTH | messaggi di sicurezza/autorizzazione (usa LOG_AUTHPRIV nei sistemi dove è definita quella costante) |
LOG_AUTHPRIV | messaggi di sicurezza/autorizzazione (private) |
LOG_CRON | clock daemon (cron e at) |
LOG_DAEMON | altri demoni di sistema |
LOG_KERN | messaggi del kernel |
LOG_LOCAL0 ... LOG_LOCAL7 | riservato per il locale |
LOG_LPR | sottosistema line printer |
LOG_MAIL | sottosistema mail |
LOG_NEWS | sottosistema news di USENET |
LOG_SYSLOG | messaggi generati internamente da syslogd |
LOG_USER | messaggi generici user-level |
LOG_UUCP | sottosistema UUCP |
Vedere anche define_syslog_variables(), syslog() e closelog().
(PHP 3>= 3.0.7, PHP 4 , PHP 5)
pfsockopen -- Apre una connessione persistente Internet o di tipo domain socket UnixQuesta funzione si comporta esattamente come fsockopen() con la differenza che la connessione non viene chiusa dopo che lo script ha finito la sua esecuzione. È la versione persistente di fsockopen().
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.
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.
Imposta il valore di timeout per un descrittore socket, espresso come la somma di secondi e microsecondi.
Questa funzione era precedentemente chiamata set_socket_timeout(), ma questo uso è deprecato.
Vedere anche: fsockopen() e fopen().
syslog() genera un messaggio di log che viene distribuito dal logger di sistema. priorità è la combinazione della facility e del livello, valori utilizzabili sono riportati nella prossima sezione. L'argomento rimanente è il messaggio da inviare, eccetto i due caratteri %m che vengono sostituiti dalla stringa del messaggio di errore (strerror) corrispondente all'attuale valore di errno.
Tabella 1. Priorità syslog() (in ordine discendente)
Costante | Descrizione |
---|---|
LOG_EMERG | sistema non utilizzabile |
LOG_ALERT | azione da intraprendere immediatamente |
LOG_CRIT | condizioni critiche |
LOG_ERR | condizioni di errore |
LOG_WARNING | condizioni di attenzione |
LOG_NOTICE | condizione normale, ma significativa |
LOG_INFO | messaggio di informazione |
LOG_DEBUG | messaggio a livello di debug |
Esempio 1. Uso di syslog()
|
Su Windows NT, il servizio syslog è emulato usando Event Log.
Vedere anche define_syslog_variables(), openlog() e closelog().
ncurses (new curses) is a free software emulation of curses in System V Rel 4.0 (and above). It uses terminfo format, supports pads, colors, multiple highlights, form characters and function key mapping. Because of the interactive nature of this library, it will be of little use for writing Web applications, but may be useful when writing scripts meant using PHP from the command line.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
Ncurses is available for the following platforms:
AIX
BeOS
Cygwin
Digital Unix (aka OSF1)
FreeBSD
GNU/Linux
HPUX
IRIX
OS/2
SCO OpenServer
Solaris
SunOS
You need the ncurses libraries and headerfiles. Download the latest version from the ftp://ftp.gnu.org/pub/gnu/ncurses/ or from an other GNU-Mirror.
To get these functions to work, you have to compile the CGI or CLI version of PHP with --with-ncurses[=DIR].
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Ncurses configuration options
Name | Default | Changeable |
---|---|---|
ncurses.value | "42" | PHP_INI_ALL |
ncurses.string | "foobar" | PHP_INI_ALL |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 2. ncurses color constants
constant | meaning |
---|---|
NCURSES_COLOR_BLACK | no color (black) |
NCURSES_COLOR_WHITE | white |
NCURSES_COLOR_RED | red - supported when terminal is in color mode |
NCURSES_COLOR_GREEN | green - supported when terminal is in color mode |
NCURSES_COLOR_YELLOW | yellow - supported when terminal is in color mode |
NCURSES_COLOR_BLUE | blue - supported when terminal is in color mode |
NCURSES_COLOR_CYAN | cyan - supported when terminal is in color mode |
NCURSES_COLOR_MAGENTA | magenta - supported when terminal is in color mode |
Tabella 3. ncurses key constants
constant | meaning |
---|---|
NCURSES_KEY_F0 - NCURSES_KEY_F64 | function keys F1 - F64 |
NCURSES_KEY_DOWN | down arrow |
NCURSES_KEY_UP | up arrow |
NCURSES_KEY_LEFT | left arrow |
NCURSES_KEY_RIGHT | right arrow |
NCURSES_KEY_HOME | home key (upward+left arrow) |
NCURSES_KEY_BACKSPACE | backspace |
NCURSES_KEY_DL | delete line |
NCURSES_KEY_IL | insert line |
NCURSES_KEY_DC | delete character |
NCURSES_KEY_IC | insert char or enter insert mode |
NCURSES_KEY_EIC | exit insert char mode |
NCURSES_KEY_CLEAR | clear screen |
NCURSES_KEY_EOS | clear to end of screen |
NCURSES_KEY_EOL | clear to end of line |
NCURSES_KEY_SF | scroll one line forward |
NCURSES_KEY_SR | scroll one line backward |
NCURSES_KEY_NPAGE | next page |
NCURSES_KEY_PPAGE | previous page |
NCURSES_KEY_STAB | set tab |
NCURSES_KEY_CTAB | clear tab |
NCURSES_KEY_CATAB | clear all tabs |
NCURSES_KEY_SRESET | soft (partial) reset |
NCURSES_KEY_RESET | reset or hard reset |
NCURSES_KEY_PRINT | |
NCURSES_KEY_LL | lower left |
NCURSES_KEY_A1 | upper left of keypad |
NCURSES_KEY_A3 | upper right of keypad |
NCURSES_KEY_B2 | center of keypad |
NCURSES_KEY_C1 | lower left of keypad |
NCURSES_KEY_C3 | lower right of keypad |
NCURSES_KEY_BTAB | back tab |
NCURSES_KEY_BEG | beginning |
NCURSES_KEY_CANCEL | cancel |
NCURSES_KEY_CLOSE | close |
NCURSES_KEY_COMMAND | cmd (command) |
NCURSES_KEY_COPY | copy |
NCURSES_KEY_CREATE | create |
NCURSES_KEY_END | end |
NCURSES_KEY_EXIT | exit |
NCURSES_KEY_FIND | find |
NCURSES_KEY_HELP | help |
NCURSES_KEY_MARK | mark |
NCURSES_KEY_MESSAGE | message |
NCURSES_KEY_MOVE | move |
NCURSES_KEY_NEXT | next |
NCURSES_KEY_OPEN | open |
NCURSES_KEY_OPTIONS | options |
NCURSES_KEY_PREVIOUS | previous |
NCURSES_KEY_REDO | redo |
NCURSES_KEY_REFERENCE | ref (reference) |
NCURSES_KEY_REFRESH | refresh |
NCURSES_KEY_REPLACE | replace |
NCURSES_KEY_RESTART | restart |
NCURSES_KEY_RESUME | resume |
NCURSES_KEY_SAVE | save |
NCURSES_KEY_SBEG | shiftet beg (beginning) |
NCURSES_KEY_SCANCEL | shifted cancel |
NCURSES_KEY_SCOMMAND | shifted command |
NCURSES_KEY_SCOPY | shifted copy |
NCURSES_KEY_SCREATE | shifted create |
NCURSES_KEY_SDC | shifted delete char |
NCURSES_KEY_SDL | shifted delete line |
NCURSES_KEY_SELECT | select |
NCURSES_KEY_SEND | shifted end |
NCURSES_KEY_SEOL | shifted end of line |
NCURSES_KEY_SEXIT | shifted exit |
NCURSES_KEY_SFIND | shifted find |
NCURSES_KEY_SHELP | shifted help |
NCURSES_KEY_SHOME | shifted home |
NCURSES_KEY_SIC | shifted input |
NCURSES_KEY_SLEFT | shifted left arrow |
NCURSES_KEY_SMESSAGE | shifted message |
NCURSES_KEY_SMOVE | shifted move |
NCURSES_KEY_SNEXT | shifted next |
NCURSES_KEY_SOPTIONS | shifted options |
NCURSES_KEY_SPREVIOUS | shifted previous |
NCURSES_KEY_SPRINT | shifted print |
NCURSES_KEY_SREDO | shifted redo |
NCURSES_KEY_SREPLACE | shifted replace |
NCURSES_KEY_SRIGHT | shifted right arrow |
NCURSES_KEY_SRSUME | shifted resume |
NCURSES_KEY_SSAVE | shifted save |
NCURSES_KEY_SSUSPEND | shifted suspend |
NCURSES_KEY_UNDO | undo |
NCURSES_KEY_MOUSE | mouse event has occurred |
NCURSES_KEY_MAX | maximum key value |
Tabella 4. mouse constants
Constant | meaning |
---|---|
NCURSES_BUTTON1_RELEASED - NCURSES_BUTTON4_RELEASED | button (1-4) released |
NCURSES_BUTTON1_PRESSED - NCURSES_BUTTON4_PRESSED | button (1-4) pressed |
NCURSES_BUTTON1_CLICKED - NCURSES_BUTTON4_CLICKED | button (1-4) clicked |
NCURSES_BUTTON1_DOUBLE_CLICKED - NCURSES_BUTTON4_DOUBLE_CLICKED | button (1-4) double clicked |
NCURSES_BUTTON1_TRIPLE_CLICKED - NCURSES_BUTTON4_TRIPLE_CLICKED | button (1-4) triple clicked |
NCURSES_BUTTON_CTRL | ctrl pressed during click |
NCURSES_BUTTON_SHIFT | shift pressed during click |
NCURSES_BUTTON_ALT | alt pressed during click |
NCURSES_ALL_MOUSE_EVENTS | report all mouse events |
NCURSES_REPORT_MOUSE_POSITION | report mouse position |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_addchnstr -- Add attributed string with specified length at current positionAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_beep() sends an audible alert (bell) and if its not possible flashes the screen. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also ncurses_flash()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_border -- Draw a border around the screen using attributed charactersAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_border() draws the specified lines and corners around the main window. Each parameter expects 0 to draw a line and 1 to skip it. The corners are top left, top right, bottom left and bottom right.
Use ncurses_wborder() for borders around subwindows!
See also ncurses_wborder().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The function ncurses_can_change_color() returns TRUE or FALSE, depending on whether the terminal has color capabilities and whether the programmer can change the colors.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_cbreak() disables line buffering and character processing (interrupt and flow control characters are unaffected), making characters typed by the user immediately available to the program.
ncurses_cbreak() returns TRUE or NCURSES_ERR if any error occurred.
See also: ncurses_nocbreak()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_clear() clears the screen completely without setting blanks. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Note: ncurses_clear() clears the screen without setting blanks, which have the current background rendition. To clear screen with blanks, use ncurses_erase().
See also ncurses_erase().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_clrtobot() erases all lines from cursor to end of screen and creates blanks. Blanks created by ncurses_clrtobot() have the current background rendition. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also ncurses_clear(), and ncurses_clrtoeol()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_clrtoeol() erases the current line from cursor position to the end. Blanks created by ncurses_clrtoeol() have the current background rendition. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also ncurses_clear(), and ncurses_clrtobot()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_def_prog_mode() saves the current terminal modes for program (in curses) for use by ncurses_reset_prog_mode(). Returns FALSE on success, otherwise TRUE.
See also: ncurses_reset_prog_mode()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_def_shell_mode() saves the current terminal modes for shell (not in curses) for use by ncurses_reset_shell_mode(). Returns FALSE on success, otherwise TRUE.
See also: ncurses_reset_shell_mode()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
ncurses_del_panel -- Remove panel from the stack and delete it (but not the associated window)
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_delch -- Delete character at current position, move rest of line leftAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_delch() deletes the character under the cursor. All characters to the right of the cursor on the same line are moved to the left one position and the last character on the line is filled with a blank. The cursor position does not change. Returns FALSE on success, otherwise TRUE.
See also: ncurses_deleteln()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_deleteln() deletes the current line under cursorposition. All lines below the current line are moved up one line. The bottom line of window is cleared. Cursor position does not change. Returns FALSE on success, otherwise TRUE.
See also: ncurses_delch()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_doupdate()() compares the virtual screen to the physical screen and updates the physical screen. This way is more effective than using multiple refresh calls. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_echo() enables echo mode. All characters typed by user are echoed by ncurses_getch(). Returns FALSE on success, TRUE if any error occurred.
To disable echo mode use ncurses_noecho().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_erase() fills the terminal screen with blanks. Created blanks have the current background rendition, set by ncurses_bkgd(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also ncurses_bkgd(), and ncurses_clear()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_erasechar() returns the current erase char character.
See also: ncurses_killchar()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_flash() flashes the screen, and if its not possible, sends an audible alert (bell). Returns FALSE on success, otherwise TRUE.
See also: ncurses_beep()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The ncurses_flushinp() throws away any typeahead that has been typed and has not yet been read by your program. Returns FALSE on success, otherwise TRUE.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_getmaxyx() puts the horizontal and vertical size of the window window into the given variables &y and &x. Variables must be passed as reference, so they are updated when the user changes terminal size.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_getmouse() reads mouse event out of queue. Function ncurses_getmouse() will return ;FALSE if a mouse event is actually visible in the given window, otherwise it will return TRUE. Event options will be delivered in parameter mevent, which has to be an array, passed by reference (see example below). On success an associative array with following keys will be delivered:
"id" : Id to distinguish multiple devices
"x" : screen relative x-position in character cells
"y" : screen relative y-position in character cells
"z" : currently not supported
"mmask" : Mouse action
See also ncurses_ungetmouse()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_has_colors() returns TRUE or FALSE depending on whether the terminal has color capacities.
See also: ncurses_can_change_color()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_has_ic() checks terminals insert- and delete capabilities. It returns TRUE when terminal has insert/delete-capabilities, otherwise FALSE.
See also: ncurses_has_il()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_has_il() checks terminals insert- and delete-line-capabilities. It returns TRUE when terminal has insert/delete-line capabilities, otherwise FALSE
See also: ncurses_has_ic()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_hline -- Draw a horizontal line at current position using an attributed character and max. n characters longAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_inch() returns the character from the current position.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_init() initializes the ncurses interface and must be used before any other ncurses function.
(PHP 4 >= 4.1.0, PHP 5)
ncurses_insch -- Insert character moving rest of line including character at current positionAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_insdelln -- Insert lines before current line scrolling down (negative numbers delete and scroll up)Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_insertln() inserts a new line above the current line. The bottom line will be lost.
(PHP 4 >= 4.2.0, PHP 5)
ncurses_insstr -- Insert string at current position, moving rest of line rightAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_instr() returns the number of characters read from the current character position until end of line. buffer contains the characters. Attributes are stripped from the characters.
(PHP 4 >= 4.1.0, PHP 5)
ncurses_isendwin -- Ncurses is in endwin mode, normal screen output may be performedAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_isendwin() returns TRUE, if ncurses_endwin() has been called without any subsequent calls to ncurses_wrefresh(), otherwise FALSE.
See also ncurses_endwin() and ncurses_wrefresh().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_killchar() returns the current line kill character.
See also: ncurses_erasechar()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_longname() returns a verbose description of the terminal. The description is truncated to 128 characters. On Error ncurses_longname() returns NULL.
See also: ncurses_termname()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Function ncurses_mousemask() will set mouse events to be reported. By default no mouse events will be reported. The function ncurses_mousemask() will return a mask to indicated which of the in parameter newmask specified mouse events can be reported. On complete failure, it returns 0. In parameter oldmask, which is passed by reference ncurses_mousemask() returns the previous value of mouse event mask. Mouse events are represented by NCURSES_KEY_MOUSE in the ncurses_wgetch() input stream. To read the event data and pop the event of of queue, call ncurses_getmouse().
As a side effect, setting a zero mousemask in newmask turns off the mouse pointer. Setting a non zero value turns mouse pointer on.
mouse mask options can be set with the following predefined constants:
NCURSES_BUTTON1_PRESSED
NCURSES_BUTTON1_RELEASED
NCURSES_BUTTON1_CLICKED
NCURSES_BUTTON1_DOUBLE_CLICKED
NCURSES_BUTTON1_TRIPLE_CLICKED
NCURSES_BUTTON2_PRESSED
NCURSES_BUTTON2_RELEASED
NCURSES_BUTTON2_CLICKED
NCURSES_BUTTON2_DOUBLE_CLICKED
NCURSES_BUTTON2_TRIPLE_CLICKED
NCURSES_BUTTON3_PRESSED
NCURSES_BUTTON3_RELEASED
NCURSES_BUTTON3_CLICKED
NCURSES_BUTTON3_DOUBLE_CLICKED
NCURSES_BUTTON3_TRIPLE_CLICKED
NCURSES_BUTTON4_PRESSED
NCURSES_BUTTON4_RELEASED
NCURSES_BUTTON4_CLICKED
NCURSES_BUTTON4_DOUBLE_CLICKED
NCURSES_BUTTON4_TRIPLE_CLICKED
NCURSES_BUTTON_SHIFT>
NCURSES_BUTTON_CTRL
NCURSES_BUTTON_ALT
NCURSES_ALL_MOUSE_EVENTS
NCURSES_REPORT_MOUSE_POSITION
See also ncurses_getmouse(), ncurses_ungetmouse() and ncurese_getch().
(PHP 4 >= 4.3.0, PHP 5)
ncurses_move_panel -- Moves a panel so that its upper-left corner is at [startx, starty]
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_mvaddchnstr -- Move position and add attributed string with specified lengthAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_mvdelch -- Move position and delete character, shift rest of line leftAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_mvhline -- Set new position and draw a horizontal line using an attributed character and max. n characters longAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
ncurses_mvvline -- Set new position and draw a vertical line using an attributed character and max. n characters longAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_newwin() creates a new window to draw elements in. Windows can be positioned using x, y, rows and cols. When creating additional windows, remember to use ncurses_getmaxyx() to check for available space, as terminal size is individual and may vary. The return value is a resource ID used to differ between multiple windows.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_nocbreak() routine returns terminal to normal (cooked) mode. Initially the terminal may or may not in cbreak mode as the mode is inherited. Therefore a program should call ncurses_cbreak() and ncurses_nocbreak() explicitly. Returns TRUE if any error occurred, otherwise FALSE.
See also: ncurses_cbreak()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_noecho() prevents echoing of user typed characters. Returns TRUE if any error occurred, otherwise FALSE.
See also: ncurses_echo(), ncurses_getch()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_noraw() switches the terminal out of raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal. Returns TRUE if any error occurred, otherwise FALSE.
See also: ncurses_raw(), ncurses_cbreak(), ncurses_nocbreak()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(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
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(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
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_raw() places the terminal in raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal. Returns TRUE if any error occurred, otherwise FALSE.
See also: ncurses_noraw(), ncurses_cbreak(), ncurses_nocbreak()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Function ncurses_resetty() restores the terminal state, which was previously saved by calling ncurses_savetty(). This function always returns FALSE.
See also: ncurses_savetty()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Function ncurses_savetty() saves the current terminal state. The saved terminal state can be restored with function ncurses_resetty(). ncurses_savetty() always returns FALSE.
See also: ncurses_resetty()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_scrl -- Scroll window content up or down without changing current positionAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
ncurses_show_panel -- Places an invisible panel on top of the stack, making it visible
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_slk_attr() returns the current soft label key attribute. On error returns TRUE, otherwise FALSE.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The function ncurses_slk_clear() clears soft label keys from screen. Returns TRUE on error, otherwise FALSE.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Function ncurses_slk_init() must be called before ncurses_initscr() or ncurses_newterm() is called. If ncurses_initscr() eventually uses a line from stdscr to emulate the soft labels, then format determines how the labels are arranged of the screen. Setting format to 0 indicates a 3-2-3 arrangement of the labels, 1 indicates a 4-4 arrangement and 2 indicates the PC like 4-4-4 mode, but in addition an index line will be created.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_slk_refresh() copies soft label keys from virtual screen to physical screen. Returns TRUE on error, otherwise FALSE.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The function ncurses_slk_restore() restores the soft label keys after ncurses_slk_clear() has been performed.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The ncurses_slk_touch() function forces all the soft labels to be output the next time a ncurses_slk_noutrefresh() is performed.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_termattrs -- Returns a logical OR of all attribute flags supported by terminalAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_termname() returns terminals shortname. The shortname is truncated to 14 characters. On error ncurses_termname() returns NULL.
See also: ncurses_longname()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_getmouse() pushes a KEY_MOUSE event onto the unput queue and associates with this event the given state sata and screen-relative character cell coordinates, specified in mevent. Event options will be specified in associative array mevent:
"id" : Id to distinguish multiple devices
"x" : screen relative x-position in character cells
"y" : screen relative y-position in character cells
"z" : currently not supported
"mmask" : Mouse action
ncurses_ungetmouse() returns FALSE on success, otherwise TRUE.
See also: ncurses_getmouse()
(PHP 4 >= 4.3.0, PHP 5)
ncurses_update_panels -- Refreshes the virtual screen to reflect the relations between panels in the stack.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_use_env -- Control use of environment information about terminal sizeAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_use_extended_names -- Control use of extended names in terminfo descriptionsAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_vline -- Draw a vertical line at current position using an attributed character and max. n characters longAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
ncurses_waddch -- Adds character at current position in a window and advance cursor
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
ncurses_wborder -- Draws a border around the window using attributed charactersAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_wborder() draws the specified lines and corners around the passed window window. Each parameter expects 0 to draw a line and 1 to skip it. The corners are top left, top right, bottom left and bottom right.
Use ncurses_border() for borders around the main window.
See also ncurses_border().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
ncurses_whline -- Draws a horizontal line in a window at current position using an attributed character and max. n characters long
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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.
(PHP 4 >= 4.0.5)
notes_body -- Open the message msg_number in the specified mailbox on the specified server (leave servAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.0.5)
notes_find_note -- Returns a note id found in database_name. Specify the name of the note. Leaving type blaAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.0.5)
notes_header_info -- Open the message msg_number in the specified mailbox on the specified server (leave servAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
These functions are only available when running PHP as a NSAPI module in Netscape/iPlanet/SunONE webservers.
For PHP installation on Netscape/iPlanet/SunONE webservers see the NSAPI section in the installation chapter.
The behaviour of the NSAPI PHP module is affected by settings in php.ini. Configuration settings from php.ini may be overridden by additional parameters to the php4_execute call in obj.conf
NSAPI implements a subset of the functions from the Apache module for maximum compatibility.
Tabella 2. Apache functions implemented by NSAPI
Apache function (only as alias) | NSAPI function | Description |
---|---|---|
apache_request_headers() | nsapi_request_headers() | Fetch all HTTP request headers |
apache_response_headers() | nsapi_response_headers() | Fetch all HTTP response headers |
getallheaders() | nsapi_request_headers() | Fetch all HTTP request headers |
virtual() | nsapi_virtual() | Make NSAPI sub-request |
nsapi_request_headers() returns an associative array of all the HTTP headers in the current request. This is only supported when PHP runs as a NSAPI module.
Nota: Prior to PHP 4.3.3, getallheaders() was only available for the Apache servers. After PHP 4.3.3, getallheaders() is an alias for nsapi_request_headers() if you use the NSAPI module.
Nota: You can also get at the value of the common CGI variables by reading them from the $_SERVER superglobal, which works whether or not you are using PHP as a NSAPI module.
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() 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.
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.
Per potere accedere ai database supportati occorre avere installato le librerie necessarie.
Include il supporto per Adabas D. DIR indica la directory di installazione di Adabas, il default è /usr/local.
Include il supporto per SAP DB. DIR indica la directory di installazione di SAP DB, il default è /usr/local.
Include il supporto per Solid. DIR indica la directory di installazione di Solid, il default è /usr/local/solid.
Include il supporto per IBM DB2. DIR indica la directory di installazione di DB2, il default è /home/db2inst1/sqllib.
Include il supporto per Empress. DIR indica la directory di installazione di Empress, il default è $EMPRESSPATH. A partire da PHP 4, questa opzione supporta solo Empress Versione 8.60 e successive.
Include il supporto per Empress Local Access. DIR indica la directory di installazione di Empress, il default è $EMPRESSPATH. A partire da PHP 4, questa opzione supporta solo Empress Versione 8.60 e successive.
Include il supporto per Birdstep. DIR indica la directory di installazione di Birdstep, il default è /usr/local/birdstep.
Include il supporto definito dall'utente per ODBC. DIR indica la directory di installazione di ODBC, il default è /usr/local. Accertarsi di definire CUSTOM_ODBC_LIBS e di avere odbc.h nelle directory di include. Ad esempio, si devorebbe definire i seguenti parametri per Sybase SQL Anywhere 5.5.00 su QNX, prima di eseguire lo script di configurazione: CPPFLAGS="-DODBC_QNX -DSQLANY_BUG" LDFLAGS=-lunix CUSTOM_ODBC_LIBS="-ldblib -lodbc".
Include il supporto per iODBC. DIR indica la directory di installazione di iODBC, il default è /usr/local.
Include il supporto per Easysoft OOB. DIR indica la directory di installazione di OOB, il default è /usr/local/easysoft/oob/client.
Include il supporto per unixODBC. DIR indica la directory di installazione di unixODBC, il default è /usr/local.
Include il supporto per OpenLink ODBC. DIR indica la directory di installazione di OpenLink, il default è /usr/local. This is the same as iODBC.
Include il supporto per DBMaker. DIR indica la directory di installazione di DBMaker, per default si ha la directory in cui è installata l'ultima versione di DBMaker (tipo /home/dbmaker/3.6).
Per disabilitare il supporto alle funzioni ODBC unificate in PHP 3 aggiungere il parametro --disable-unified-odbc nella linea di configurazione. Ciò è applicabile soltanto se è abilitata una delle seguenti interfaccie: iODBC, Adabas, Solid, Velocis oppure una versione personalizzata di ODBC.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Parametrizzazione per il modulo Funzioni ODBC Unificate
Nome | Default | Modificabile |
---|---|---|
odbc.default_db * | NULL | PHP_INI_ALL |
odbc.default_user * | NULL | PHP_INI_ALL |
odbc.default_pw * | NULL | PHP_INI_ALL |
odbc.allow_persistent | "1" | PHP_INI_SYSTEM |
odbc.check_persistent | "1" | PHP_INI_SYSTEM |
odbc.max_persistent | "-1" | PHP_INI_SYSTEM |
odbc.max_links | "-1" | PHP_INI_SYSTEM |
odbc.defaultlrl | "4096" | PHP_INI_ALL |
odbc.defaultbinmode | "1" | PHP_INI_ALL |
Nota: I parametri segnati con * non sono ancora implementati.
Breve descrizione dei parametri di configurazione.
Sorgenti di dati ODBC da utilizzare se non viene fornita in odbc_connect() o odbc_pconnect().
Nome utente da usare se non viene passato nelle funzioni odbc_connect() o odbc_pconnect().
Password da usare se non viene passato nelle funzioni odbc_connect() o odbc_pconnect().
Indica se permettere le connessioni ODBC persistenti.
Verifica se una connessione è ancora valida prima di ri-utilizzarla.
Imposta il numero massimo di connessioni persistenti permesse per processo.
Imposta il numero massimo di connessioni permesse per processo, comprese le connessioni persistenti.
Gestisce i campi di tipo LONG. Specifica il numero di byte da ritornare alla variabile.
Gestione dei dati binari.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Se non viene fornito il parametro OnOff, la funzione restituisce lo stato dell'auto-commit per id_connessione. Il valore reso è vero se l'autocommit è attivo, altrimenti falso se non è attivato oppure si verifica un errore.
Se il campo OnOff è posto a vero, l' auto-commit è abilitato, se è valorizzato a falso l'auto-commit è disabilitato. La funzione restituisce TRUE se l'operazione riesce, FALSE se si verifica un errore.
Per default, l'auto-commit è abilitato. La disabilitazione dell'auto-commit equivale ad iniziare una transazione.
Vedere inoltre odbc_commit() e odbc_rollback().
(Tipi di campi ODBC SQL coinvolti: BINARY, VARBINARY, LONGVARBINARY)
ODBC_BINMODE_PASSTHRU: Restituzione del dato binario direttamente al client
ODBC_BINMODE_RETURN: restituisce il dato inalterato
ODBC_BINMODE_CONVERT: Conversione in char
Quando si esegue la conversione da dati binari SQL a dati di tipo char del C, ciascun byte ( 8 bits) dei dati sorgenti vengono rappresentati da 2 caratteri ASCII. Questi caratteri sono la rappresentazione ASCII dei numeri nella loro forma esadecimale. Ad esempio, il valore binario 00000001 è convertito in "01" e il valore binario 11111111 è convertito come "FF".
Tabella 1. Gestione del tipo LONGVARBINARY
Modalità | Impostazione di longreadlen | Comportamento |
---|---|---|
ODBC_BINMODE_PASSTHRU | 0 | direttamente al client |
ODBC_BINMODE_RETURN | 0 | direttamente al client |
ODBC_BINMODE_CONVERT | 0 | direttamente al client |
ODBC_BINMODE_PASSTHRU | 0 | passthru |
ODBC_BINMODE_PASSTHRU | >0 | direttamente al client |
ODBC_BINMODE_RETURN | >0 | restituito inalterato |
ODBC_BINMODE_CONVERT | >0 | restituito come char |
Se viene utilizzata odbc_fetch_into(), nei casi in cui il dato viene inviato direttamente al client, quest'ultima restituisce una stringa vuota per le colonne binarie.
Se l'argomento id_risultato è valorizzato a 0, il settaggio viene applicato come default per i nuovi risultati.
Nota: I valori di default per longreadlen è 4096, mentre la modalità di default è ODBC_BINMODE_RETURN. La gestione delle colonne di campi long binary, è anche gestita dalla funzione odbc_longreadlen()
La funzione odbc_close_all() chiude tutte le connessioni aperte con il database server
Nota: Se ci sono delle transazioni aperte sulla connessione richiesta, la funzione fallisce. In questo caso la connessione resta aperta.
odbc_close() chiude la connessione con il database server associata all'identificativo di connessione indicato.
Nota: Se ci sono delle transazioni aperte sulla connessione richiesta, la funzione fallisce. In questo caso la connessione resta aperta.
(PHP 4 , PHP 5)
odbc_columnprivileges -- Restituisce un identificatore di risultato che permette di ricavare l'elenco delle colonne e dei privilegi ad esse associati.Elenca le colonne e i privilegi associati ad esse per la tabella data. La funzione ritorna un identificatore di risultato ODBC oppure FALSE se si verifica un errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
GRANTOR
GRANTEE
PRIVILEGE
IS_GRANTABLE
I campi di ordinamento delle righe risultanti sono TABLE_QUALIFIER, TABLE_OWNER e TABLE_NAME.
L'argomento nome_colonna accetta dei criteri di ricerca ('%' per indicare zero o più caratteri e '_' per indicare un singolo carattere).
(PHP 4 , PHP 5)
odbc_columns -- Elenca i nomi delle colonne nella tabella specificata. La funzione ritorna un identificatore di risultato contenenti le informazioni.Elenca i nomi di tutte le colonne presenti nel range richiesto. La funzione restituisce un identificatore di risultato ODBC oppure FALSE se si verifica un errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
TABLE_QUALIFIER
TABLE_SCHKM
TABLE_NAME
COLUMN_NAME
DATA_TYPE
TYPE_NAME
PRECISION
LENGTH
SCALE
RADIX
NULLABLE
REMARKS
I campi di ordinamento delle righe risultanti sono TABLE_QUALIFIER, TABLE_SCHKM e TABLE_NAME.
Gli argomenti schema, nome_tabella e nome_colonna accettano dei criteri di ricerca ('%' per indicare zero o più caratteri e '_' per indicare un singolo carattere).
Vedere anche odbc_columnprivileges() per ottenere i privilegi associati alle colonne.
La funzione odbc_commit() esegue tutte le transazioni pendenti sulla connessione indicata dall'argomento id_connessione. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Restituisce un identificatore di connessione ODBC oppure 0 (falso) se si verifica un errore.
L'identificatore di connessione ritornato da questa funzione è utilizzato dalle altre funzioni ODBC. Si possono avere più connessioni aperte contemporaneamente se queste utlizzano differenti database o differenti credenziali utente. Il quarto parametro (opzionale), setta il tipo di cursore da utilizzare per questa connessione. Normalmente questo parametro non è necessario, ma può essere utilizzato per aggirare dei problemi che si manifestano con alcuni driver ODBC.
Con alcuni driver ODBC, l'esecuzione di complesse procedure può generare un errore tipo: "Non si riesce ad aprire un cursore sulla procedura che richieda qualsiasi cosa oltre ad un singola istruzione select". L'uso di SQL_CUR_USE_ODBC, può evitare questo errore. Inoltre alcuni driver non supportano il parametro row_number della funzione odbc_fetch_row(). In questo caso SQL_CUR_USE_ODBC può essere d'aiuto.
Il campo tipo_cursore può assumere le seguenti costanti:
SQL_CUR_USE_IF_NEEDED
SQL_CUR_USE_ODBC
SQL_CUR_USE_DRIVER
SQL_CUR_DEFAULT
Per le connessioni persistenti vedere odbc_pconnect().
odbc_cursor restituisce il nome del cursore per l'argomento id_risultato.
La funzione restituisce FALSE se si verifica un errore, oppure un array se ha successo.
Questa funzione restituisce 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() esegue una query sulla connessione data.
La funzione restituisce un codice di 6 cifre indicante lo stato di ODBC. Se non vi sono errori viene restituita una stringa vuota. Se viene passato il parametro id_connessione, viene restituito l'ultimo stato di questa connessione, altrimenti si ha l'ultimo stato dell'ultima operazione su una qualsiasi connessione.
Vedere anche: odbc_errormsg() e odbc_exec().
la funzione restituisce una stringa contenente l'ultimo messaggio di errore generato da ODBC, oppure una stringa vuota se non ci sono errori. Se viene passato il parametro id_connessione, viene restituito l'ultimo stato di questa connessione, altrimenti si ha l'ultimo stato dell'ultima operazione su una qualsiasi connessione.
Vedere anche: odbc_error() and odbc_exec().
Restituisce FALSE se si verifica un errore. Restituisce un identificatore del risultato ODBC se l'espressione SQL viene eseguita correttamente.
odbc_exec() invia una espressione SQL al server tramite la connessione specificata da id_connessione. Questo parametro deve essere un identificativo valido restituito da odbc_connect() oppure odbc_pconnect().
Vedere anche: odbc_prepare() e odbc_execute() per l'esecuzione di molteplici espressioni SQL.
Esegue una espressione SQL memorizzata tramite la funzione odbc_prepare(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento. L'array array_parametri occorre soltanto se è necessario fornire parametri all'espressione.
I parametri in array_parametri saranno sostituiti dai segnaposto nell'ordine dell'espressione predisposta.
Qualsiasi parametro in array_parametri che inizia e finisce con gli apici singoli sarà considerato come il nome di un file da leggere e inviare al database server come dati per gli appropriati segnaposto.
Nota: Dalla versione 4.1.1 la funzionalità di lettura del file ha le seguenti restrizioni:
La lettura del file non è soggetta alle restrizioni di 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().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
odbc_fetch_into -- Scarica una riga del risultato della query in un arrayLa funzione restituisce il numero di colonne presenti nel risultato; FALSE se si verifica un errore. Il parametro array_dati deve essere passato per referenza, ma può essere di qualsiasi tipo dato che verrà convertito in array. Nell'array saranno posti i valori delle colonne di una riga tratta dalla tabella risultante dalla query a partire dall'indice 0.
A partire dalla versione 4.0.5 di PHP non occorre passare il parametro array_dati per riferimento.
A partire dall versione 4.0.6 di PHP il parametro numero_riga non può essere passato come costante, ma come variabile.
A partire dalla versione 4.2.0 di PHP i parametri array_dati e numero_riga sono stati invertiti. Questo permette al parametro numero_riga di essere ancora una costante. Questa è l'ultima variazione alla funzione.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Se odbc_fetch_row() ha successo (c'è almeno una riga), la funzione restituisce TRUE. Altrimenti, se non vi sono più righe, la funzione restituisce FALSE.
odbc_fetch_row() estrae un record dai dati restituiti dalle funzioni odbc_do() / odbc_exec(). Dopo l'esecuzione di odbc_fetch_row(), i campi della riga sono accessibili tramite la funzione odbc_result().
Se non viene specificato il parametro numero_riga, odbc_fetch_row() restituisce la riga successiva dal set delle righe risultanti dalla query. Si può intercalare esecuzioni successive di odbc_fetch_row() con e senza il parametro numero_riga.
Per spostarsi attraverso le righe risultanti, si può eseguire odbc_fetch_row() con il parametro numero_riga impostato a 1, e quindi continuare ad utilizzare odbc_fetch_row() senza numero_riga. Se il driver non supporta l'estrazione di una riga per numero, il campo numero_riga sarà ignorato.
All'interno di un set di righe, referenziate dall'identificativo di risultato ODBC fornito, la funzione odbc_field_len() restituisce la dimensione (precisione) del campo indicato dall'argomento. La numerazione dei campi parte da 1.
Vedere anche: odbc_field_scale() per ottenere la scala di un numero in virgola mobile.
La funzione odbc_field_name() restituisce il nome del campo presente nella colonna richiesta all'interno di un risultato ODBC identificato dal'argomento id_risultato. La numerazione delle colonne parte da 1. La funzione restituisce falso se si verifica un errore.
odbc_field_num() restituisce il numero della colonna in cui si trova il campo richiesto all'interno di un risultato ODBC indicato dall'argomento id_risultato. La numerazione delle colonne parte da 1. Si ottiene FALSE se si verifica un errore.
All'interno di un set di righe, referenziate dall'identificativo di risultato ODBC fornito, la funzione odbc_field_precision() restituisce la precisione del campo indicato dal numero di campo indicato.
Vedere anche: odbc_field_scale() per ottenere la scala di un numero in virgola mobile.
All'interno di un set di righe, referenziate dall'identificativo di risultato ODBC fornito, la funzione odbc_field_precision() restituisce la scala del campo indicato dal numero di campo indicato.
La funzione odbc_field_type() restituisce il tipo di dato SQL del campo indicato dal numero all'interno di un set di righe referenziate dall'identificativo di risultato ODBC passato. La numerazione delle colonne parte da 1.
(PHP 4 , PHP 5)
odbc_foreignkeys -- Restituisce l'elenco delle chiavi esterne per la tabella indicata, oppure la lista delle chiavi esterne in altre tabelle che fanno riferimento alla chiave primaria della tabella indicata.La funzione odbc_foreignkeys() ritorna informazioni sulle chiavi esterne. Restituisce un identificatore di risultato oppure FALSE se si verifica un errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
PKTABLE_QUALIFIER
PKTABLE_OWNER
PKTABLE_NAME
PKCOLUMN_NAME
FKTABLE_QUALIFIER
FKTABLE_OWNER
FKTABLE_NAME
FKCOLUMN_NAME
KEY_SEQ
UPDATE_RULE
DELETE_RULE
FK_NAME
PK_NAME
Se l'argomento pk_tabella contiene il nome di una tabella, la funzione odbc_foreignkeys() ritorna una serie di righe contenenti i dati della chiave primaria della tabella e di tutte le chiavi esterne che hanno riferimenti a questa.
Se l'argomento fk_tabella contiene il nome di una tabella, la funzione odbc_foreignkeys() ritorna una serie di righe contenenti i dati delle chiavi esterne della tabella e delle chiavi primarie ( di altre tabelle ) a cui queste hanno riferimenti.
Se entrambi gli argomenti pk_tabella e fk_tabella contengono nomi di tabelle, odbc_foreignkeys() restituisce le chiavi esterne della tabella specificata in fk_tabella che hanno riferimenti alla chiave primaria della tabella indicata in pk_tabella. La funzione dovrebbe trovare almeno una chiave.
Restituisce sempre TRUE.
La funzione odbc_free_result() permette di non utilizzare molta memoria durante l'esecuzione di uno script. Infatti, se si è sicuri di non avere più bisogno dei dati del risultato, si può eseguire odbc_free_result(), e la memoria associata a id_risultato sarà liberata. Se la funzione non viene utilizzata, le aree di memoria resteranno disponibili per tutta la durata dello script. Al termine verranno liberate in modo automatico.
Nota: Se si ha l'auto-commit disabilitato (vedere odbc_autocommit()) e si esegue odbc_free_result() prima di eseguire il commit, tutte le transazioni pendenti saranno annullate,
(PHP 4 , PHP 5)
odbc_gettypeinfo -- Restituisce un identificatore di risultato contenente informazioni sui tipi di dati supportati dalla sorgente di dati.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.
(tipi di campi ODBC ed SQL coinvolti: LONG, LONGVARBINARY) Tramite l'argomento lunghezza si controlla il numero di byte da ritornare a PHP. Se il campo viene posto a 0, i dati della colonna saranno passati direttamente al client.
Nota: Per la gestione delle colonne di tipo LONGVARBINARY si utilizza anche odbc_binmode().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
All'interno di un set di righe, referenziate dall'identificativo di risultato ODBC fornito, la funzione odbc_num_fields() restituisce il numero di campi (colonne) presenti. La funzione restituisce -1 se si verifica un errore. L'argomento fornito è un identificatore di esito restituito dalla funzione odbc_exec().
odbc_num_rows() ritorna il numero di record presenti in un risultato ODBC. La funzione ritorna -1 se si verifica un errore. Per le clausole INSERT, UPDATE e DELETE, odbc_num_rows() ritorna il numero di righe coinvolte. Nella clausola SELECT questo può essere il numero di righe disponibili.
Nota: Con diversi driver, la funzione odbc_num_rows(), utilizzata con lo scopo di determinare il numero di righe dopo una SELECT, restituisce -1.
Restituisce un identificatore di connessione ODBC oppure 0 (FALSE) su errore. Questa funzione è molto simile a odbc_connect(), eccetto che la connessione non viene realmente chiusa quando lo script finisce. Successive richieste di connessione che utilizzino la stessa combinazione di dsn, utente, password (eseguite sia utilizzando odbc_connect(), sia utilizzando odbc_pconnect()) possono riutilizzare la connessione.
Nota: Le connessioni persistenti non hanno effetti se PHP viene utilizzato come programma CGI.
Per informazioni sul campo opzionale tipo_cursore, vedere la funzione odbc_connect(). Per maggiori dettagli sulle connessioni persistenti, fare riferimento alla FAQ di PHP.
La funzione restituisce FALSE su errore.
Restituisce un identificativo di risultato ODBC se l'espressione SQL viene predisposta correttamente. L'identificativo restituito può essere utilizzato successivamente per eseguire l'espressione utilizzando la funzione odbc_execute().
(PHP 4 , PHP 5)
odbc_primarykeys -- Restituisce un identificatore di risultato che può essere utilizzato per ricavare il nome della colonna che contiene la chiave primaria della tabella.Restituisce il nome della colonna che contiene la chiave primaria per la tabella. La funzione ritorna un identificatore di risultato ODBC oppure FALSE se si verifica un errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
COLUMN_NAME
KEY_SEQ
PK_NAME
La funzione ritorna la lista dei parametri di input e di output e anche delle colonne che concorrono al determinazione del risultato per le procedure indicate. Viene restituito un identificatore di risultato oppure FALSE se si è un errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
PROCEDURE_QUALIFIER
PROCEDURE_OWNER
PROCEDURE_NAME
COLUMN_NAME
COLUMN_TYPE
DATA_TYPE
TYPE_NAME
PRECISION
LENGTH
SCALE
RADIX
NULLABLE
REMARKS
I campi di ordinamento delle righe risultanti sono PROCEDURE_QUALIFIER, PROCEDURE_OWNER, PROCEDURE_NAME e COLUMN_TYPE.
Gli argomenti proprietario, procedura e colonna accettano dei criteri di ricerca ('%' per indicare zero o più caratteri e '_' per indicare un singolo carattere).
(PHP 4 , PHP 5)
odbc_procedures -- Restituisce l'elenco delle procedure memorizzate in una specifica sorgente di dati. La funzione ritorna un identificatore di risultato che punta alle informazioni reperite.Si ottiene l'elenco di tutte le procedure presenti nei limiti richiesti. La funzione restituisce un identificatore di risultato, oppure FALSE su errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
PROCEDURE_QUALIFIER
PROCEDURE_OWNER
PROCEDURE_NAME
NUM_INPUT_PARAMS
NUM_OUTPUT_PARAMS
NUM_RESULT_SETS
REMARKS
PROCEDURE_TYPE
Gli argomenti proprietario e nome accettano dei criteri di ricerca ('%' per indicare zero o più caratteri e '_' per indicare un singolo carattere).
Restituisce il numero di righe elaborate, oppure FALSE se si verifica un errore.
Dato un identificatore di risultato restituito da odbc_exec(), la funzione odbc_result_all() visualizza tutti i record ottenuti in una di tabella in formato HTML. Utilizzando il parametro opzionale formato, è possibile fornire informazioni addizionali sulla formattazione della tabella.
Restituisce il contenuto dei campi.
Il parametro campo può essere sia un intero indicante il numero di colonna del campo desiderato; sia una stringa contenente il nome del campo. Ad esempio:
Nel primo caso l'esecuzione di odbc_result() restituisce il valore del terzo campo del record corrente della query. Nel secondo, la funzione odbc_result() restituisce il valore del campo il cui nome è "val", sempre utilizzando i dati dal record corrente. Si ha un errore qualora il numero di colonna fornito sia minore di 1 oppure sia superiore al numero delle colonne (o campi) presenti nel record corrente. Analogamente, si ottiene un errore se il nome del campo richiesto non sia presente nella tabella/e oggetto della ricerca.
L'indice dei campi parte da 1. Per quanto riguarda la gestione dei campi di tipo binario o long fare riferimento a odbc_binmode() e a odbc_longreadlen().
Annulla tutte le operazioni pendenti sulla connessione indicata da id_connessione. Se ha successo restituisce TRUE, altrimenti FALSE.
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
odbc_setoption -- Settaggio dei parametri ODBC. Restituisce FALSE se si verifica un errore, altrimenti TRUE.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 4 , PHP 5)
odbc_specialcolumns -- Restituisce sia il set di colonne che identificano in modo univoco una riga nella tabella, sia colonne che sono automaticamente aggiornate quando un qualsiasi campo della riga viene aggiornato da una transazione.Quando l'argomento tipo è impostato a SQL_BEST_ROWID, odbc_specialcolumns() restituisce la colonna o le colonne che identificano in modo univoco ciascuna riga nella tabella.
Quando l'argomento tipo è impostato a SQL_ROWVER, odbc_specialcolumns() restituisce la colonna o 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.
Si ottengono informazioni statistiche sulla tabella e i propri indici. La funzione restituisce un identificatore di risultato ODBC, oppure FALSE su errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
NON_UNIQUE
INDEX_QUALIFIER
INDEX_NAME
TYPE
SEQ_IN_INDEX
COLUMN_NAME
COLLATION
CARDINALITY
PAGES
FILTER_CONDITION
I campi di ordinamento delle righe risultanti sono NON_UNIQUE, TYPE, INDEX_QUALIFIER, INDEX_NAME e SEQ_IN_INDEX.
Elenca le tabelle presenti nei limiti richiesti e, per ciascuna di queste, ne fornisce i privilegi. La funzione ritorna un identificatore di risultato ODBC, oppure FALSE su errore.
Le righe risultanti dall'elaborazione hanno i seguenti campi:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
GRANTOR
GRANTEE
PRIVILEGE
IS_GRANTABLE
I campi di ordinamento delle righe risultanti sono TABLE_QUALIFIER, TABLE_OWNER e TABLE_NAME.
Gli argomenti proprietario e nome accettano dei criteri di ricerca ('%' per indicare zero o più caratteri e '_' per indicare un singolo carattere).
(PHP 3>= 3.0.17, PHP 4 , PHP 5)
odbc_tables -- Restituisce l'elenco delle tabelle presenti in una specifica sorgente di dati. Restituisce l'identificatore di risultato in cui vi sono le informazioni.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.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
In Object Oriented Programming, it is common to see the composition of simple classes (and/or instances) into a more complex one. This is a flexible strategy for building complicated objects and object hierarchies and can function as a dynamic alternative to multiple inheritance. There are two ways to perform class (and/or object) composition depending on the relationship between the composed elements: Association and Aggregation.
An Association is a composition of independently constructed and externally visible parts. When we associate classes or objects, each one keeps a reference to the ones it is associated with. When we associate classes statically, one class will contain a reference to an instance of the other class. For example:
Esempio 1. Class association
|
Esempio 2. Object association
|
Aggregation, on the other hand, implies encapsulation (hidding) of the parts of the composition. We can aggregate classes by using a (static) inner class (PHP does not yet support inner classes), in this case the aggregated class definition is not accessible, except through the class that contains it. The aggregation of instances (object aggregation) involves the dynamic creation of subobjects inside an object, in the process, expanding the properties and methods of that object.
Object aggregation is a natural way of representing a whole-part relationship, (for example, molecules are aggregates of atoms), or can be used to obtain an effect equivalent to multiple inheritance, without having to permanently bind a subclass to two or more parent classes and their interfaces. In fact object aggregation can be more flexible, in which we can select what methods or properties to "inherit" in the aggregated object.
We define 3 classes, each implementing a different storage method:
Esempio 3. storage_classes.inc
|
We then instantiate a couple of objects from the defined classes, and perform some aggregations and deaggregations, printing some object information along the way:
Esempio 4. test_aggregation.php
|
We will now consider the output to understand some of the side-effects and limitation of object aggregation in PHP. First, the newly created $fs and $ws objects give the expected output (according to their respective class declaration). Note that for the purposes of object aggregation, private elements of a class/object begin with an underscore character ("_"), even though there is not real distinction between public and private class/object elements in PHP.
$fs object Class: filestorage property: data (array) 0 => 3.1415926535898 1 => kludge != cruft method: filestorage method: write $ws object Class: wddxstorage property: data (array) 0 => 3.1415926535898 1 => kludge != cruft property: version = 1.0 property: _id = ID::9bb2b640764d4370eb04808af8b076a5 method: wddxstorage method: store method: _genid |
We then aggregate $fs with the WDDXStorage class, and print out the object information. We can see now that even though nominally the $fs object is still of FileStorage, it now has the property $version, and the method store(), both defined in WDDXStorage. One important thing to note is that it has not aggregated the private elements defined in the class, which are present in the $ws object. Also absent is the constructor from WDDXStorage, which will not be logical to aggegate.
Let's aggregate $fs to the WDDXStorage class $fs object Class: filestorage property: data (array) 0 => 3.1415926535898 1 => kludge != cruft property: version = 1.0 method: filestorage method: write method: store |
The 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.
(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.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()
Will produce the output
|
_secret_super_dicing
See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()
(PHP 4 >= 4.2.0)
aggregate_methods_by_list -- Selective dynamic class methods aggregation to an objectAggregates methods from a class to an existing object using a list of method names. The optional paramater exclude is used to decide whether the list contains the names of methods to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).
The class constructor or methods whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.
See also aggregate(), aggregate_info(), aggregate_methods(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()
(PHP 4 >= 4.2.0)
aggregate_methods_by_regexp -- Selective class methods aggregation to an object using a regular expressionAggregates methods from a class to an existing object using a regular expresion to match method names. The optional paramater exclude is used to decide whether the regular expression will select the names of methods to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).
The class constructor or methods whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.
See also aggregate(), aggregate_info(), aggregate_methods(), aggregate_methods_by_list(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()
Aggregates all methods defined in a class to an existing object, except for the class constructor, or methods whose names start with an underscore character (_) which are considered private to the aggregated class.
See also aggregate(), aggregate_info(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()
(PHP 4 >= 4.2.0)
aggregate_properties_by_list -- Selective dynamic class properties aggregation to an objectAggregates properties from a class to an existing object using a list of property names. The optional paramater exclude is used to decide whether the list contains the names of class properties to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).
The properties whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.
See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_regexp(), aggregate_info(), deaggregate()
(PHP 4 >= 4.2.0)
aggregate_properties_by_regexp -- Selective class properties aggregation to an object using a regular expressionAggregates properties from a class to an existing object using a regular expresion to match their names. The optional paramater exclude is used to decide whether the regular expression will select the names of class properties to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).
The properties whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.
See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_info(), deaggregate()
Aggregates all properties defined in a class to an existing object, except for properties whose names start with an underscore character (_) which are considered private to the aggregated class.
See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), aggregate_info(), deaggregate()
Aggregates methods and properties defined in a class to an existing object. Methods and properties with names starting with an underscore character (_) are considered private to the aggregated class and are not used, constructors are also excluded from the aggregation procedure.
See also aggregate_info(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()
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()
Queste funzioni permettono di accedere ai database Oracle9, Oracle8 e Oracle7. Usano la Oracle Call Interface (OCI).
Questa estensione è più flessibile della estensione precedente di Oracle. Supporta il binding di variabili PHP locali e globali ai segnaposto Oracle, ha pieno supporto di LOB, FILE e ROWID e permette di utilizzare variabili di definizione personalizzabili. Si raccomanda di utilizzare questa estensione al posto della vecchia estensione quando possibile;
Occorre avere installate le librerie client di Oracle per utilizzare questa estensione. Gli utenti Windows necessitano almeno della versione 8.1 di Oracle per utilizzare la dll php_oci8.dll.
Prima di usare questa estensione, occorre sincerarsi di aver impostato le variabili d'ambiente per l'utente Oracle, come pure per l'utente del server web. Le variabili che potrebbero necessitare l'impostazione sono le seguenti:
ORACLE_HOME
ORACLE_SID
LD_PRELOAD
LD_LIBRARY_PATH
NLS_LANG
ORA_NLS33
Dopo aver impostato le variabili d'ambiente per l'utente del server web, occorre sicerarsi di aver aggiunto anche l'utente stesso (nobody, www) al gruppo oracle.
Se il server web non parte o va in blocco: Controllare che apache sia linkato con la libreria pthread:
# ldd /www/apache/bin/httpd libpthread.so.0 => /lib/libpthread.so.0 (0x4001c000) libm.so.6 => /lib/libm.so.6 (0x4002f000) libcrypt.so.1 => /lib/libcrypt.so.1 (0x4004c000) libdl.so.2 => /lib/libdl.so.2 (0x4007a000) libc.so.6 => /lib/libc.so.6 (0x4007e000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)Se la libpthread non compare nell'elenco, occorre reinstallare Apache:
Si noti che su alcuni sistemi, come ad esempio UnixWare, la libreria si chiama libthread invece di libpthread. PHP e Apache devono essere configurati con EXTRA_LIBS=-lthread.
Si deve compilare PHP con l'opzione --with-oci8[=DIR], dove DIR è di default il contenuto della variabile di ambiente ORACLE_HOME.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Modalità di esecuzione dello statement. Non viene eseguito il commit automatico utilizzando questa modalità.
Modalità di esecuzione dello statement. Utilizzare questa modalità se non si vuole eseguire la query, ma solamente ricevere la descrizione della select list.
Modalità di esecuzione dello statement. Vene eseguito automaticamente il commit dello statement dopo la chiamata della oci_execute().
Modalità di recupero dati dello statement. Utilizzato quando l'applicazione conosce in anticipo quante righe verranno recuperate. Questa modalità disattiva il prefetching negli Oracle release 8 o successivi. Il cursore viene eliminato dopo che le sono state caricate e ciò può determinare un utilizzo ridotto delle risorse del server.
Utilizzato con oci_bind_by_name() quando si collegano i BFILE.
Utilizzato con oci_bind_by_name() quando si collegano i CFILE.
Utilizzato con oci_bind_by_name() quando si collegano i CLOB.
Utilizzato con oci_bind_by_name() quando si collegano i BLOB.
Utilizzato con oci_bind_by_name() quando si collegano i ROWID.
Utilizzato con oci_bind_by_name() quando si collegano i cursori, precedentemente allocati con oci_new_descriptor().
Utilizzato con oci_bind_by_name() quando si collegano i named data type.
Alias di OCI_B_BFILE.
Alias di OCI_B_CFILEE.
Alias di OCI_B_CLOB.
Alias di OCI_B_BLOB.
Alias di OCI_B_ROWID.
Alias di OCI_B_NTY.
Modalità di default di oci_fetch_all().
Modalità alternativa di oci_fetch_all().
Utilizzato con oci_fetch_all() e oci_fetch_array() per ottenere un array associative come risultato.
Utilizzato con oci_fetch_all() e oci_fetch_array() per ottenere un array enumerativo come risultato.
Utilizzato con oci_fetch_all() e oci_fetch_array() per ottenere un array con indici sia associativi che numerici.
Utilizzato con oci_fetch_array() per ottenere elementi dell'array vuoti se il valore del campo è NULL.
Utilizzato con oci_fetch_array() per ottenere il valore del LOB invece del suo descrittore.
Questo flag ordina a oci_new_descriptor() di inizializzare un nuovo descrittore di FILE.
Questo flag ordina a oci_new_descriptor() di inizializzare un nuovo descrittore di LOB.
Questo flag ordina a oci_new_descriptor() di inizializzare un nuovo descrittore di ROWID.
Alias di OCI_DTYPE_FILE.
Alias di OCI_DTYPE_LOB.
Alias di OCI_DTYPE_ROWID.
Esempio 1. Trucchi OCI
|
You can easily access stored procedures in the same way as you would from the commands line.
Esempio 2. Using Stored Procedures
|
oci_bind_by_name() collega la variabile PHP variable al segnaposto Oracle ph_name. L'utilizzo in modalità input o output sarà determinato a run-time, e lo spazio di memoria necessario sarà allocato. Il parametro lungmax imposta la lunghezza massima del collegamento. Se si imposta lungmax a -1 oci_bind_by_name() userà l'attuale lunghezza di variabile per impostare la lunghezza massima.
Se si deve collegare un tipo dato astratto (LOB/ROWID/BFILE) occorre innanzitutto allocarlo usando la funzione oci_new_descriptor(). Il parametro lungmax non è usato con i tipi dati astratti e dovrebbe essere impostato a -1. La variabile tipo informa oracle sul tipo di descrittore che si vuole usare. I valori possibili sono:
OCI_B_FILE - per i BFILE;
OCI_B_CFILE - per i CFILE;
OCI_B_CLOB - per i CLOB;
OCI_B_BLOB - per i BLOB;
OCI_B_ROWID - per i ROWID;
OCI_B_NTY - per i named datatype;
OCI_B_CURSOR - per i cursori precedentemente creati con oci_new_cursor().
Esempio 1. esempio di ocibindbyname()
|
Ricordarsi che questa funzione elimina gli spazi alla fine della riga. Vedere il seguente esempio:
Esempio 2. esempio di oci_bind_by_name()
|
Esempio 3. esempio di oci_bind_by_name()
|
Avvertimento |
Non utilizzare le magic_quotes_gpc o addslashes() e oci_bind_by_name() simultaneamente in quanto le virgolette non sono necessarie nelle variabili e qualsiasi virgoletta aggiunta automaticamente verrà scritta nel database dal momento che ocibindbyname() non è in grado di distinguere le virgolette aggiunte automaticamente da quelle intenzionali. |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Nelle versioni di PHP antecedenti la 5.0.0 si deve usare ocibindbyname(). Questo nome può ancora essere utilizzato, è rimasto come alias di oci_bind_by_name() per mantenere la compatibilità. Ciò è comunque deprecato e non raccomandato.
oci_cancel() invalida un cursore, rilasciando tutte le risorse associate e cancella la possibilità di leggere da esso.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nelle versioni di PHP antecedenti la 5.0.0 si deve usare ocicancel(). Questo nome può ancora essere utilizzato, è rimasto come alias di oci_cancel() per mantenere la compatibilità. Ciò è comunque deprecato e non raccomandato.
oci_close() closes the Oracle connection connection.
Nota: 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.
(no version information, might be only in CVS)
collection->append -- Appends an object to the collectionAppends 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.
(no version information, might be only in CVS)
collection->assign -- Assigns a value to the collection from another existing collectionAssigns a value to the collection from another, previously created collection. Both collections must be created with oci_new_collection() prior to using them.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
collection->assignElem -- Assigns a value to the element of the collectionAssigns a value to the element with index index. Parameter value can be a string or a number.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
(no version information, might be only in CVS)
collection->max -- Gets the maximum number of elements in the collectionReturns the maximum number of elements in the collection. If the returned value is 0, then the number of elements is not limited. collection->max() returns FALSE in case of error.
See also oci_collection_size().
Returns the number of elements in the collection.
See also oci_collection_max().
(no version information, might be only in CVS)
collection->trim -- Trims elements from the end of the collectionTrims num of elements from the end of the collection.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also oci_collection_size().
oci_commit() commits all outstanding statements for the active transaction on the Oracle connection connection.
Esempio 1. oci_commit() example
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: In PHP versions before 5.0.0 you must use ocicommit() instead. This name still can be used, it was left as alias of oci_commit() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_rollback() and oci_execute().
oci_connect() returns a connection identifier needed for most other OCI calls. The optional third parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora to which you want to connect. If the optional third parameter is not specified, PHP uses the environment variables ORACLE_SID (Oracle instance) or TWO_TASK (tnsnames.ora) to determine which database to connect to.
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
|
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() 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
|
Nota: In PHP versions before 5.0.0 you must use ocidefinebyname() instead. This name still can be used, it was left as alias of oci_define_by_name() for downwards compatability. This, however, is deprecated and not recommended.
For most errors, the parameter is the most appropriate resource handle. For connection errors with oci_connect(), oci_new_connect() or oci_pconnect(), do not pass a parameter. If no error is found, oci_error() returns FALSE. oci_error() returns the error as an associative array. In this array, code consists the oracle error code and message the oracle error string.
As of PHP 4.3: offset and sqltext will also be included in the return array to indicate the location of the error and the original SQL text which caused it.
Esempio 3. Displaying the Oracle error message and problematic statement after an execution error
|
Nota: In PHP versions before 5.0.0 you must use ocierror() instead. This name still can be used, it was left as alias of oci_error() for downwards compatability. This, however, is deprecated and not recommended.
oci_execute() executes a previously parsed statement (see oci_parse()). The optional mode allows you to specify the execution mode (default is OCI_COMMIT_ON_SUCCESS). If you don't want statements to be committed automatically, you should specify OCI_DEFAULT as your mode.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: In PHP versions before 5.0.0 you must use ociexecute() instead. This name still can be used, it was left as alias of oci_execute() for downwards compatability. This, however, is deprecated and not recommended.
oci_fetch_all() fetches all the rows from a result into a user-defined array. oci_fetch_all() returns the number of rows fetched or FALSE in case of 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
|
oci_fetch_all() returns FALSE in case of error.
Nota: In PHP versions before 5.0.0 you must use ocifetchstatement() instead. This name still can be used, it was left as alias of oci_fetch_all() for downwards compatability. This, however, is deprecated and not recommended.
(PHP 5)
oci_fetch_array -- Returns the next row from the result data as an associative or numeric array, or bothReturns an array, which corresponds to the next result row or FALSE in case of error or there 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. |
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
|
Esempio 2. oci_fetch_array() with OCI_NUM example
|
Esempio 3. oci_fetch_array() with OCI_ASSOC example
|
Esempio 4. oci_fetch_array() with OCI_RETURN_LOBS example
|
See also oci_fetch_assoc(), oci_fetch_object(), oci_fetch_row() and oci_fetch_all().
oci_fetch_assoc() returns the next row from the result data as an associative array (identical to oci_fetch_array() call with OCI_ASSOC flag).
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() 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().
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() 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() returns TRUE if field field from the statement is NULL. Parameter field could be a field's index or a field's name (uppercased).
Nota: In PHP versions before 5.0.0 you must use ocicolumnisnull() instead. This name still can be used, it was left as alias of oci_field_is_null() for downwards compatability. This, however, is deprecated and not recommended.
oci_field_name() returns the name of the field corresponding to the field number (1-based).
Esempio 1. oci_field_name() example
|
Nota: In PHP versions before 5.0.0 you must use ocicolumnname() instead. This name still can be used, it was left as alias of oci_field_name() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_num_fields(), oci_field_type(), and oci_field_size().
Returns precision of the field with field index (1-based).
For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).
Nota: In PHP versions before 5.0.0 you must use ocicolumnprecision() instead. This name still can be used, it was left as alias of oci_field_precision() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_field_scale() and oci_field_type().
Returns scale of the column with field index (1-based) or FALSE if there is no such field.
For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).
Nota: In PHP versions before 5.0.0 you must use ocicolumnscale() instead. This name still can be used, it was left as alias of oci_field_scale() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_field_precision() and oci_field_type().
oci_field_size() returns the size of a field in bytes. Value of field parameter can be the field's index (1-based) or it's name.
Esempio 1. oci_field_size()example
|
Nota: In PHP versions before 5.0.0 you must use ocicolumnsize() instead. This name still can be used, it was left as alias of oci_field_size() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_num_fields() and oci_field_name().
oci_field_type_raw() returns Oracle's raw data type of the field.
Nota: In PHP versions before 5.0.0 you must use ocicolumntyperaw() instead. This name still can be used, it was left as alias of oci_field_type_raw() for downwards compatability. This, however, is deprecated and not recommended.
However, if you want to get field's type, then oci_field_type() will suit you better. See oci_field_type() for additional information.
oci_field_type() returns a field's data type. Parameter field is an index of the field in the statement (1-based).
Esempio 1. oci_field_type() example
|
Nota: In PHP versions before 5.0.0 you must use ocicolumntype() instead. This name still can be used, it was left as alias of oci_field_type() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_num_fields(), oci_field_name(), and oci_field_size().
(no version information, might be only in CVS)
collection->free -- Frees resources associated with collection objectFrees resources associated with collection object.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
descriptor->free -- Frees resources associated with descriptordescriptor->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() frees resources associated with Oracle's cursor or statement, which was received from as a result of oci_parse() or obtained from Oracle.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
oci_internal_debug() enables or disables internal debug output. Set onoff to 0 to turn debug output off or 1 to turn it on.
Nota: In PHP versions before 5.0.0 you must use ociinternaldebug() instead. This name still can be used, it was left as alias of oci_internal_debug() for downwards compatability. This, however, is deprecated and not recommended.
(no version information, might be only in CVS)
lob->append -- Appends data from the large object to another large objectAppends data from the large object to the end of another large object.
Writing to the large object with 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() 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().
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.
(no version information, might be only in CVS)
lob->eof -- Tests for end-of-file on a large object's descriptorReturns TRUE if internal pointer of large object is at the end of LOB. Otherwise returns FALSE.
See also oci_lob_size().
(no version information, might be only in CVS)
lob->erase -- Erases a specified portion of the internal LOB dataErases a specified portion of the internal LOB data starting at a specified offset. Parameters length and offset are optional. 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.
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.
(no version information, might be only in CVS)
lob->flush -- Flushes/writes buffer of the LOB to the serverlob->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.
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.
Compares two LOB/FILE locators. Returns TRUE if these objects are equal and FALSE otherwise.
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.
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().
(no version information, might be only in CVS)
lob->rewind -- Moves the internal pointer to the beginning of the large objectSets the internal pointer to the beginning of the large object.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also oci_lob_seek() and oci_lob_tell().
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().
(no version information, might be only in CVS)
lob->seek -- Sets the internal pointer of the large objectSets the internal pointer of the large object. Parameter offset indicates the amount of bytes, on which internal pointer should be moved from the position, pointed by whence:
OCI_SEEK_SET - sets the position equal to offset |
OCI_SEEK_CUR - adds offset bytes to the current position |
OCI_SEEK_END - adds offset bytes to the end of large object (use negative value to move to a position before the end of large object) |
See also oci_lob_rewind() and oci_lob_tell().
Returns length of large object value or FALSE in case of error. Empty objects have zero length.
(no version information, might be only in CVS)
lob->tell -- Returns current position of internal pointer of large objectReturns current position of a LOB's internal pointer or FALSE if an error occured.
See also oci_lob_size() and oci_lob_eof().
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().
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().
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().
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() 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
|
oci_new_connect() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocinlogon() instead. This name still can be used, it was left as alias of oci_new_connect() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_connect() and oci_pconnect().
oci_new_cursor() allocates a new statement handle on the specified connection.
Esempio 1. Using REF CURSOR in an Oracle's stored procedure
|
Esempio 2. Using REF CURSOR in an Oracle's select statement
|
oci_new_cursor() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocinewcursor() instead. This name still can be used, it was left as alias of oci_new_cursor() for downwards compatability. This, however, is deprecated and not recommended.
oci_new_descriptor() allocates resources to hold descriptor or LOB locator. Valid values for type are: OCI_D_FILE, OCI_D_LOB and OCI_D_ROWID.
Esempio 1. oci_new_descriptor() example
|
Esempio 2. oci_new_descriptor() example
|
oci_new_descriptor() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocinewdescriptor() instead. This name still can be used, it was left as alias of oci_new_descriptor() for downwards compatability. This, however, is deprecated and not recommended.
oci_num_fields() returns the number of columns in the statement.
Esempio 1. oci_num_fields() example
|
oci_num_fields() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocinumcols() instead. This name still can be used, it was left as alias of oci_num_fields() for downwards compatability. This, however, is deprecated and not recommended.
oci_num_rows() returns number of rows affected during statement execution.
Nota: This function does not return number of rows selected! For SELECT statements this function will return the number of rows, that were fetched to the buffer with oci_fetch*() functions.
Esempio 1. oci_num_rows() example
|
oci_num_rows() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocirowcount() instead. This name still can be used, it was left as alias of oci_num_rows() for downwards compatability. This, however, is deprecated and not recommended.
oci_parse() prepares the query using connection and returns the statement identifier, which can be used with oci_bind_by_name(), oci_execute() and other functions.
Nota: This function does not validate query. The only way to find out if query is valid SQL or PL/SQL statement - is to execute it.
oci_parse() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ociparse() instead. This name still can be used, it was left as alias of oci_parse() for downwards compatability. This, however, is deprecated and not recommended.
Changes password for user with username. Parameters old_password and new_password should indicate old and new passwords respectively.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: In PHP versions before 5.0.0 you must use ocipasswordchange() instead. This name still can be used, it was left as alias of oci_password_change() for downwards compatability. This, however, is deprecated and not recommended.
oci_pconnect() creates a 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() 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() 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().
Returns a string with version information of the Oracle server, which uses connection connection or returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ociserverversion() instead. This name still can be used, it was left as alias of oci_server_version() for downwards compatability. This, however, is deprecated and not recommended.
Sets the number of rows to be prefetched after successful call to oci_execute(). The default value for rows is 1.
Nota: In PHP versions before 5.0.0 you must use ocisetprefetch() instead. This name still can be used, it was left as alias of oci_set_prefetch() for downwards compatability. This, however, is deprecated and not recommended.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
oci_statement_type() returns the query type of statement statement as one of the following values:
SELECT
UPDATE
DELETE
INSERT
CREATE
DROP
ALTER
BEGIN
DECLARE
UNKNOWN
Parameter statement is a valid OCI statement identifier, returned from oci_parse().
oci_statement_type() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocistatementtype() instead. This name still can be used, it was left as alias of oci_statement_type() for downwards compatability. This, however, is deprecated and not recommended.
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
|
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. |
Se non si vogliono leggere altri dati da un cursore, chiamare ocicancel().
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.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.0.6, PHP 5)
ocicollassignelem -- Assegna un elemento alla collezione in una specifica posizione
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ocicolumnisnull() restituisce TRUE se il campo col nel risultato dell'istruzione stmt è NULL. Si può usare il numero del campo (primo campo=1) o il nome del campo per il parametro col.
ocicolumnname() restituisce il nome del campo corrispondente alla posizione (1 = primo campo) specificata.
Esempio 1. esempio di ocicolumnname()
|
Vedere anche ocinumcols(), ocicolumntype(), e ocicolumnsize().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ocicolumnsize() restituisce la dimensione del campo come riportata da Oracle. Si può usare il numero del campo (primo campo=1) o il nome del campo per il parametro col.
Esempio 1. esempio di ocicolumnsize()
|
Vedere anche ocinumcols(), ocicolumnname() e ocicolumnsize().
ocicolumntype() restituisce il tipo del campo corrispondente alla posizione (1 = primo campo) specificata.
Esempio 1. OCIColumnType
|
Vedere anche ocinumcols(), ocicolumnname(), e ocicolumnsize().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ocicommit() esegue tutte le transazioni in sospeso sulla connessione Oracle connection. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Questo esempio dimostra l'utilizzo di OCICommit.
Esempio 1. OCICommit
|
Vedere anche ocirollback().
(PHP 3>= 3.0.7, PHP 4 , PHP 5)
OCIDefineByName -- Utilizza una variabile PHP per la fase di definizione in un comando SELECTocidefinebyname() aggancia le variabili PHP ai campi SQL. Attenzione: Oracle usa nomi di colonna MAIUSCOLI, mentre nella SELECT si possono anche scrivere minuscoli. ocidefinebyname() vuole il parametro Column-Name in caratteri maiuscoli. Se si definisce una variabile che non esiste nel comando SELECT, non viene dato alcun errore!
Se occorre definire un tipo di dati astratto (LOB/ROWID/BFILE) lo si deve prima allocare usando la funzione OCINewDescriptor(). Vedere anche la funzione OCIBindByName().
Esempio 1. OCIDefineByName
|
ocierror() restituisce l'ultimo errore. Se il parametro opzionale stmt|conn|global non è specificato, viene restituito l'ultimo errore generato. Se non ci sono errori, ocierror() restituisce FALSE. ocierror() restituisce l'errore in un array associativo. In questo array, code dà il codice d'errora oracle e message dà la stringa d'errore.
ociexecute() esegue un comando precedentemente analizzato. (vedere ociparse()). Il parametro opzionale mode permette di specificare la modalità di esecuzione (il default è OCI_COMMIT_ON_SUCCESS). Se non si desidera che i comandi eseguano un commit automatico, usare OCI_DEFAULT nella variabile mode.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 3>= 3.0.4, PHP 4 , PHP 5)
ocifetch -- Estrae la prossima tupla opnendola nel buffer di risultato.ocifetch() estrae la prossima tupla (nelle istruzioni SELECT) ponendola nel buffer interno di risultato.
ocifetchinto() estrae la prossima tupla (nelle istruzioni SELECT) ponendola nell'array result. ocifetchinto() sovrascriverà il precedente contenuto di result. Di default result conterrà un array (primo indice = 1) di tutti i campi che non sono NULL.
Il parametro mode permette di cambiare il comportamento predefinito. E' possibile specificare più di un'opzione sommandole (es. OCI_ASSOC+OCI_RETURN_NULLS). Le opzioni valide sono:
OCI_ASSOC Restituisce un array associativo. |
OCI_NUM Restituisce un array indicizzato (primo indice = 0). (DEFAULT) |
OCI_RETURN_NULLS Restituisce anche i campi NULL. |
OCI_RETURN_LOBS Restituisce il valore di un LOB invece del descrittore. |
Vedere anche ocifetch() e ociexecute().
ocifetchstatement() estrae tutte le tuple da un risultato ponendole in un array definito dall'utente. ocifetchstatement() restituisce il numero di tuple estratte.
Esempio 1. Esempio di ocifetchstatement()
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ocifreecursor() libera tutte le risorse associate al cursore stmt. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
ocifreedesc() cancella il descrittore di oggetto binario lob. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 3>= 3.0.5, PHP 4 , PHP 5)
ocifreestatement -- Libera tutte le risorse associate ad un'istruzioneocifreestatement() libera tutte le risorse associate all'istruzione stmt.Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
lob->getBuffering -- Returns current state of buffering for large objectReturns FALSE if buffering for the large object is off and TRUE if buffering is used.
See also ocisetbufferinglob().
(PHP 3>= 3.0.4, PHP 4 , PHP 5)
ociinternaldebug -- Abilita o disabilita la visualizzazione del debug interno.ociinternaldebug() abilita la visualizzazione del debug interno. Impostare onoff a 0 per spegnere il debug, 1 per accenderlo.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ocilogoff() chiude la connessione Oracle.
L'uso di ocilogoff() normalmente non è necessario, dal momento che i collegamenti non persistenti sono automaticamente chiusi alla fine dell'esecuzione dello script. Vedere anche liberare le risorse
ocilogon() restituisce un identificatore di connessione necessario per la maggior parte delle altre chiamate OCI. Il terzo parametro opzionale può contenere il nome della istanza Oracle locale o il nome della voce in tnsnames.ora a cui ci si vuole connettere. Se il terzo parametro opzionale non è specificato, PHP usa la variabile d'ambiente ORACLE_SID (istanza di Oracle) o TWO_TASK (in tnsnames.ora) per determinare a quale database collegarsi.
Le connessioni sono condivise a livello di pagina quando si usa OCILogon(). Questo significa che i commit e i rollback avvengono su tutte le transazioni aperte nella pagina, anche se sono state create connessioni multiple.
Questo esempio dimostra come le connessioni sono condivise.
Esempio 1. esempio di ocilogon()
|
Vedere anche ociplogon() e ocinlogon().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ocinewcursor() alloca un nuovo identificatore di istruzione sulla connessione specificata.
Esempio 1. Using a REF CURSOR from a stored procedure
|
Esempio 2. Using a REF CURSOR in a select statement
|
ocinewdescriptor() alloca memoria per accogliere descrittori o locatori LOB. I valori validi per il parametro type sono OCI_D_FILE, OCI_D_LOB e OCI_D_ROWID. Per i descrittori LOB, i metodi load, save, e savefile sono associati al descrittore, per i BFILE esiste solo il metodo load. Vedere i suggerimenti nel secondo esempio.
Esempio 1. esempio di ocinewdescriptor()
|
Esempio 2. OCINewDescriptor
|
ocinlogon() crea una nuova connessione a un database Oracle 8 e si autentica. Il terzo parametro opzionale può contenere il nome della istanza Oracle locale o il nome della voce in tnsnames.ora a cui ci si vuole connettere. Se il terzo parametro opzionale non è specificato, PHP usa la variabile d'ambiente ORACLE_SID (istanza di Oracle) o TWO_TASK (in tnsnames.ora) per determinare a quale database collegarsi.
ocinlogon() forza una nuova connessione. Si deve usare quando si ha necessità di isolare un insieme di transazioni. Di default, le connessioni sono condivise a livello di pagina se si usa ocilogon() o a livello di processo del web server se si usa ociplogon(). Se ci sono connessioni multiple aperte con ocinlogon(), tutti i commit e rollback avverranno solo sulla connessione specificata.
Questo esempio dimostra come le connessioni sono isolate.
Esempio 1. esempio di ocinlogon()
|
Vedere anche ocilogon() e ociplogon().
(PHP 3>= 3.0.4, PHP 4 , PHP 5)
ocinumcols -- Restituisce il numero di campi che risultano da un comando SQLocinumcols() restituisce il numero di campi contenuti in un'istruzione SQL.
Esempio 1. ocinumcols()
|
ociparse() analizza la query rispetto alla connessione conn. Restituisce un identificatore di istruzione se la query è valida, FALSE altrimenti. La query può essere qualsiasi comando SQL o blocco di codice PL/SQL.
ociplogon() crea una connessione persistente a un database Oracle 8 e si autentica. Il terzo parametro opzionale può contenere il nome della istanza Oracle locale o il nome della voce in tnsnames.ora a cui ci si vuole connettere. Se il terzo parametro opzionale non è specificato, PHP usa la variabile d'ambiente ORACLE_SID (istanza di Oracle) o TWO_TASK (in tnsnames.ora) per determinare a quale database collegarsi.
Vedere anche ocilogon() e ocinlogon().
ociresult() restituisce i dati del campo column nella tupla corrente (vedere ocifetch()).ociresult() restituirà tutto come stringa, eccetto i tipi astratti (ROWIDs, LOBs e FILEs).
ocirollback() annulla tutte le transazioni in sospeso sulla connessione Oracle connection. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche ocicommit()
ocirowcount() restituisce il numero di tuple modificate, ad esempio, da un comando update. Questa funzione non riporta il numero di tuple restituite da una select!
Esempio 1. esempio di ocirowcount()
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 3>= 3.0.4, PHP 4 , PHP 5)
ociserverversion -- Restituisce una stringa contenente informazioni sulla versione del server(no version information, might be only in CVS)
lob->setBuffering -- Changes current state of buffering for large objectlob->setBuffering() sets the buffering for the large object, depending on the value of the on_off parameter. Repeated calls to lob->setBuffering() with the same flag will return TRUE. The values for on_off are: TRUE for on and FALSE for off.
Use of this function may provide 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().
Imposta a rows il numero di tuple da precaricare. Il valore di default è 1.
ocistatementtype() restituisce uno dei seguenti valori:
SELECT
UPDATE
DELETE
INSERT
CREATE
DROP
ALTER
BEGIN
DECLARE
UNKNOWN
Esempio 1. Esempi di ocistatementtype()
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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.
This module uses the functions of OpenSSL for generation and verification of signatures and for sealing (encrypting) and opening (decrypting) data. OpenSSL offers many features that this module currently doesn't support. Some of these may be added in the future.
In order to use the OpenSSL functions you need to install the OpenSSL package. PHP between versions 4.0.5 and 4.3.1 will work with OpenSSL >= 0.9.5. Other versions (PHP <=4.0.4pl1 and >= 4.3.2) require OpenSSL >= 0.9.6.
Avvertimento |
You are strongly encouraged to use the most recent OpenSSL version, otherwise your web server could be vulnerable to attack. |
To use PHP's OpenSSL support you must also compile PHP --with-openssl[=DIR].
Note to Win32 Users: In order to enable this module on a Windows environment, you must copy libeay32.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)
Additionally, if you are planning to use the key generation and certificate signing functions, you will need to install a valid openssl.cnf on your system. As of PHP 4.3.0, we include a sample configuration file in the openssl folder of our win32 binary distribution. If you are using PHP 4.2.0 or later and are missing the file, you can obtain it from the OpenSSL home page or by downloading the PHP 4.3.0 release and using the configuration file from there.
Note to Win32 Users: PHP will search for the openssl.cnf using the following logic:
the OPENSSL_CONF environmental variable, if set, will be used as the path (including filename) of the configuration file.
the SSLEAY_CONF environmental variable, if set, will be used as the path (including filename) of the configuration file.
The file openssl.cnf will be assumed to be found in the default certificate area, as configured at the time that the openssl DLL was compiled. This is usually means that the default filename is c:\usr\local\ssl\openssl.cnf.
In your installation, you need to decide whether to install the configuration file at c:\usr\local\ssl\openssl.cnf or whether to install it someplace else and use environmental variables (possibly on a per-virtual-host basis) to locate the configuration file. Note that it is possible to override the default path from the script using the configargs of the functions that require a configuration file.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Quite a few of the openssl functions require a key or a certificate parameter. PHP 4.0.5 and earlier have to use a key or certificate resource returned by one of the openssl_get_xxx functions. Later versions may use one of the following methods:
Certificates
An X.509 resource returned from openssl_x509_read()
A string having the format file://path/to/cert.pem; the named file must contain a PEM encoded certificate
A string containing the content of a certificate, PEM encoded
Public/Private Keys
A key resource returned from openssl_get_publickey() or openssl_get_privatekey()
For public keys only: an X.509 resource
A string having the format file://path/to/file.pem - the named file must contain a PEM encoded certificate/private key (it may contain both)
A string containing the content of a certificate/key, PEM encoded
For private keys, you may also use the syntax array($key, $passphrase) where $key represents a key specified using the file:// or textual content notation above, and $passphrase represents a string containing the passphrase for that private key
When calling a function that will verify a signature/certificate, the cainfo parameter is an array containing file and directory names that specify the locations of trusted CA files. If a directory is specified, then it must be a correctly formed hashed directory as the openssl command would use.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
The S/MIME functions make use of flags which are specified using a bitfield which can include one or more of the following values:
Tabella 1. PKCS7 CONSTANTS
Constant | Description |
---|---|
PKCS7_TEXT | Adds text/plain content type headers to encrypted/signed message. If decrypting or verifying, it strips those headers from the output - if the decrypted or verified message is not of MIME type text/plain then an error will occur. |
PKCS7_BINARY | Normally the input message is converted to "canonical" format which is effectively using CR and LF as end of line: as required by the S/MIME specification. When this options is present, no translation occurs. This is useful when handling binary data which may not be in MIME format. |
PKCS7_NOINTERN | When verifying a message, certificates (if any) included in the message are normally searched for the signing certificate. With this option only the certificates specified in the extracerts parameter of openssl_pkcs7_verify() are used. The supplied certificates can still be used as untrusted CAs however. |
PKCS7_NOVERIFY | Do not verify the signers certificate of a signed message. |
PKCS7_NOCHAIN | Do not chain verification of signers certificates: that is don't use the certificates in the signed message as untrusted CAs. |
PKCS7_NOCERTS | When signing a message the signer's certificate is normally included - with this option it is excluded. This will reduce the size of the signed message but the verifier must have a copy of the signers certificate available locally (passed using the extracerts to openssl_pkcs7_verify() for example). |
PKCS7_NOATTR | Normally when a message is signed, a set of attributes are included which include the signing time and the supported symmetric algorithms. With this option they are not included. |
PKCS7_DETACHED | When signing a message, use cleartext signing with the MIME type multipart/signed. This is the default if you do not specify any flags to openssl_pkcs7_sign(). If you turn this option off, the message will be signed using opaque signing, which is more resistant to translation by mail relays but cannot be read by mail agents that do not support S/MIME. |
PKCS7_NOSIGS | Don't try and verify the signatures on a message |
Nota: These constants were added in 4.0.6.
openssl_csr_export_to_file() takes the Certificate Signing Request represented by csr and saves it as ascii-armoured text into the file named by outfilename.
The optional parameter notext affects the verbosity of the output; if it is FALSE then additional human-readable information is included in the output. The default value of notext is TRUE.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also openssl_csr_export(), openssl_csr_new() and openssl_csr_sign().
openssl_csr_export() takes the Certificate Signing Request represented by csr and stores it as ascii-armoured text into out, which is passed by reference.
The optional parameter notext affects the verbosity of the output; if it is FALSE then additional human-readable information is included in the output. The default value of notext is TRUE.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also openssl_csr_export_to_file(), openssl_csr_new() and openssl_csr_sign().
openssl_csr_new() generates a new CSR (Certificate Signing Request) based on the information provided by dn, which represents the Distinguished Name to be used in the certificate.
privkey should be set to a private key that was previously generated by openssl_pkey_new() (or otherwise obtained from the other openssl_pkey family of functions). The corresponding public portion of the key will be used to sign the CSR.
extraattribs is used to specify additional configuration options for the CSR. Both dn and extraattribs are associative arrays whose keys are converted to OIDs and applied to the relevant part of the request.
Nota: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.
By default, the information in your system openssl.conf is used to initialize the request; you can specify a configuration file section by setting the config_section_section key of configargs. You can also specify an alternative openssl configuration file by setting the value of the config key to the path of the file you want to use. The following keys, if present in configargs behave as their equivalents in the openssl.conf, as listed in the table below.
Tabella 1. Configuration overrides
configargs key | type | openssl.conf equivalent | description |
---|---|---|---|
digest_alg | string | default_md | Selects which digest method to use |
x509_extensions | string | x509_extensions | Selects which extensions should be used when creating an x509 certificate |
req_extensions | string | req_extensions | Selects which extensions should be used when creating a CSR |
private_key_bits | string | default_bits | Specifies how many bits should be used to generate a private key |
private_key_type | integer | none | Specifies the type of private key to create. This can be one of OPENSSL_KEYTYPE_DSA, OPENSSL_KEYTYPE_DH or OPENSSL_KEYTYPE_RSA. The default value is OPENSSL_KEYTYPE_RSA which is currently the only supported key type. |
encrypt_key | boolean | encrypt_key | Should an exported key (with passphrase) be encrypted? |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. openssl_csr_new() example - creating a self-signed-certificate
|
(PHP 4 >= 4.2.0, PHP 5)
openssl_csr_sign -- Sign a CSR with another certificate (or itself) and generate a certificateopenssl_csr_sign() generates an x509 certificate resource from the csr previously generated by openssl_csr_new(), but it can also be the path to a PEM encoded CSR when specified as file://path/to/csr or an exported string generated by openssl_csr_export(). The generated certificate will be signed by cacert. If cacert is NULL, the generated certificate will be a self-signed certificate. priv_key is the private key that corresponds to cacert. days specifies the length of time for which the generated certificate will be valid, in days. You can finetune the CSR signing by configargs. See openssl_csr_new() for more information about configargs. Since PHP 4.3.3 you can specify the serial number of issued certificate by serial. In earlier versions, it was always 0.
Returns an x509 certificate resource on success, FALSE on failure.
Nota: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.
Esempio 1. openssl_csr_sign() example - signing a CSR (how to implement your own CA)
|
Returns an error message string, or FALSE if there are no more error messages to return.
openssl_error_string() returns the last error from the openSSL library. Error messages are stacked, so this function should be called multiple times to collect all of the information.
openssl_free_key() frees the key associated with the specified key_identifier from memory.
This is an alias for openssl_pkey_get_private().
(PHP 4 >= 4.0.4, PHP 5)
openssl_get_publickey -- Extract public key from certificate and prepare it for useThis is an alias for openssl_pkey_get_public().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. If successful the opened data is returned in open_data.
openssl_open() opens (decrypts) sealed_data using the private key associated with the key identifier priv_key_id and the envelope key env_key, and fills open_data with the decrypted data. The envelope key is generated when the data are sealed and can only be used by one specific private key. See openssl_seal() for more information.
Esempio 1. openssl_open() example
|
See also openssl_seal().
Decrypts the S/MIME encrypted message contained in the file specified by infilename using the certificate and its associated private key specified by recipcert and recipkey.
The decrypted message is output to the file specified by outfilename
Esempio 1. openssl_pkcs7_decrypt() example
|
openssl_pkcs7_encrypt() takes the contents of the file named infile and encrypts them using an RC2 40-bit cipher so that they can only be read by the intended recipients specified by recipcerts, which is either a lone X.509 certificate, or an array of X.509 certificates. headers is an array of headers that will be prepended to the data after it has been encrypted. flags can be used to specify options that affect the encoding process - see PKCS7 constants. headers can be either an associative array keyed by header name, or an indexed array, where each element contains a single header line.
Esempio 1. openssl_pkcs7_encrypt() example
|
openssl_pkcs7_sign() takes the contents of the file named infilename and signs them using the certificate and its matching private key specified by signcert and privkey parameters.
headers is an array of headers that will be prepended to the data after it has been signed (see openssl_pkcs7_encrypt() for more information about the format of this parameter.
flags can be used to alter the output - see PKCS7 constants - if not specified, it defaults to PKCS7_DETACHED.
extracerts specifies the name of a file containing a bunch of extra certificates to include in the signature which can for example be used to help the recipient to verify the certificate that you used.
Esempio 1. openssl_pkcs7_sign() example
|
openssl_pkcs7_verify() reads the S/MIME message contained in the filename specified by filename and examines the digital signature. It returns TRUE if the signature is verified, FALSE if it is not correct (the message has been tampered with, or the signing certificate is invalid), or -1 on error.
flags can be used to affect how the signature is verified - see PKCS7 constants for more information.
If the outfilename is specified, it should be a string holding the name of a file into which the certificates of the persons that signed the messages will be stored in PEM format.
If the cainfo is specified, it should hold information about the trusted CA certificates to use in the verification process - see certificate verification for more information about this parameter.
If the extracerts is specified, it is the filename of a file containing a bunch of certificates to use as untrusted CAs.
(PHP 4 >= 4.2.0, PHP 5)
openssl_pkey_export_to_file -- Gets an exportable representation of a key into a fileopenssl_pkey_export_to_file() saves an ascii-armoured (PEM encoded) rendition of key into the file named by outfilename. The key can be optionally protected by a passphrase. configargs can be used to fine-tune the export process by specifying and/or overriding options for the openssl configuration file. See openssl_csr_new() for more information about configargs. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.
(PHP 4 >= 4.2.0, PHP 5)
openssl_pkey_export -- Gets an exportable representation of a key into a stringopenssl_pkey_export() exports key as a PEM encoded string and stores it into out (which is passed by reference). The key is optionally protected by passphrase. configargs can be used to fine-tune the export process by specifying and/or overriding options for the openssl configuration file. See openssl_csr_new() for more information about configargs. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.
Returns a positive key resource identifier on success, or FALSE on error.
openssl_get_privatekey() parses key and prepares it for use by other functions. key can be one of the following:
a string having the format file://path/to/file.pem. The named file must contain a PEM encoded certificate/private key (it may contain both).
A PEM formatted private key.
The optional parameter passphrase must be used if the specified key is encrypted (protected by a passphrase).
(PHP 4 >= 4.2.0, PHP 5)
openssl_pkey_get_public -- Extract public key from certificate and prepare it for useReturns a positive key resource identifier on success, or FALSE on error.
openssl_get_publickey() extracts the public key from certificate and prepares it for use by other functions. certificate can be one of the following:
an X.509 certificate resource
a string having the format file://path/to/file.pem. The named file must contain a PEM encoded certificate/private key (it may contain both).
A PEM formatted private key.
openssl_pkey_new() generates a new private and public key pair. The public component of the key can be obtained using openssl_pkey_get_public(). You can finetune the key generation (such as specifying the number of bits) using configargs. See openssl_csr_new() for more information about configargs.
Nota: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Returns the length of the sealed data on success, or FALSE on error. If successful the sealed data is returned in sealed_data, and the envelope keys in env_keys.
openssl_seal() seals (encrypts) data by using RC4 with a randomly generated secret key. The key is encrypted with each of the public keys associated with the identifiers in pub_key_ids and each encrypted key is returned in env_keys. This means that one can send sealed data to multiple recipients (provided one has obtained their public keys). Each recipient must receive both the sealed data and the envelope key that was encrypted with the recipient's public key.
Esempio 1. openssl_seal() example
|
See also openssl_open().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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
|
See also openssl_verify().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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
|
See also openssl_sign().
(PHP 4 >= 4.2.0, PHP 5)
openssl_x509_check_private_key -- Checks if a private key corresponds to a certificateopenssl_x509_check_private_key() returns TRUE if key is the private key that corresponds to cert, or FALSE otherwise.
(PHP 4 >= 4.0.6, PHP 5)
openssl_x509_checkpurpose -- Verifies if a certificate can be used for a particular purposeReturns TRUE if the certificate can be used for the intended purpose, FALSE if it cannot, or -1 on error.
openssl_x509_checkpurpose() examines the certificate specified by x509cert to see if it can be used for the purpose specified by purpose.
cainfo should be an array of trusted CA files/dirs as described in Certificate Verification.
untrustedfile, if specified, is the name of a PEM encoded file holding certificates that can be used to help verify the certificate, although no trust in placed in the certificates that come from that file.
Tabella 1. openssl_x509_checkpurpose() purposes
Constant | Description |
---|---|
X509_PURPOSE_SSL_CLIENT | Can the certificate be used for the client side of an SSL connection? |
X509_PURPOSE_SSL_SERVER | Can the certificate be used for the server side of an SSL connection? |
X509_PURPOSE_NS_SSL_SERVER | Can the cert be used for Netscape SSL server? |
X509_PURPOSE_SMIME_SIGN | Can the cert be used to sign S/MIME email? |
X509_PURPOSE_SMIME_ENCRYPT | Can the cert be used to encrypt S/MIME email? |
X509_PURPOSE_CRL_SIGN | Can the cert be used to sign a certificate revocation list (CRL)? |
X509_PURPOSE_ANY | Can the cert be used for Any/All purposes? |
openssl_x509_export_to_file() stores x509 into a file named by outfilename in a PEM encoded format.
The optional parameter notext affects the verbosity of the output; if it is FALSE then additional human-readable information is included in the output. The default value of notext is TRUE.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
openssl_x509_export() stores x509 into a string named by output in a PEM encoded format.
The optional parameter notext affects the verbosity of the output; if it is FALSE then additional human-readable information is included in the output. The default value of notext is TRUE.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
openssl_x509_free() frees the certificate associated with the specified x509cert resource from memory.
(PHP 4 >= 4.0.6, PHP 5)
openssl_x509_parse -- Parse an X509 certificate and return the information as an arrayAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.
Questa estensione permette l'accesso ai server database Oracle. Vedere anche l'estensione OCI8.
You have to compile PHP with the option --with-oracle[=DIR], where DIR defaults to your environment variable ORACLE_HOME.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
(PHP 3, PHP 4 , PHP 5)
Ora_Bind -- effettua il binding di una variabile PHP ad un parametro di OracleRestituisce TRUE se il binding riesce, altrimenti FALSE. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Questa funzione collega la variabile PHP indicata con un parametro SQL. Il parametro SQL deve essere nella forma ":name". Con il parametro facoltativo type, si può determinare se il parametro SQL è di in/out (0, default), in (1) oppure out (2). Dalla versione 3.0.1 di PHP, su possono utilizzare le costanti ORA_BIND_INOUT, ORA_BIND_IN e ORA_BIND_OUT al posto dei numeri.
ora_bind deve essere invocata dopo ora_parse() e prima di ora_exec(). I valori di input possono essere dati mediante assegnamento alle variabili PHP collegate; dopo aver chiamato ora_exec() le variabili PHP collegate contengono i valori di output, se disponibili.
<?php ora_parse($curs, "declare tmp INTEGER; begin tmp := :in; :out := tmp; :x := 7.77; end;"); ora_bind($curs, "result", ":x", $len, 2); ora_bind($curs, "input", ":in", 5, 1); ora_bind($curs, "output", ":out", 5, 2); $input = 765; ora_exec($curs); echo "Result: $result<BR>Out: $output<BR>In: $input"; ?> |
Restituisce TRUE se la chiusura è effettuata, altrimenti FALSE. I dettagli dell'errore si ottengono con le funzioni ora_error() e ora_errorcode().
Questa funzione chiude un corsore dati aperto con ora_open().
Restituisce il nome del campo/colonna column nel cursore cursor. Il nome è restituito in lettere maiuscole. La colonna 0 è la prima.
Restituisce la dimensione del campo/colonna column nel cursore cursor. La colonna 0 è la prima.
Restituisce il tipo Oracle del campo/colonna column nel cursore cursor. La colonna 0 è la pirma. Il tipo restituito sarà uno dei seguenti:
"VARCHAR2" |
"VARCHAR" |
"CHAR" |
"NUMBER" |
"LONG" |
"LONG RAW" |
"ROWID" |
"DATE" |
"CURSOR" |
Questa funzione esegue una transazione Oracle. Una transazione è definita come tutti i cambiamenti su una data connessione dall'ultimo commit/rollback, con autocommit spento, o dall'inizio della connessione.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioniora_error() e ora_errorcode().
Questa funzione disabilita il commit automatico dopo ogni ora_exec().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Questa funzione abilita il commit automatico dopo ogni ora_exec() sulla connessione specificata.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Questa funzione è la combinazione veloce di ora_parse(), ora_exec() e ora_fetch(). Analizza, ed esegue un comando SQL, quindi scarica la prima tupla del risultato.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Vedere anche ora_parse(),ora_exec(), e ora_fetch().
Restituisce un messaggio d'errore nella forma XXX-NNNNN dove XXX è la sorgente dell'errore e NNNNN identifica il messaggio d'errore.
Nota: Il supporto per gli id di connessione è stato aggiunto nella versione 3.0.4.
Nelle versioni UNIX di Oracle, è possibile ottenere i dettagli dell'errore in questo modo: $ oerr ora 00001 00001, 00000, "unique constraint (%s.%s) violated" // *Cause: An update or insert statement attempted to insert a duplicate key // For Trusted ORACLE configured in DBMS MAC mode, you may see // this message if a duplicate entry exists at a different level. // *Action: Either remove the unique restriction or do not insert the key
Restituisce il codice numerico di errore dell'ultimo comando eseguito sul cursore o sulla connessione specificata.
Nota: Il supporto per gli id di connessione è stato aggiunto nella versione 3.0.4.
ora_exec() esegue il comando cursor, già analizzato da ora_parse().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Vedere anche ora_parse(), ora_fetch() e ora_do().
Recupera una tupla e la mette in un array. Il parametro flags ha due valori: se il flag ORA_FETCHINTO_NULLS è impostato, i campi con valori NULL vengono inseriti nell'array; se il flag ORA_FETCHINTO_ASSOC è impostato, viene creato un array associativo.
Restituisce il numero di campi acquisiti.
Vedere anche ora_parse(),ora_exec(), ora_fetch() e ora_do().
Acquisisce una tupla di dati dal cursore specificato.
Restituisce TRUE (la tupla è stata acquisita) o FALSE (non ci sono più tuple, o è avvenuto un errore). Se è avvenuto un errore, i dettagli si ottengono usando le funzioni ora_error() e ora_errorcode(). Se non sono avvenuti errori, ora_errorcode() restituirà 0.
Vedere anche ora_parse(),ora_exec(), e ora_do().
Restituisce i dati del campo o del risultato di una funzione.
Restituisce il contenuto del campo/colonna. Se avviene un errore, viene restituito il valore FALSE e ora_errorcode() restituirà un valore diverso da zero. Si noti, comunque, che un test al valore FALSE sul risultato di questa funzione può dare esito positivo anche in caso non ci siano errori (campo NULL, stringa vuota, il numero 0, la stringa "0").
Depenna l'utente e disconnette dal server.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Vedere anche ora_logon().
Stabilisce una connessione tra PHP e un database Oracle utilizzando la username user e password password specificate.
Le connessioni possono essere create usando SQL*Net fornendo il nomeTNS a user in questo modo:
Se i dati contengono caratteri non-ASCII, si deve controllare di avere impostato NLS_LANG nel proprio environment. Per quanto riguarda i moduli del server, occorre impostarlo nell' environment del server prima di avviarlo.
Restituisce un indice di connessione se l'operazione ha successo, oppure FALSE in caso di errore. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode() functions.
ora_numcols() restituisce il numero di campi di un risultato. Dopo una sequenza parse/exec/fetch restituisce solo risultati che abbiano coerenza.
Vedere anche ora_parse(),ora_exec(), ora_fetch() e ora_do().
ora_numrows() restituisce il numero di tuple in un risultato.
Apre un cursore Oracle associato alla connessione.
Restituisce un indice di cursore oppure FALSE in caso di errore. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Questa funziona analizza un comando SQL o un blocco PL/SQL e lo associa al cursore specificato.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche ora_exec(), ora_fetch() e ora_do().
Stabilisce una connessione permanente tra PHP ed un database Oracle con le username and password specificate.
Vedere anche ora_logon().
Questa funzione annulla una transazione Oracle. (Vedere ora_commit() per la definizione di una transazione.)
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode() functions.
Ovrimos SQL Server, is a client/server, transactional RDBMS combined with Web capabilities and fast transactions.
Nota: Questo modulo non è disponibile su piattaforme Windows.
You'll need to install the sqlcli library available in the Ovrimos SQL Server distribution.
To enable Ovrimos support in PHP just compile PHP with the --with-ovrimos[=DIR] parameter to your configure line. DIR is the Ovrimos' libsqlcli install directory.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Esempio 1. Connect to Ovrimos SQL Server and select from a system table
|
ovrimos_close() is used to close the specified connection to Ovrimos. This has the effect of rolling back uncommitted transactions.
ovrimos_commit() is used to commit the transaction. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
ovrimos_connect() is used to connect to the specified database.
ovrimos_connect() returns a connection id (greater than 0) or 0 for failure. The meaning of host and db are those used everywhere in Ovrimos APIs. host is a host name or IP address and db is either a database name, or a string containing the port number.
Esempio 1. ovrimos_connect() Example
|
ovrimos_cursor() returns the name of the cursor. Useful when wishing to perform positioned updates or deletes.
ovrimos_exec() executes an SQL statement (query or update) and returns a result_id or FALSE. Evidently, the SQL statement should not contain parameters.
ovrimos_execute() executes a prepared statement. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. If the prepared statement contained parameters (question marks in the statement), the correct number of parameters should be passed in an array. Notice that I don't follow the PHP convention of placing just the name of the optional parameter inside square brackets. I couldn't bring myself on liking it.
ovrimos_fetch_into() fetches a row from the result set into result_array, which should be passed by reference. Which row is fetched is determined by the two last parameters. how is one of Next (default), Prev, First, Last, Absolute, corresponding to forward direction from current position, backward direction from current position, forward direction from the start, backward direction from the end and absolute position from the start (essentially equivalent to 'first' but needs 'rownumber'). Case is not significant. rownumber is optional except for absolute positioning. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. A fetch into example
|
ovrimos_fetch_row() fetches a row from the result set. Column values should be retrieved with other calls. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. A fetch row example
|
ovrimos_field_len() is used to get the length of the output column with number field_number (1-based), in result result_id.
ovrimos_field_name() returns the output column name at the (1-based) index specified.
ovrimos_field_num() returns the (1-based) index of the output column specified by field_name, or FALSE.
ovrimos_field_type() returns the (numeric) type of the output column at the (1-based) index specified by field_number.
ovrimos_free_result() frees the specified result_id. Returns TRUE.
(PHP 4 >= 4.0.3, PHP 5)
ovrimos_longreadlen -- Specifies how many bytes are to be retrieved from long datatypesovrimos_longreadlen() specifies how many bytes are to be retrieved from long datatypes (long varchar and long varbinary). Default is zero. It currently sets this parameter the specified result set. Returns TRUE.
ovrimos_num_fields() returns the number of columns in a result_id resulting from a query.
ovrimos_num_rows() returns the number of rows affected by update operations.
ovrimos_prepare() prepares an SQL statement and returns a result_id (or FALSE on failure).
Esempio 1. Connect to Ovrimos SQL Server and prepare a statement
|
ovrimos_result_all() prints the whole result set as an HTML table. Returns the number of rows in the generated table.
Esempio 1. Prepare a statement, execute, and view the result
|
Esempio 2. ovrimos_result_all() with meta-information
|
Esempio 3. ovrimos_result_all() example
|
ovrimos_result() retrieves the output column specified by field, either as a string or as an 1-based index. Returns FALSE on failure.
The Output Control functions allow you to control when output is sent from the script. This can be useful in several different situations, especially if you need to send headers to the browser after your script has began outputting data. The Output Control functions do not affect headers sent using header() or setcookie(), only functions such as echo() and data between blocks of PHP code.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Output Control configuration options
Name | Default | Changeable |
---|---|---|
output_buffering | "0" | PHP_INI_PERDIR|PHP_INI_SYSTEM |
output_handler | NULL | PHP_INI_PERDIR|PHP_INI_SYSTEM |
implicit_flush | "0" | PHP_INI_PERDIR|PHP_INI_SYSTEM |
Breve descrizione dei parametri di configurazione.
You can enable output buffering for all files by setting this directive to 'On'. If you wish to limit the size of the buffer to a certain size - you can use a maximum number of bytes instead of 'On', as a value for this directive (e.g., output_buffering=4096).
You can redirect all of the output of your scripts to a function. For example, if you set output_handler to mb_output_handler(), character encoding will be transparently converted to the specified encoding. Setting any output handler automatically turns on output buffering.
Nota: You cannot use both mb_output_handler() with ob_inconv_handler() and you cannot use both ob_gzhandler() and zlib.output_compression.
FALSE by default. Changing this to TRUE tells PHP to tell the output layer to flush itself automatically after every output block. This is equivalent to calling the PHP function flush() after each and every call to print() or echo() and each and every HTML block.
When using PHP within an web environment, turning this option on has serious performance implications and is generally recommended for debugging purposes only. This value defaults to TRUE when operating under the CLI SAPI.
See also ob_implicit_flush().
In the above example, the output from echo() would be stored in the output buffer until ob_end_flush() was called. In the mean time, the call to setcookie() successfully stored a cookie without causing an error. (You can not normally send headers to the browser after data has already been sent.)
Nota: When upgrading from PHP 4.1 (and 4.2) to 4.3 that due to a bug in earlier versions you must ensure that implict_flush is OFF in your php.ini, otherwise any output with ob_start() will not be hidden from output.
Flushes the output buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This effectively tries to push all the output so far to the user's browser.
flush() has no effect on the buffering scheme of your webserver or the browser on the client side.
Several servers, especially on Win32, will still buffer the output from your script until it terminates before transmitting the results to the browser.
Server modules for Apache like mod_gzip may do buffering of their own that will cause flush() to not result in data being sent immediately to the client.
Even the browser may buffer its input before displaying it. Netscape, for example, buffers text until it receives an end-of-line or the beginning of a tag, and it won't render tables until the </table> tag of the outermost table is seen.
Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page.
This function discards the contents of the output buffer.
This function does not destroy the output buffer like ob_end_clean() does.
See also ob_flush(), ob_end_flush() and ob_end_clean().
This function discards the contents of the topmost output buffer and turns off this output buffering. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_clean() as the buffer contents are discarded when ob_end_flush() is called. The function returns TRUE when it successfully discarded one buffer and FALSE otherwise. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).
The following example shows an easy way to get rid of all output buffers:
Nota: If the function fails it generates an E_NOTICE.
The boolean return value was added in PHP 4.2.0.
See also ob_start(), ob_get_contents(), and ob_flush().
This function will send the contents of the topmost output buffer (if any) and turn this output buffer off. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_flush() as the buffer contents are discarded after ob_end_flush() is called. The function returns TRUE when it successfully discarded one buffer and FALSE otherwise. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).
Nota: This function is similar to ob_get_flush(), except that ob_get_flush() returns the buffer as a string.
The following example shows an easy way to flush and end all output buffers:
Nota: If the function fails it generates an E_NOTICE.
The boolean return value was added in PHP 4.2.0.
See also ob_start(), ob_get_contents(), ob_get_flush(), ob_flush() and ob_end_clean().
This function will send the contents of the output buffer (if any). If you want to further process the buffer's contents you have to call ob_get_contents() before ob_flush() as the buffer contents are discarded after ob_flush() is called.
This function does not destroy the output buffer like ob_end_flush() does.
See also ob_get_contents(), ob_clean(), ob_end_flush() and ob_end_clean().
This will return the contents of the output buffer and end output buffering. If output buffering isn't active then FALSE is returned. ob_get_clean() essentially executes both ob_get_contents() and ob_end_clean().
See also ob_start() and ob_get_contents().
This will return the contents of the output buffer or FALSE, if output buffering isn't active.
See also ob_start() and ob_get_length().
(PHP 4 >= 4.3.0, PHP 5)
ob_get_flush -- Flush the output buffer, return it as a string and turn off output bufferingob_get_flush() flushs the output buffer, return it as a string and turns off output buffering. ob_get_flush() returns FALSE if no buffering is active.
Nota: This function is similar to ob_end_flush(), except that this function returns the buffer as a string.
Esempio 1. ob_get_flush() example
The above example will output:
|
See also ob_end_clean(), ob_end_flush() and ob_list_handlers().
This will return the length of the contents in the output buffer or FALSE, if output buffering isn't active.
See also ob_start() and ob_get_contents().
This will return the level of nested output buffering handlers or zero if output buffering is not activated.
See also ob_start() and ob_get_contents().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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() is intended to be used as a callback function for ob_start() to help facilitate sending gz-encoded data to web browsers that support compressed web pages. Before ob_gzhandler() actually sends compressed data, it determines what type of content encoding the browser will accept ("gzip", "deflate" or none at all) and will return its output accordingly. All browsers are supported since it's up to the browser to send the correct header saying that it accepts compressed web pages.
Nota: mode was added in PHP 4.0.5.
Nota: You cannot use both ob_gzhandler() and ini.zlib.output_compression. Also note that using ini.zlib.output_compression is preferred over ob_gzhandler().
See also ob_start() and ob_end_flush().
ob_implicit_flush() will turn implicit flushing on or off (if no flag is given, it defaults to on). Implicit flushing will result in a flush operation after every output call, so that explicit calls to flush() will no longer be needed.
Turning implicit flushing on will disable output buffering, the output buffers current output will be sent as if ob_end_flush() had been called.
See also flush(), ob_start(), and ob_end_flush().
This 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".
See also ob_end_clean(), ob_end_flush(), ob_get_flush(), ob_start().
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.
The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.
An optional output_callback function may be specified. This function takes a string as a parameter and should return a string. The function will be called when ob_end_flush() is called, or when the output buffer is flushed to the browser at the end of the request. When output_callback is called, it will receive the contents of the output buffer as its parameter and is expected to return a new output buffer as a result, which will be sent to the browser. If the output_callback is not a callable function, this function will return FALSE.
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
Would produce:
|
See also ob_get_contents(), ob_end_flush(), ob_end_clean(), ob_implicit_flush() and ob_gzhandler().
This function rewrite the URLs and forms with the given variable.
Nota: This function buffers the output.
Esempio 1. output_add_rewrite_var() example
The above example will output:
|
See also output_reset_rewrite_vars(), ob_flush() and ob_list_handlers().
This function resets the URL rewriter and undo the changes made by output_add_rewrite_var() and/or by session_start() that are still in the buffer.
Esempio 1. output_reset_rewrite_vars() example
The above example will output:
|
See also output_add_rewrite_var(), ob_flush(), ob_list_handlers() and session_start().
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
|
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. |
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..
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.
PDFlib is available for download at http://www.pdflib.com/products/pdflib/index.html, but requires that you purchase a license for commercial use. The JPEG and TIFF libraries are required to compile this extension.
Any version of PHP 4 after March 9, 2000 does not support versions of PDFlib older than 3.0.
PDFlib 3.0 or greater is supported by PHP 3.0.19 and later.
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.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Starting with PHP 4.0.5, the PHP extension for PDFlib is officially supported by PDFlib GmbH. This means that all the functions described in the PDFlib manual (V3.00 or greater) are supported by PHP 4 with exactly the same meaning and the same parameters. Only the return values may differ from the PDFlib manual, because the PHP convention of returning FALSE was adopted. For compatibility reasons, this binding for PDFlib still supports the old functions, but they should be replaced by their new versions. PDFlib GmbH will not support any problems arising from the use of these deprecated functions.
Tabella 1. Deprecated functions and their replacements
Old function | Replacement |
---|---|
pdf_put_image() | Not needed anymore. |
pdf_execute_image() | Not needed anymore. |
pdf_get_annotation() | pdf_get_bookmark() using the same parameters. |
pdf_get_font() | pdf_get_value() passing "font" as the second parameter. |
pdf_get_fontsize() | pdf_get_value() passing "fontsize" as the second parameter. |
pdf_get_fontname() | pdf_get_parameter() passing "fontname" as the second parameter. |
pdf_set_info_creator() | pdf_set_info() passing "Creator" as the second parameter. |
pdf_set_info_title() | pdf_set_info() passing "Title" as the second parameter. |
pdf_set_info_subject() | pdf_set_info() passing "Subject" as the second parameter. |
pdf_set_info_author() | pdf_set_info() passing "Author" as the second parameter. |
pdf_set_info_keywords() | pdf_set_info() passing "Keywords" as the second parameter. |
pdf_set_leading() | pdf_set_value() passing "leading" as the second parameter. |
pdf_set_text_rendering() | pdf_set_value() passing "textrendering" as the second parameter. |
pdf_set_text_rise() | pdf_set_value() passing "textrise" as the second parameter. |
pdf_set_horiz_scaling() | pdf_set_value() passing "horizscaling" as the second parameter. |
pdf_set_text_matrix() | Not available anymore |
pdf_set_char_spacing() | pdf_set_value() passing "charspacing" as the second parameter. |
pdf_set_word_spacing() | pdf_set_value() passing "wordspacing" as the second parameter. |
pdf_set_transition() | pdf_set_parameter() passing "transition" as the second parameter. |
pdf_open() | pdf_new() plus an subsequent call of pdf_open_file() |
pdf_set_font() | pdf_findfont() plus an subsequent call of pdf_setfont() |
pdf_set_duration() | pdf_set_value() passing "duration" as the second parameter. |
pdf_open_gif() | pdf_open_image_file() passing "gif" as the second parameter. |
pdf_open_jpeg() | pdf_open_image_file() passing "jpeg" as the second parameter. |
pdf_open_tiff() | pdf_open_image_file() passing "tiff" as the second parameter. |
pdf_open_png() | pdf_open_image_file() passing "png" as the second parameter. |
pdf_get_image_width() | pdf_get_value() passing "imagewidth" as the second parameter and the image as the third parameter. |
pdf_get_image_height() | pdf_get_value() passing "imageheight" as the second parameter and the image as the third parameter. |
Most of the functions are fairly easy to use. The most difficult part is probably creating your first PDF document. The following example should help to get you started. It creates test.pdf with one page. The page contains the text "Times Roman outlined" in an outlined, 30pt font. The text is also underlined.
Esempio 1. Creating a PDF document with PDFlib
|
The PDFlib distribution contains a more complex example which creates a page with an analog clock. Here we use the in-memory creation feature of PDFlib to alleviate the need to use temporary files. The example was converted to PHP from the PDFlib example. (The same example is available in the CLibPDF documentation.)
Esempio 3. pdfclock example from PDFlib distribution
|
Add a nested bookmark under parent, or a new top-level bookmark if parent = 0. Returns a bookmark descriptor which may be used as parent for subsequent nested bookmarks. If open = 1, child bookmarks will be folded out, and invisible if open = 0.
Esempio 1. pdf_add_bookmark() example
|
Adds a link to a web resource specified by filename. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_add_locallink().
Add a link annotation to a target within the current PDF file. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
dest is the zoom setting on the destination page, it can be one of retain, fitpage, fitwidth, fitheight or fitbbox.
See also pdf_add_launchlink().
Sets an annotation for the current page. icon is one of comment, insert, note, paragraph, newparagraph, key, or help. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Add a file link annotation (to a PDF target). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_add_locallink() and pdf_add_weblink().
Adds an existing image as thumbnail for the current page. Thumbnail images must not be wider or higher than 106 pixels. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_open_image(), pdf_open_image_file() and pdf_open_memory_image().
Add a weblink annotation to a target url on the Web. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Add a counterclockwise circular arc from alpha to beta degrees with center (x; y) and radius r. Actual drawing of the circle is performed by the next stroke or fill operation.
Esempio 1. pdf_arcn() example
|
See also: pdf_arcn(), pdf_circle(), pdf_stroke(), pdf_fill() and pdf_fill_stroke().
Add a clockwise circular arc from alpha to beta degrees with center (x; y) and radius r. Actual drawing of the circle is performed by the next stroke or fill operation.
Esempio 1. pdf_arcn() example
|
See also: pdf_arc(), pdf_circle(), pdf_stroke(), pdf_fill() and pdf_fillstroke().
Add a file attachment annotation. icon is one of graph, paperclip, pushpin, or tag. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Only the 'Full' Acrobat software will be able to display these file attachments. All other PDF viewers will either show nothing or display a question mark.
Add a new page to the document. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. The width and height are specified in points, which are 1/72 of an inch.
Tabella 1. Common Page Sizes in Points
name | size |
---|---|
A0 | 2380✗3368 |
A1 | 1684✗2380 |
A2 | 1190✗1684 |
A3 | 842✗1190 |
A4 | 595✗842 |
A5 | 421✗595 |
A6 | 297✗421 |
B5 | 501✗709 |
letter (8.5"✗11") | 612✗792 |
legal (8.5"✗14") | 612✗1008 |
ledger (17"✗11") | 1224✗792 |
11"✗17" | 792✗1224 |
See also pdf_end_page().
Starts a new pattern definition and returns a pattern handle. width, and height define the bounding box for the pattern. xstep and ystep give the repeated pattern offsets. painttype=1 means that the pattern has its own colour settings whereas a value of 2 indicates that the current colour is used when the pattern is applied.
See also pdf_end_pattern().
Start a new template definition.
Add a circle with center (x, y) and radius r to the current page. Actual drawing of the circle is performed by the next stroke or fill operation.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. pdf_circle() example
|
See also: pdf_arc(), pdf_arcn(), pdf_curveto(), pdf_stroke(), pdf_fill() and pdf_fill_stroke().
Use the current path as clipping path. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Close an image retrieved with the pdf_open_image() function.
Close the page handle, and free all page-related resources. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Close all open page handles, and close the input PDF document. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_open_pdi().
Close the generated PDF file, and free all document-related resources. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_new().
Close the path, fill, and stroke it. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_closepath() and pdf_closepath_stroke().
Close the path, and stroke it. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_closepath() and pdf_closepath_fil_stroke().
Close the current path. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_closepath_stroke() and pdf_closepath_fil_stroke().
Concatenate a matrix to the CTM. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Print text at the next line. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Draw a Bezier curve from the current point, using 3 more control points. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Delete the PDF resource, and free all internal resources. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_new().
Finish the page. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_begin_page().
Finish the pattern definition. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_begin_pattern().
Finish the template definition. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
This function is deprecated, use one of the pdf_stroke(), pdf_clip() or pdf_closepath_fill_stroke() functions instead.
Fill and stroke the path with the current fill and stroke color. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_setcolor().
Fill the interior of the path with the current fill color. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_setcolor().
Prepare a font for later use with pdf_setfont(). The metrics will be loaded, and if embed is nonzero, the font file will be checked, but not yet used. encoding is one of builtin, macroman, winansi, host, a user-defined encoding name or the name of a CMap.
pdf_findfont() returns a font handle or FALSE on error.
Get the contents of the PDF output buffer. The result must be used by the client before calling any other PDFlib function.
Returns the major version number of the PDFlib.
See also pdf_get_minorversion().
Returns the minor version number of the PDFlib.
See also pdf_get_majorversion().
Get the contents of some PDFlib parameter with string type.
Get the contents of some PDI document parameter with string type.
Get the contents of some PDI document parameter with numerical type.
Get the contents of some PDFlib parameter with float type.
Reset all implicit color and graphics state parameters to their defaults. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Draw a line from the current point to (x, y). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Make a named spot color from the current color. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_setcolor().
Set the current point to (x, y. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: The current point for graphics and the current text output position are maintained separately. See pdf_set_text_pos() to set the text output position.
Create a new PDF resource, using default error handling and memory management.
See also pdf_close().
Open a raw CCITT image.
Create a new PDF file using the supplied file name. If filename is empty the PDF document will be generated in memory instead of on file. The result must be fetched by the client with the pdf_get_buffer() function. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The following example shows how to create a pdf document in memory and how to output it correctly.
Esempio 1. Creating a PDF document in memory
|
Open an image file. Supported types are jpeg, tiff, gif, and png. stringparam is either , mask, masked, or page. intparamis either 0, the image id of the applied mask, or the page.
Use image data from a variety of data sources. Supported types are jpeg, ccitt, raw. Supported sources are memory, fileref, url. len is only used when type is raw, params is only used when type is ccitt.
(PHP 3>= 3.0.10, PHP 4 , PHP 5)
pdf_open_memory_image -- Opens an image created with PHP's image functionsThe pdf_open_memory_image() function takes an image created with the PHP's image functions and makes it available for the pdf resource. The function returns a pdf image identifier.
See also pdf_close_image() and pdf_place_image().
Prepare a page for later use with pdf_place_image()
Opens an existing PDF document and prepares it for later use.
See also pdf_close_pdi().
Place an image with the lower left corner at (x, y), and scale it. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Place a PDI page with the lower left corner at (x, y), and scale it. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Draw a (width * height) rectangle at lower left (x, y). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Restore the most recently saved graphics state. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Rotate the coordinate system by phi degrees. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Save the current graphics state. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Scale the coordinate system. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 3>= 3.0.12, PHP 4 , PHP 5)
pdf_set_border_color -- Sets color of border around links and annotationsSet the border color for all kinds of annotations. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 4 >= 4.0.1, PHP 5)
pdf_set_border_dash -- Sets dash style of border around links and annotationsSets the border dash style for all kinds of annotations. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_setdash().
(PHP 3>= 3.0.12, PHP 4 , PHP 5)
pdf_set_border_style -- Sets style of border around links and annotationsSets the border style for all kinds of annotations. style is solid or dashed. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
Sets some PDFlib parameters with string type. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_set_value().
Set the text output position specified by x and y. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Set the value of some PDFlib parameter with float type. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_set_parameter().
Set the current color space and color. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. The parameter type can be fill, stroke or both to specify that the color is set for filling, stroking or both filling and stroking. The parameter colorspace can be gray, rgb, cmyk, spot or pattern. The parameters c1, c2, c3 and c4 represent the color components for the color space specified by colorspace. Except as otherwise noted, the color components are floating-point values that range from 0 to 1.
For gray only c1 is used.
For rgb parameters c1, c2, and c3 specify the red, green and blue values respectively.
For cmyk, parameters c1, c2, c3, and c4 are the cyan, magenta, yellow and black values, respectively.
For spot, c1 should be a spot color handles returned by pdf_makespotcolor() and c2 is a tint value between 0 and 1.
For pattern, c1 should be a pattern handle returned by pdf_begin_pattern().
Set the current dash pattern to b black and w white units. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Sets the flatness to a value between 0 and 100 inclusive. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Set the current font in the given size, using a font handle returned by pdf_findfont(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_findfont().
Set the current fill color to a gray value between 0 and 1 inclusive. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current stroke color to a gray value between 0 and 1 inclusive. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current fill and stroke color. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the linecap parameter to a value between 0 and 2 inclusive.
Sets the line join parameter to a value between 0 and 2 inclusive. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Sets the current linewidth to width. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Explicitly set the current transformation matrix. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Set the miter limit to a value greater than or equal to 1. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Set the current fill color to the supplied RGB values. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current stroke color to the supplied RGB values. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current fill and stroke color to the supplied RGB values. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Format text in the current font and size into the supplied text box according to the requested formatting mode, which must be one of left, right, center, justify or fulljustify. If width and height are 0, only a single line is placed at the point (left, top) in the requested mode.
Returns the number of characters that did not fit in the specified box. Returns 0 if all characters fit or the width and height parameters were set to 0 for single-line formatting.
Print text in the current font at ( x, y). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Print text in the current font and size at the current position. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Skew the coordinate system in x and y direction by alpha and beta degrees. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Returns the width of text using the 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().
Stroke the path with the current color and line width, and clear it. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
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:
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.
These functions are only available if PHP has been compiled with the --with-pfpro[=DIR] option.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Verisign Payflow Pro configuration options
Name | Default | Changeable |
---|---|---|
pfpro.defaulthost/PFPRO_VERSION < 3 | "test.signio.com" | PHP_INI_ALL |
pfpro.defaulthost | "test-payflow.verisign.com" | PHP_INI_ALL |
pfpro.defaultport | "443" | PHP_INI_ALL |
pfpro.defaulttimeout | "30" | PHP_INI_ALL |
pfpro.proxyaddress | "" | PHP_INI_ALL |
pfpro.proxyport | "" | PHP_INI_ALL |
pfpro.proxylogon | "" | PHP_INI_ALL |
pfpro.proxypassword | "" | PHP_INI_ALL |
pfpro_cleanup() is used to shutdown the Payflow Pro library cleanly. It should be called after you have processed any transactions and before the end of your script. However you may omit this call, in which case this extension will automatically call pfpro_cleanup() after your script terminates.
See also pfpro_init().
pfpro_init() is used to initialise the Payflow Pro library. You may omit this call, in which case this extension will automatically call pfpro_init() before the first transaction.
See also pfpro_cleanup().
Returns: A string containing the response.
pfpro_process_raw() processes a raw transaction string with Payflow Pro. You should really use pfpro_process() instead, as the encoding rules of these transactions are non-standard.
The first parameter in this case is a string containing the raw transaction request. All other parameters are the same as with pfpro_process(). The return value is a string containing the raw response.
Nota: Be sure to read the Payflow Pro Developers Guide for full details of the required parameters and encoding rules. You would be well advised to use pfpro_process() instead.
Esempio 1. Payflow Pro raw example
|
See also pfpro_process().
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
|
Queste funzioni permettono di accedere a diverse informazioni sul PHP stesso, come la configurazione di runtime, il moduli caricati, la versione e molto altro. Si troveranno anche funzioni per impostare le opzioni di runtime del PHP. Probabilmente la più nota tra queste è - phpinfo() -.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Parametri di configurazione per PHP Opzioni/informazioni
Nome | Default | Modificabile |
---|---|---|
assert.active | "1" | PHP_INI_ALL |
assert.bail | "0" | PHP_INI_ALL |
assert.warning | "1" | PHP_INI_ALL |
assert.callback | NULL | PHP_INI_ALL |
assert.quiet_eval | "0" | PHP_INI_ALL |
enable_dl | "1" | PHP_INI_SYSTEM |
max_execution_time | "30" | PHP_INI_ALL |
max_input_time | "60" | PHP_INI_ALL |
magic_quotes_gpc | "1" | PHP_INI_PERDIR|PHP_INI_SYSTEM |
magic_quotes_runtime | "0" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
Abilita l'analisi degli assert().
Termina uno script a fronte di un assert fallito.
Invia un PHP warning per ogni asserzione fallita.
Funzione utente da richiamare a fronte di un assert fallito
Utilizzare questo parametro di error_reporting() durante l'analisi dei un'asserzione. Se è abilitato, non sono visualizzati gli errori (error_reporting(0)) durante il parsing di una asserzione. Se disabilitato, gli errori saranno visualizzati in base all'impostazione di error_reporting().
Questa direttiva è utile soltanto nella versione di PHP attiva come modulo di Apache. Essa permette di caricare in modo dinamico le estensioni di PHP potendo impostare dl() on oppure off in base al server virtuale o per directory.
La ragione principale per disabilitare il caricamento dinamico dei moduli è la sicurezza. Con il caricamento dinamico è possibile ignorare tutte le restrizioni open_basedir. Per default il caricamento dinamico è attivo tranne quando si utilizza il safe mode. In safe mode, è sempre impossibile utilizzare dl().
Questo parametro imposta il tempo massimo in secondi concessi ad uno script per l'esecuzione prima di essere interrotto dal parser. Questo aiuta a prevenire che script scritti male blocchino il server. Per default è impostato a 30.
Il tempo massimo di esecuzione non è condizionato dalle chiamate di sistema, dalle operazioni sugli stream, eccetera. Vedere la funzione set_time_limit() per maggiori dettagli.
Non si può cambiare questo parametro con ini_set() quando il PHP gira in safe mode. L'unico modo è di disabilitare il safe mode oppure di cambiare il limite di tempo nel php.ini.
Impostail tempo massimo in secondi concesso ad uno script per ricevere i dati di input, tipo POST, GET e upload di file. Il valore di default è 60.
Imposta il parametro magic_quote per GPC (Get/Post/Cookie). Quando magic_quote è impostato a on, tutti i ' (apici singoli), " (doppi apici), \ (backslash) e NUL sono vengono preceduti in automatico dal backslash.
Nota: Se il parametro magic_quotes_sybase è impostato a ON, questo è prioritario rispetto a magic_quotes_gpc. Avere entrambi i parametri attivi significa che soltanto gli apici singoli sono preceduti dal carattere di escape come ''. Doppi apici, backslash, e NUL non vengono toccati.
Vedere anche get_magic_quotes_gpc()
Se si abilita magic_quotes_runtime, diverse funzioni che restituiscono dati da ogni tipo di fonte esterna, compresi i database ed i file di testo, avranno gli apici preceduti dal backslash. Se è anche attivato magic_quotes_sybase, soltanto l'apice singolo sarà preceduto dal carattere di escape costituito da un apice singolo anzichè il backslash.
Le costanti qui elencate sono sempre disponibili in quanto parte del core di PHP.
Tabella 2. Costanti predefinite per phpcredits()
Costante | Valore | Descrizione |
---|---|---|
CREDITS_GROUP | 1 | Lista degli sviluppatori principali |
CREDITS_GENERAL | 2 | Lista generale: design e progetto del linguaggio, autori del PHP 4.0 e del modulo SAPI. |
CREDITS_SAPI | 4 | Lista delle API server e dei loro sviluppatori. |
CREDITS_MODULES | 8 | Lista dei moduli e dei loro sviluppatori. |
CREDITS_DOCS | 16 | La lista del gruppo di documentazione. |
CREDITS_FULLPAGE | 32 | Solitamente utilizzato in combinazione con altri flag. Indica che la pagina completa HTML deve essere stampata includendo le infomazioni di altri flag. |
CREDITS_QA | 64 | Elenca i riconoscimenti per il gruppo della qualità. |
CREDITS_ALL | -1 | Tutta la lista dei meriti, equivale a CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_FULLPAGE. Genera una pagina HTML completa. Questa è l'impostazione di default. |
Tabella 3. Costanti di phpinfo()
Costante | Valore | Descrizione |
---|---|---|
INFO_GENERAL | 1 | La linea di configurazione, php.ini luogo, data di compila, Web Server, sistema e altro. |
INFO_CREDITS | 2 | PHP 4 Credits. Vedere anche phpcredits(). |
INFO_CONFIGURATION | 4 | Impostazioni correnti e di base delle opzioni PHP. Vedere anche ini_get(). |
INFO_MODULES | 8 | Moduli caricati e le loro impostazioni. |
INFO_ENVIRONMENT | 16 | Variabili d'ambiente disponibili in $_ENV. |
INFO_VARIABLES | 32 | Visualizza tutte le variabili predefinite da EGPCS (Environment, GET, POST, Cookie, Server). |
INFO_LICENSE | 64 | Informazioni sulla licenza di PHP. Vedere anche faq sulla licenza. |
INFO_ALL | -1 | Visualizza tutto quanto descritto. Questo è il valore dei default. |
Usando assert_options() si è in grado di impostare vari parametri di controllo per la funzione assert(), oppure ottenerne l'impostazione corrente.
Tabella 1. Opzioni di assert
opzione | parametro ini | default | descrizione |
---|---|---|---|
ASSERT_ACTIVE | assert.active | 1 | abilita l'assert() |
ASSERT_WARNING | assert.warning | 1 | indica a PHP i generare un warning per ogni asserzione fallita |
ASSERT_BAIL | assert.bail | 0 | termina l'esecuzione alla prima asserzione fallita |
ASSERT_QUIET_EVAL | assert.quiet_eval | 0 | disabilita la gestione degli errori nelle espressioni di asserzione |
ASSERT_CALLBACK | assert.callback | (NULL) | funzione utente da richiamare per le asserzioni fallite |
assert_options() restituirà l'impostazione originale di ogni opzione, oppure FALSE se fallisce.
assert() verifica se la data assertion è FALSE, nel caso intraprende le opportune azioni.
Se il parametro assertion è una stringa questo sarà considerato da assert() come codice PHP. I vantaggi di usare le stringhe con assertion sono che si ha meno overhead nella verifica e la visualizzazione dei messaggi che contengono assertion quando questa fallisce. Ciò significa che se si passa una condizione booleana come assertion, questa condizione non sarà mostrata come parametro della funzione che può essere definita con assert_options(), la condizione sarò in stringa prima di chiamare la funzione handler, e il valore booleano FALSE viene convertito in una stringa vuota.
Le asserzioni dovrebbero essere utilizzate solo per il debug. Si possono usare per controlli di coerenza che sono sempre TRUE e che, in caso contrario, indichino errori di programmazione, oppure per verificare la presenza o meni di certe caratteristiche, tipo le estensioni, oppure certi limiti di sistema o caratteristiche.
Le asserzioni non dovrebbero essere utilizzate per le normali operazioni di runtime quali il controllo dei parametri di input. Come regola si deve avere che il programma possa girare senza la presenza delle regole di asserzione.
Il comportamento di assert() può essere impostato tramite assert_options() oppure tramite .ini-settings come descritto nel pagine del manuale relative a quelle funzioni.
La funzione assert_options() e/o il parametro ASSERT_CALLBACK permetto di attivare una funzione di callback per gestire una asserzione fallita.
I callback di assert() sono particolarmente utili per costruire suite di test poiché permettono di catturare facilmente il codice passato all'assert, oltre alle informazioni su dove l'assert è scattato. Sebbene quest'ultime informazioni siano rilevabili anche con altri metodi, l'uso delle asserzione rende il tutto più semplice!
Le funzioni di callback devono accettare tre parametri. Il primo conterrà il nome del file in cui si trova l'asserzione fallita. Il secondo parametro conterrà il numero di linea dell'asserzione fallita, ed il terzo conterrà l'espressione dell'asserzione (se fornito - valori alfanumerici quali 1 o due" non saranno passati a questo parametro).
Esempio 1. Gestione di una asserzione fallita con codice personalizzato
|
La funzione carica il modulo di PHP passato nel parametro library. Il parametro library indica soltanto il nome del file del modulo da caricare il quale può dipendere dal piattaforma utilizzata. Ad esempio il modulo sockets (se compilato come modulo condiviso, non è il default!) sulle piattaforme Unix si chiama sockets.so, mentre in Windows si chiama php_sockets.dll.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. Se la funzionalità di carico dei moduli non è disponibile (vedi note), oppure è stata disabilitata (sia disabilitando enable_dl oppure attivando 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()
|
La directory da cui vengono caricate le estensioni dipende dal sistema operativo della macchina:
Windows - Se non viene impostato esplicitamente nel php.ini, i moduli sono caricati da c:\php4\extensions\ .
Unix - Se non viene impostato esplicitamente nel php.ini, la directory di default dipenda da
se il PHP è stato compilato con --enable-debug o meno
se il PHP è stato compilato con (versione sperimentale) ZTS (Zend Thread Safety) o meno
il valore attuale di ZEND_MODULE_API_NO (numero interno del modulo API Zend, il quale indica la data in cui si sono apportate le maggiori modifiche al modulo, ad esempio 20010901)
Nota: La funzione dl() non è supportata dai web server multithread. Utilizzare il parametro del php.ini extensions quando si debba utilizzare tali server. Mentre le versioni CGI e CLI non hanno questa limitazione.
Nota: La dl() è sensibile alla maiuscole sulle piattaforme Unix.
Nota: Questa funzione è disabilitata nella modalitàsafe-mode
Vedere anche Direttive per il carimaneto dei moduli e extension_loaded().
Restituisce TRUE se il modulo specificato da name è caricato, oppure FALSE.
Si può verificare il nome dei vari moduli caricati tramite phpinfo(), o, se si sta utilizzando le versioni CGI o CLI di PHP, si può utilizzare l'opzione -m:
$ php -m [PHP Modules] xml tokenizer standard sockets session posix pcre overload mysql mbstring ctype [Zend Modules] |
Nota: La funzione extension_loaded() utilizza i nomi interni dei moduli per verificare se tale modulo è disponibile o meno. La maggior parte dei nomi interni sono scritti in minuscolo, ma possono esserci moduli con nomi contenenti lettere maiuscole. Fare attenzione che questa funzione distingue tra lettere minuscole e maiuscole
Vedere anche get_loaded_extensions(), get_extension_funcs(), phpinfo() e dl().
Restituisce il valore corrente della variabile di configurazione indicata da varname, oppure FALSE se si verifica un errore.
La funzione non restituisce informazioni di configurazione nel caso in cui il PHP è compilato, o caricato da un file di configurazione di Apache (tramite le direttive php3_configuration_option).
Per verificare se il sistema utilizza un file di configurazione, tentare di ricavare il valore di cfg_file_path. Se è disponibile significa che si utilizza un file di configurazione.
Vedere anche ini_get().
Restituisce il nome del proprietario dello script PHP.
Vedere anche getmyuid(), getmygid(), getmypid(), getmyinode() e getlastmod().
(PHP 4 >= 4.1.0, PHP 5)
get_defined_constants -- Restituisve un array associativo con i nomi di tutte le costanti ed i loro valoriQuesta funzione restituisce i nomi ed i valori di tutte le costanti attualmente definite. Queste includono sia quelle create dalle estensioni sia quelle create con la funzione define().
Ad esempio la linea seguente:
<?php print_r(get_defined_constants()); ?> |
visualizzerà il seguente elenco:
Array ( [E_ERROR] => 1 [E_WARNING] => 2 [E_PARSE] => 4 [E_NOTICE] => 8 [E_CORE_ERROR] => 16 [E_CORE_WARNING] => 32 [E_COMPILE_ERROR] => 64 [E_COMPILE_WARNING] => 128 [E_USER_ERROR] => 256 [E_USER_WARNING] => 512 [E_USER_NOTICE] => 1024 [E_ALL] => 2047 [TRUE] => 1 ) |
Vedere anche get_loaded_extensions(), get_defined_functions() e get_defined_vars().
(PHP 4 , PHP 5)
get_extension_funcs -- Restituisce una matrice con i nomi delle funzioni di un moduloQuesta 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()
(PHP 4 >= 4.3.0, PHP 5)
get_include_path -- Restituisce il valore del parametro di configurazione include_pathRestituisce il valore di include_path.
Vedere anche ini_get(), restore_include_path(), set_include_path() e include().
(PHP 4 , PHP 5)
get_included_files -- Restituisce una matrice con i nomi dei file inclusi o richiestiRestituisce una matrice contenente i nomi di tutti i file che sono stati includi tramite le funzioni include(), include_once(), require() oppure require_once().
Lo script originario viene considerato come 'file incluso', pertanto sarà elencato insieme agli altri file referenziati da include() e simili.
File che sono inclusi più volte saranno elencati soltanto una volta sola
Nota: File inclusi tramite la direttiva auto_prepend_file non saranno inseriti nella matrice.
Esempio 1. Esempio di uso di get_included_files() del file (abc.php)
l'esempio visualizzerà:
|
Nota: In PHP 4.0.1pl2 e nelle versioni precedenti get_included_files() assumeva che i file inclusi avessero come estensione .php; file con altre estensioni erano ignorati. La matrice restituita da get_included_files() era una matrice associativa e riportava soltanto i file inclusi con include() e include_once().
Vedere anche include(), include_once(), require(), require_once() e get_required_files().
(PHP 4 , PHP 5)
get_loaded_extensions -- Restituisce una matrice con il nome di tutti i moduli compilati e caricatiRestituisce una matrice con il nome di tutti i moduli compilati e caricati nell'interprete PHP.
Ad esempio la seguente linea:
<?php print_r(get_loaded_extensions()); ?> |
restituirà qualcosa simile a:
Array ( [0] => xml [1] => wddx [2] => standard [3] => session [4] => posix [5] => pgsql [6] => pcre [7] => gd [8] => ftp [9] => db [10] => calendar [11] => bcmath ) |
Vedere anche get_extension_funcs(), extension_loaded(), dl() e phpinfo().
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
get_magic_quotes_gpc -- Restituisce l'attuale configurazione di magic quotes gpcRestituisce l'impostazione attuale della direttiva di configurazione magic_quotes_gpc (0 uguale a off, 1 per on).
Nota: Se la direttiva magic_quotes_sybase è impostata a ON, questa è prioritaria rispetto a magic_quotes_gpc. Pertanto, anche se get_magic_quotes() restituisce TRUE ne i doppi apici, ne i backslashes o i NUL saranno preceduti dal caratteri di escape. Lo saranno soltanto gli apici singoli. In questo caso saranno: ''
Si ricordi che magic_quotes_gpc non può essere impostata a runtime.
Esempio 1. Esempio di uso di get_magic_quotes_gpc()
|
Vedere anche addslashes(), stripslashes(), get_magic_quotes_runtime() e ini_get().
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
get_magic_quotes_runtime -- Restituisce l'impostazione corrente della direttiva magic_quotes_runtimeRestituisce l'impostazione corrente della direttiva magic_quotes_runtime (0 per off, 1 per on).
Vedere anche get_magic_quotes_gpc() e set_magic_quotes_runtime().
Restituisce il valore della variabile d'ambiente varname, oppure FALSE in caso di errore.
Si può accedere all'elenco di tutte le variabili d'ambiente utilizzando phpinfo(). Si può avere una descrizione della maggior parte di queste alla pagina specifiche CGI , in modo particolare nella pagina delle variabili d'ambiente.
Nota: Questa funzione non gira in modalità ISAPI.
Vedere anche putenv().
Restituisce la data dell'ultima modifica alla pagina corrente. Il valore restituito è un timestamp, può essere elaborato con la funzione date(). Restituisce FALSE su errore.
Nota: Se si è interessati ad avere la data dell'ultima modifica di un'altro file, si consideri l'uso di filemtime().
Vedere anche date(), getmyuid(), getmygid(), get_current_user(), getmyinode(), getmypid() e filemtime().
Restituisce l'ID del gruppo del proprietario dello script, oppure FALSE per errore.
Vedere anche getmyuid(), getmypid(), get_current_user(), getmyinode() e getlastmod().
Restituisce l'inode dello script, oppure FALSE su errore.
Vedere anche getmygid(), getmyuid(), get_current_user(), getmypid() e getlastmod().
Nota: Questa funzione non è implementata su piattaforme Windows
Restituisce l'ID del processo PHP, oppure FALSE in caso errore.
Avvertimento |
Gli ID di processo non sono univoci, poichè sono sorgenti di bassa entropia. Si raccomanda di non basarsi sul pid nei contesti basati sulla sicurezza. |
Vedere anche getmygid(), getmyuid(), get_current_user(), getmyinode() e getlastmod().
Restituisce l'ID utente del proprietario dello script, oppure FALSE in caso di errore.
Vedere anche getmygid(), getmypid(), get_current_user(), getmyinode() e getlastmod().
Restituisce una matrcie associativa con l'accoppiata opzione / valore basata sulle opzioni attese indicate in options, oppure FALSE in caso di errore.
Il parametro options può contenere i seguenti elementi: caratteri individualie e caratteri seguiti dai due punti per indicare un'opzione seguita da un valore. Ad esempio, la stringa di opzione x identifica il parametro -x, e una stringa x: identifica un parametro ed il suo valore -x argument. Non è rilevante se il vlore è precedeuto da spazio.
Questa funzione restituisce l'accoppiata opzione / valore. Se l'opzione non ha valori, il valore restituito sarà FALSE.
Nota: Questa funzione non è implementata su piattaforme Windows
Questa funzione è un interfaccia a getrusage(2). Restituisce una matrice associativa contente le informazioni restituite dalla chiamata di sistema. Se il parametro who vale 1, getrusage()sarà eseguita con RUSAGE_CHILDREN.
Tutte le informazioni sono accessibili tramite i nomi dei campi documentati.
Nota: Questa funzione non è implementata su piattaforme Windows
Restituisce tutte le opzioni di configurazione come una matrice associativa. Se viene specificato il parametro opzionale extension La funzione restituirà solo le opzioni specifiche per quel modulo.
I nomi delle opzioni faranno da indice per la matrcie restituita, quindi gli elementi potranno essere: global_value (impostata in php.ini), local_value (impostata in ini_set() oppure in .htaccess), e access (il livello di accesso). Per avere informazioni su cosa siano i livello di accesso, vedere la pagina del manuale su modifiche di configurazione
Nota: Per le direttive è possibile avere più livelli di accesso, è per questo che access restituisce le appropriate maschere di bit.
Esempio 1. Esempio di uso di ini_get_all()
Parte dell'aoutput potrebbe essere:
|
Vedere anche ini_get(), ini_restore(), ini_set(), get_loaded_extensions() e phpinfo().
Restituisce il valore delle opzioni di configurazione. In caso di errore, tipo la richiesta per un valore inesistente, sarà restituita una stringa vuota.
Richieste per valori booleani: Nel file ini, il valore booleano off sarà restituito come stringa vuota, 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().
Ripristina il valore della data opzione di configurazione allo stato originale.
Vedere anche ini_get(), ini_get_all() e ini_set().
Imposta il valore di una data opzione di configurazione. Se l'operazione riesce restituisce il vecchio valore, oppure FALSE se fallisce. Le opzioni di configurazione manterranno il nuovo valore durante l'esecuzione dello script, e saranno ripristinate al termine dello stesso.
Non tutte le opzioni disponibili possono essere modificate da ini_set(). 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
Nome | Default | Modificabile |
---|---|---|
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.callback | NULL | PHP_INI_ALL |
assert.quiet_eval | "0" | PHP_INI_ALL |
assert.warning | "1" | PHP_INI_ALL |
auto_append_file | NULL | PHP_INI_PERDIR |
auto_detect_line_endings | "0" | PHP_INI_ALL |
auto_globals_jit | "1" | PHP_INI_PERDIR |
auto_prepend_file | NULL | PHP_INI_PERDIR |
bcmath.scale | "0" | PHP_INI_ALL |
browscap | NULL | PHP_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_root | NULL | PHP_INI_SYSTEM |
enable_dl | "1" | PHP_INI_SYSTEM |
engine | "1" | PHP_INI_ALL |
error_append_string | NULL | PHP_INI_ALL |
error_log | NULL | PHP_INI_ALL |
error_prepend_string | NULL | PHP_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_host | NULL | PHP_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_charset | NULL | PHP_INI_ALL |
ibase.default_db | NULL | PHP_INI_SYSTEM |
ibase.default_password | NULL | PHP_INI_ALL |
ibase.default_user | NULL | PHP_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_host | NULL | PHP_INI_SYSTEM |
ifx.default_password | NULL | PHP_INI_SYSTEM |
ifx.default_user | NULL | PHP_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_database | NULL | PHP_INI_ALL |
ingres.default_password | NULL | PHP_INI_ALL |
ingres.default_user | NULL | PHP_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_parameters | NULL | PHP_INI_PERDIR |
max_execution_time | "30" | PHP_INI_ALL |
max_input_time | "-1" | PHP_INI_PERDIR |
mbstring.detect_order | NULL | PHP_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_encoding | NULL | PHP_INI_ALL |
mbstring.language | "neutral" | PHP_INI_PERDIR |
mbstring.script_encoding | NULL | PHP_INI_ALL |
mbstring.substitute_character | NULL | PHP_INI_ALL |
mcrypt.algorithms_dir | NULL | PHP_INI_ALL |
mcrypt.modes_dir | NULL | PHP_INI_ALL |
memory_limit | "8M" | PHP_INI_ALL |
mime_magic.debug | "0" | PHP_INI_SYSTEM |
mime_magic.magicfile | PHP_PREFIX | PHP_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_host | NULL | PHP_INI_ALL |
mysql.default_password | NULL | PHP_INI_ALL |
mysql.default_port | NULL | PHP_INI_ALL |
mysql.default_socket | NULL | PHP_INI_ALL |
mysql.default_user | NULL | PHP_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_host | NULL | PHP_INI_ALL |
mysqli.default_port | "3306" | PHP_INI_ALL |
mysqli.default_pw | NULL | PHP_INI_ALL |
mysqli.default_socket | NULL | PHP_INI_ALL |
mysqli.default_user | NULL | PHP_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_db | NULL | PHP_INI_ALL |
odbc.default_pw | NULL | PHP_INI_ALL |
odbc.default_user | NULL | PHP_INI_ALL |
odbc.max_links | "-1" | PHP_INI_SYSTEM |
odbc.max_persistent | "-1" | PHP_INI_SYSTEM |
open_basedir | NULL | PHP_INI_SYSTEM |
output_buffering | "0" | PHP_INI_PERDIR |
output_handler | NULL | PHP_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_dir | NULL | PHP_INI_SYSTEM |
safe_mode_protected_env_vars | "LD_LIBRARY_PATH" | PHP_INI_SYSTEM |
sendmail_from | NULL | PHP_INI_ALL |
sendmail_path | NULL | PHP_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.hostname | NULL | PHP_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_func | NULL | PHP_INI_ALL |
upload_max_filesize | "2M" | PHP_INI_PERDIR |
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
url_rewriter.tags | "a=href,area=href,frame=src,form=,fieldset=" | PHP_INI_ALL |
user_agent | NULL | PHP_INI_ALL |
user_dir | NULL | PHP_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_*
Costante | Valore | Significato |
---|---|---|
PHP_INI_USER | 1 | Entry can be set in user scripts |
PHP_INI_PERDIR | 2 | L'opzione può essere impostata in php.ini, .htaccess o httpd.conf |
PHP_INI_SYSTEM | 4 | L'opzione può essere impostata in php.ini o httpd.conf |
PHP_INI_ALL | 7 | L'opzione può essere impostata ovunque |
Vedere anche: get_cfg_var(), ini_get(), ini_get_all() e ini_restore()
Non esiste una funzione main() tranne che nel sorgente PHP. Dal PHP 4.3.0 è stata introdotta nel sorgente una nuova tipologia di errore gestibile (php_error_docref). Una caratteristica di questa è quella di fornire il link alla pagina del manuale nel messaggio di errore nel caso in cui la direttiva html_errors (on per default) e docref_root (on per default dal PHP 4.3.2) siano impostate.
Qualche volta gli errori fanno riferimento alla pagina del manuale per la funzione main() ed è per questo che esiste questa pagina. Si prega di aggiungere nei commenti sottostanti quale funzione PHP ha cusato l'errore che punta a main(), e questo sarà prontamente corretto e documentato.
Tabella 1. Errori noti che punatno a main()
Nome della funzione | Non punta più qui da |
---|---|
include() | 4.3.2 |
include_once() | 4.3.2 |
require() | 4.3.2 |
require_once() | 4.3.2 |
Vedere anche html_errors e display_errors.
Restituisce la quantità di memoria, in byte, allocata dal PHP per lo script.
memory_get_usage() sarà disponibile solo se il PHP viene compilato con la configurazione --enable-memory-limit
Vedere anche memory_limit.
(PHP 4 >= 4.3.0, PHP 5)
php_ini_scanned_files -- Restituisce l'elenco dei file .ini leti dalla directory ini aggiuntivaphp_ini_scanned_files() restituisce un elenco separato da virgola dei file di configurazione letti dopo il php.ini. Questi file sono cercati nella directory specificata dall'opzione --with-config-file-scan-dir impostata al momento della compila.
La funzione restituisce la lista separata da virgola se riesce. Al contrario, se l'impostazione --with-config-files-scan-dir non è configurata la funzione resttuisce FALSE. Se un file non è riconoscibile, questo sarà inserito nell'elenco restituito, ma il PHP darà errore. Questo errore sarà visualizzato sia al momento della compila sia utilizzando php_ini_scanned_files().
La lista restituita comprende anche il percorso di include specificato in --with-config-file-scan-dir. Ogni virgola è seguita da un carattere di a capo (newline).
Questa funzione restituisce l'ID che può essere utlizzato per visualizzar il logo PHP pre-inserito.
Vedere anche phpinfo(), phpversion(), phpcredits() e zend_logo_guid().
(PHP 4 >= 4.0.1, PHP 5)
php_sapi_name -- Restituisce il tipo di interfaccia tra il PHP ed il server webphp_sapi_name() restituisce un testo minuscolo che descrive il tipo di interfaccia tra il PHP ed il server web (Server API, SAPI). In caso di CGI PHP, la stringa è "cgi", nel caso si usi mod_php per Apache, il testo sarà "apache" e così via.
(PHP 4 >= 4.0.2, PHP 5)
php_uname -- Restituisce informazioni sul sistema operativo su cui è compilato il PHPphp_uname() restituisce una stringa con la descrizione del sistema operativo su cui gira PHP. Se si desidera semplicemente il nome del sistema operativo, si utilizzi la costante PHP_OS.
Esempio 1. Alcuni esempi di php_uname()
|
Esistono alcune Costanti PHP predefinite che possono essere di aiuto, ad esempio:
Vedere anche phpversion(), php_sapi_name() e phpinfo().
Questa funzione visualizza la lista dei riconoscimenti per gli sviluppatori del PHP, dei vari moduli, eccetera. Genera il codice HTML appropriato per inserire l'informazine in una pagina. IL parametro opzionale flag, per default vale CREDITS_ALL, permette di selezionare di personalizzare la lista. Ad esempio per stampare l'elenco generale, utilizzare:
Se si vuole stampare l'elenco degli sviluppatori principali e del grupo di documentazione, in una pagina proprio conto, utilizzare:
E se si desidera inserire l'elenco completo nella propria pagina, utilizzare un codice simile al seguente:
<html> <head> <title>My credits page</title> </head> <body> <?php // some code of your own phpcredits(CREDITS_ALL - CREDITS_FULLPAGE); // some more code ?> </body> </html> |
Tabella 1. Flag pre-definiti phpcredits()
nome | descrizione |
---|---|
CREDITS_ALL | Tutta la lista dei meriti, equivale a CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_FULLPAGE. Genera una pagina HTML completa. |
CREDITS_DOCS | La lista del gruppo di documentazione |
CREDITS_FULLPAGE | Solitamente utilizzato in combinazione con altri flag. Indica che la pagina completa HTML deve essere stampata includendo le infomazioni di altri flag. |
CREDITS_GENERAL | Lista generale: design e progetto del linguaggio, autori del PHP 4.0 e del modulo SAPI. |
CREDITS_GROUP | Lista degli sviluppatori principali |
CREDITS_MODULES | Lista dei moduli e dei loro sviluppatori |
CREDITS_SAPI | Lista delle API server e dei loro sviluppatori |
Vedere anche phpinfo(), phpversion() e php_logo_guid().
Visualizza molte informazioni sullo stato corrente del PHP Queste includono informazioni sulle opzioni di compila del PHP, sui moduli, la versioen di PHP, informazioni sul server e sull'ambiente (se compilato come modulo), l'ambiente PHP, la versione di OS, percorsi, valori delle configurazioni base e attauli, intestazioni HTTP e la licenza del PHP.
Dato che ogni sistema ha una cofigurazione differente, phpinfo() viene comunemente utilizzato per verificare le impostazioni di configurazione e le variabili predefinite disponibili in un dato sistema. Inoltre, phpinfo() è utili come strumento di debug poichè visualizza tutti i dati EGPCS (Environment, GET, POST, Cookie, Server).
L'output può essere personalizzato passando una o più delle seguenti costanti sommate a livello di bit nel parametro opzionale what. Le costanti, o i rispettivi valori, possono essere combinati anche con l'operatore or.
Tabella 1. Opzioni di phpinfo()
Nome (constant) | Valore | Descrizione |
---|---|---|
INFO_GENERAL | 1 | La linea di configurazione, php.ini luogo, data di compila, Web Server, sistema e altro. |
INFO_CREDITS | 2 | PHP 4 Credits. Vedere anche phpcredits(). |
INFO_CONFIGURATION | 4 | Impostazioni correnti e di base delle opzioni PHP. Vedere anche ini_get(). |
INFO_MODULES | 8 | Moduli caricati e le loro impostazioni. Vedere anche get_loaded_modules(). |
INFO_ENVIRONMENT | 16 | Variabili d'ambiente disponibili in $_ENV. |
INFO_VARIABLES | 32 | Visualizza tutte le variabili predefinite da EGPCS (Environment, GET, POST, Cookie, Server). |
INFO_LICENSE | 64 | Informazioni sulla licenza di PHP. Vedere anche faq sulla licenza. |
INFO_ALL | -1 | Visualizza tutto quanto descritto. Questo è il valore dei default. |
Nota: La visualizzazione di parte delle informazioni è disabilitata quando expose_php viene impostato a off. Queste includono i loghi PHP e Zend, e i credits.
Nota: La funzione phpinfo() produce un testo normale anzichè un file HTML quando è utilizzata in modalità CLI.
Vedere anche phpversion(), phpcredits(), php_logo_guid(), ini_get(), ini_set(), get_loaded_modules() e la sezione sulle Variabili Predefinite.
Restituisce una stringa contenente la versione dell'interprete PHP.
Nota: Questa informazione è anche disponibile come costante predefinita PHP_VERSION.
Vedere anche version_compare(), phpinfo(), phpcredits(), php_logo_guid() e zend_version().
Imposta una variable nell'ambiente del server. La variabile d'ambiente esisterà solo per lòa durata dsello script Alla fine di questo l'ambiente sarà ripristinato allo stato originario.
L'impostazione di certe variabili d'ambiente può causare dei problemi di sicurezza. La direttiva safe_mode_allowed_env_vars contiene un'elenco separato da virgole di prefissi. In Mpodlità Sicura, l'utente può soltanto alterare le variabili d'ambiente il cui nome inizia con il prefisso indicato da questa direttiva. Per default, gli utenti sono abilitati ad impostare le variabili d'ambiente con inizino con PHP_ (ad esempio PHP_FOO=BAR). Nota: Se questa direttiva è vuota, il PHP permetterà all'utente di modificare QUALSIASI variabile d'ambiente!
La direttiva safe_mode_protected_env_vars contiene un elenco separato da virgola di variabili d'ambiente, che l'utente non può modificare tramite putenv(). Questa variabili saranno protette anche se safe_mode_allowed_env_vars autorizza la modifica a queste.
Avvertimento |
Queste impostazioni hanno effetto soltanto se safe-mode è impostato! |
Vedere anche getenv().
Ripristina il valore del parametro di configurazione include_path al valore impostato in php.ini
Esempio 1. Esempio di uso di restore_include_path()
|
Vedere anche ini_restore(), set_include_path(), get_include_path() e include().
Imposta il parametro di configurazione include_path per la durata dello script. La funzione restituisce la vecchia impostazione di include_path se ha successo, oppure FALSE se non riesce.
Vedere anche ini_set(), get_include_path(), restore_include_path() e include().
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
set_magic_quotes_runtime -- Imposta il valore attuale di magic_quotes_runtimeImposta il valore del parametro di configurazione magic_quotes_runtime (0 per off, 1 per on).
Vedere anche get_magic_quotes_gpc() e get_magic_quotes_runtime().
Imposta il limite massimo in secondi di durata dello script. Se si raggiunge questo limite, lo script viene interrotto con un errore fatale. Per default questo limite è impostato a 30 secondi o, se esiste, al valore di max_execution_time nel php.ini. Se il parametro seconds viene impostato a zero, non si impone alcun limite di tempo.
Quando viene eseguita la funzione set_time_limit(), questa re-imposta il il contatore del tempo di esecuzione a zero. In altre parole, se il timeout è impostato al default di 30 secondi, e dopo 25 secondi di esecuzione si richiama la funzione con set_time_limit(20), lo script potrà girare per 45 secondi.
Avvertimento |
La funzione set_time_limit() non ha effetto quando il PHP gira in 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.
(PHP 4 >= 4.1.0, PHP 5)
version_compare -- Confronta due stringhe contenenti il numero di versione di "PHP-standardized"version_compare() confronta due numeri di versione "PHP-standardized" . Questa funzione è utile quando si desideri che funzioni solo con alcune versioni di PHP.
La funzione version_compare() restituisce -1 se la prima verisone è minore della seconda, 0 se sono uguali, +1 se la sceonda è inferiore.
Per prima cosa la funzione sostituisce nella strina di versione le lettere _, - e + con un puntot . ed inserisce un punto . prima e dopo ogni carattere non numerico, in modo che, ad esempio, '4.3.2RC1' diventi ''4.3.2.RC.1'. Quindi divite il testo come se usasse explode('.', $ver). Poi confronta le parti cominciando da sinistra verso destra Se una parte contiene versioni speciali queste sono gestite nel seguente modo: dev < alpha = a < beta = b < RC < pl. In quest modo possono essere confrontati non solo differenti livelli di versioni quali '4.1' e '4.1.2', ma anche versioni di PHP in fase di sviluppo.
Specificando il terzo parametro opzionale operator si possono testare particolari relazioni. I possibili operatori sono: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne. Utilizzando questi parametri, la funzione restituirà 1 se la relazione è una di quelle specificate dall'operatore, altrimenti 0.
Questa funzioen restituisce l'ID che può essere utilizzato per visualizzare il logo Zend usando l'immagine inserita nel PHP.
Vedere anche php_logo_guid().
Restituisce una stringa contenente il numero di versione dell'engine Zend.
Vedere anche phpinfo(), phpcredits(), php_logo_guid() e phpversion().
Questo modulo contiene un'interfaccia alle funzioni definite dallo standard IEEE 1003.1 (POSIX.1) che non sono accessibili in altro modo. Ad esempio lo standard POSIX.1 definisce le funzioni open(), read(), write() e close() che tradizionalmente sono parte di PHP 3 da lungo tempo. Altre funzioni più specifiche del sistema operativo non sono disponibili, e quindi con questo modulo si cerca di porre rimedio a questa mancanza dando un facile accesso a queste funzioni.
Avvertimento |
Con le funzioni POSIX si possono ricavare informazioni sensibili tipo posix_getpwnam() e simili. Nessuna delle funzioni POSIX esegue alcun tipo di controllo di accesso quando è abilitata la modalità sicura. Pertanto è vivamente consigliato di disabilitare l'estensione POSIX (impostare --disable-posix nella linea di configurazione) se si opera con la modalità sicura. |
Nota: Questo modulo non è disponibile su piattaforme Windows.
Le funzioni POSIX sono abilitate per default. Si possono disabilitare con --disable-posix.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
posix_get_last_error -- Recupera il numero di errore dell'ultima funzione posix non riuscita.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().
La funzione posix_getcwd() restituisce il percorso assoluto della corrente directory di lavoro.La funzioneposix_getcwd() restituisce FALSE se si verifica un errore.
(PHP 3>= 3.0.10, PHP 4 , PHP 5)
posix_getegid -- Restituisce l'ID del gruppo per il processo correnteLa funzione restituisce l'ID del gruppo per il processo corrente. Vedere anche posix_getgrgid() per dettagli su come convertire il numero nel nome effettivo del gruppo.
(PHP 3>= 3.0.10, PHP 4 , PHP 5)
posix_geteuid -- Restituisce l'ID dell'utente per il processo correnteRestituisce il valore numerico dell'ID dell'utente per il processo corrente. Vedere posix_getpwuid() per maggiori dettagli su come convertire il numero nel nome dell'utente.
(PHP 3>= 3.0.10, PHP 4 , PHP 5)
posix_getgid -- Restituisce il reale ID del gruppo per il processo correnteLa funzione restituisce il reale ID del gruppo del processo. Vedere anche posix_getgrgid() per dettagli su come convertire il numero nel nome effettivo del gruppo.
(PHP 3>= 3.0.13, PHP 4 , PHP 5)
posix_getgrgid -- Restituisce informazioni su un gruppo dato il suo IDRestituisce un array con le informazioni del gruppo, oppure FALSE se si verifica un errore. Se gid non è un numero la funzione restituisce NULL e genera un errore di tipo E_WARNING.
Nota: A partire da PHP 4.2.0, la funzione restituisce l'elenco dei membri del gruppo in un array ordinato per nome. Precedentemente si restituiva un intero (il numero dei membri del gruppo) ed i nomi dei membri doveva essere recuperato tramite l'indice numerico.
Vedere anche posix_getegid(), filegroup(), stat() e safe_mode_gid.
(PHP 3>= 3.0.13, PHP 4 , PHP 5)
posix_getgrnam -- Restituisce le informazioni di un gruppo dato il nome
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione restituisce una matrcie di interi contenente gli ID dei gruppi per il processo corrente. Vedere anche posix_getgrgid() per informazioni su come convertire questo numero nel nome del gruppo.
Restituisce il nome dell'utente proprietario del processo corrente. Vedere posix_getpwnam() per dettagli su come ottenere maggiori informazioni sull'utente.
(PHP 3>= 3.0.10, PHP 4 , PHP 5)
posix_getpgid -- Restituisce l'id del gruppo del processo per il controllo dei jobLa funzione restituisce l'id del gruppo per il processo indicato da pid.
Questa non è una funzione POSIX, ma è comune sui sistemi BSD e System V. Se il vostro sistema non supporta questa funzione, la funzione PHP restituirà sempre FALSE.
(PHP 3>= 3.0.10, PHP 4 , PHP 5)
posix_getpgrp -- Restituisce l'identificatore di gruppo per il processo correnteRestituisce l'identificatore del gruppo di processo per il processo corrente. Vedere le pagine del manuale del vostro sistema POSIX relativamente a POSIX.1 e getpgrp(2) per avere maggiori dettagli sui gruppi di processo.
Restituisce l'ID del processo genitore per il processo corrente.
La funzione restituisce un array associativo contenente le informazioni sull'utente con nome specificato nel parametro username.
Gli elementi dell'array sono:
Tabella 1. Array delle informazioni utente
Elemento | Descrizione |
---|---|
name | L'elemento name solitamente contiene il nome dell'utente. Questo è un nome corto, di solito meno di 16 caratteri, non il nome reale, completo, dell'utente. Questo dovrebbe essere uguale al parametro username passato alla funzione e quindi ridondante. |
passwd | L'elemento passwd contiene la password dell'utente in formato criptato. Spesso, ad esempio nei sistemi utilizzano password "shadow", vengono restituiti degli asterischi. |
uid | ID dell'utente in formato numerico. |
gid | ID del gruppo a cui appartiene l'utente. Utilizzare la funzione posix_getgrgid() per ottenere il nome del gruppo e l'elenco dei suoi membri. |
gecos | GECOS è un termine obsoleto che si riferisce a campi del comando finger su sistemi Honeywell. Tuttavia il campo è sopravvissuto ed il suo contenuto è stato formalizzato in POSIX. Il campo contiene le informazioni separate da virgola relative a nome completo dell'utente, numero telefonico dell'ufficio, numero dell'ufficio, numero telefonico di casa. In molti sistemi è disponibile solo il nome completo dell'utente. |
dir | Questo elemento contiene il percorso assoluto alla home directory dell'utente. |
shell | L'elemento shell contiene il percorso assoluto alla shell di default per l'utente. |
(PHP 3>= 3.0.13, PHP 4 , PHP 5)
posix_getpwuid -- Restituisce le informazioni di un utente dato il suo IDLa funzione restituisce un array associativo contenente le informazioni sull'utente il cui ID è stato fornito nel parametro uid.
Gli elementi dell'array sono:
Tabella 1. Array delle informazioni utente
Elemento | Descrizione |
---|---|
name | L'elemento name solitamente contiene il nome dell'utente. Questo è un nome corto, di solito meno di 16 caratteri, non il nome reale, completo, dell'utente. Questo dovrebbe essere uguale al parametro username passato alla funzione e quindi ridondante. |
passwd | L'elemento passwd contiene la password dell'utente in formato criptato. Spesso, ad esempio nei sistemi utilizzano password "shadow", vengono restituiti degli asterischi. |
uid | ID dell'utente in formato numerico. |
gid | ID del gruppo a cui appartiene l'utente. Utilizzare la funzione posix_getgrgid() per ottenere il nome del gruppo e l'elenco dei suoi membri. |
gecos | GECOS è un termine obsoleto che si riferisce a campi del comando finger su sistemi Honeywell. Tuttavia il campo è sopravvissuto ed il suo contenuto è stato formalizzato in POSIX. Il campo contiene le informazioni separate da virgola relative a nome completo dell'utente, numero telefonico dell'ufficio, numero dell'ufficio, numero telefonico di casa. In molti sistemi è disponibile solo il nome completo dell'utente. |
dir | Questo elemento contiene il percorso assoluto alla home directory dell'utente. |
shell | L'elemento shell contiene il percorso assoluto alla shell di default per l'utente. |
(PHP 3>= 3.0.10, PHP 4 , PHP 5)
posix_getrlimit -- Restituisce informazioni sui limiti delle risorse del sistema
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione restituisce il sid per il processo indicato in pid. Se pid è impostato a 0, la funzione restituisce il sid del processo corrente.
Questa non è una funzione POSIX, ma è comune sui sistemi System V. Se il vostro sistema non supporta questa funzione, la funzione PHP restituirà sempre FALSE.
(PHP 3>= 3.0.10, PHP 4 , PHP 5)
posix_getuid -- Restituisce il reale ID dell'utente per il processo correnteLa funzione restituisce il reale ID dell'utente per il processo corrente. Vedere anche posix_getpwuid() per dettagli su come convertire questo nel nome dell'utente.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione invia il segnale sig al processo il cui identificatore è pid. La funzione restituisce FALSE, se non riesce ad inviare il segnale, TRUE altrimenti.
Vedere anche anche kill(2) nel manuale del vostro sistema POSIX per avere informazioni sui processi con identificatore negativo, lo speciale pid 0, -1 ed il segnale 0.
(PHP 3>= 3.0.13, PHP 4 , PHP 5)
posix_mkfifo -- Crea un file speciale di tipo fifo (una pipe nominata)La funzione posix_mkfifo() un file speciale FIFO che esiste nel file system e agisce come teminale per comunicazioni bidirezionali tra processi.
Il secondo parametro, mode deve essere passato con notazione ottale (ad esempio 0644). I permessi della nuova FIFO dipendono anche dall'impostazione corrente di umask(). I permessi del file creato sono (mode & ~umask).
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Quando safe-mode è abilitato, PHP controlla che la directory nella quale si sta lavorando, abbia lo stesso UID dello script che è in esecuzione.
La funzione imposta l'effettivo ID di gruppo per il processo. Poichè questa è una funzione privilegiata occorre avere gli opportuni privilegi (solitamente di root) per poterla eseguire.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
Imposta lo user ID per il processo corrente. Poichè questa è una funzione privilegiata occorre avere gli opportuni privilegi (solitamente di root) per poterla eseguire.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche posix_setgid().
La funzione imposta il reale ID di gruppo per il processo. Poichè questa è una funzione privilegiata occorre avere gli opportuni privilegi (solitamente di root) per poterla eseguire. L'ordine corretto per richiamare la funzione è: posix_setgid() prima, posix_setuid() poi.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione permette al processo identificato da pid di unirsi al gruppo di processi identificati da pgid. Vedere POSIX.1 e setsid(2) nel manuale del vostro sistema POSIX per avere maggiori dettagli sui gruppi di processi e sul controllo dei job. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione rende il processo corrente leader di sessione. Vedere POSIX.1 e setsid(2) nelle pagine del manuale del vostro sistema POSIX per maggiori dettagli sui gruppi di processi e sul controllo dei job. La funzione restituisce l'id di sessione.
La funzione imposta il reale ID di utente per il processo corrente. Questa è una funzione privilegiata e pertanto richiede gli opportuni privilegi (di solito root) per potere essere eseguita.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche posix_setgid().
(PHP 4 >= 4.2.0, PHP 5)
posix_strerror -- Recupera il messaggio di errore di un dato codice di errore.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().
Restituisce una serie di stringhe con le imformazioni sull'utilizzo di CPU del processo. L'indice della matrice è:
ticks - il numero di ticks dall'ultimo rebbot.
utime - user time utilizzato dal processo.
stime - system time utilizzato dal processo.
cutime - user time uutilizzato dal processo e dai suoi figli.
cstime - system time uutilizzato dal processo e dai suoi figli.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione restituisce un array con informazioni sul sistema. Le chiavi dell'array sono:
sysname - nome del sistema operativo (es. Linux)
nodename - nome del sistema (es. valiant)
release - release del sistema operativo (es. 2.2.10)
version - versione del sistema operativo (es. #4 Tue Jul 20 17:01:36 MEST 1999)
machine - architettura del sistema (es. i586)
domainname - nome del dominio DNS (es. example.com)
La chiave domainname è una estensione GNU e non è parte di POSIX.1, quindi questo campo è disponibile soltanto su sistemi GNU o quando si utilizza la libc di GNU.
Lo standard POSIX richiede di non fare affidamento sul formato dei valori restituiti, ad esempio non aspettarsi di avere sempre tre cifre nel numero di versione.
Il database PostgreSQL è un prodotto OpenSource ed è disponibile gratuitamente. Postgres, sviluppato originariamente nel Dipartimento di Informatica dell'Università di Berkeley, ha anticipato molti dei concetti su oggetti e relazioni che ora stanno diventando disponibili in alcuni database commerciali. Postgres fornisce supporto per il linguaggio SQL/92/SQL99, transazioni, integrità referenziale, stored procedures ed estensibilità dei tipi. PostgreSQL è un discendente open source dell'originario codice di Berkeley.
Per utilizzare il supporto a PostgreSQL, occorre PostgreSQL 6.5 o versioni più recenti. PostgreSQL 7.0 o successivi permettono di abilitare tutte le funzionalità di questo modulo. PostgreSQL ammette molte codifiche di carattere, tra cui la codifica multibyte. La versione corrente e maggiori informazioni su PostgreSQL sono disponibili su http://www.postgresql.org/ e http://techdocs.postgresql.org/.
In order to enable PostgreSQL support, --with-pgsql[=DIR] is required when you compile PHP. DIR is the PostgreSQL base install directory, defaults to /usr/local/pgsql. If shared object module is available, PostgreSQL module may be loaded using extension directive in php.ini or dl() function.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. PostgreSQL configuration options
Name | Default | Changeable |
---|---|---|
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 |
Breve descrizione dei parametri di configurazione.
Whether to allow persistent Postgres connections.
The maximum number of persistent Postgres connections per process.
The maximum number of Postgres connections per process, including persistent connections.
Detect broken persistent links with pg_pconnect(). Needs a little overhead.
Whether or not to ignore PostgreSQL backend notices.
Whether or not to log PostgreSQL backends notice messages. The PHP directive pgsql.ignore_notice must be off in order to log notice messages.
Avvertimento |
L'utilizzo del modulo PostgreSQL con PHP 4.0.6 non è raccomandato a causa di un bug nella gestione dei messaggi. Si usi PHP 4.1.0 o successivi. |
Avvertimento | ||||||||||||||||||||||||||||||||||||||||||||
I nomi delle funzioni relative a PostgreSQL verranno cambiate a partire dalla versione 4.2.0 per conformarsi agli standard di sviluppo attuali. La maggior parte dei nuovi nomi avrà underscore aggiuntivi, per esempio pg_lo_open(). Alcune funzioni verranno rinominate per dare consistenza. Per esempio pg_exec() diventerà pg_query(). I vecchi nomi potranno essere usati nella versione 4.2.0 e in alcune versioni successive alla 4.2.0, ma potranno essere cancellati in futuro. Tabella 2. Nomi di funzione cambiati
La vecchia sintassi di pg_connect()/pg_pconnect() sarà deprecata per supportare, in futuro, connessioni asincrone. Si usi una stringa di connessione con pg_connect() e pg_pconnect(). |
Non tutte le funzioni sono supportate su tutte le architetture. Dipende dalla versione di libpq (L'interfaccia Client C per PostgreSQL) e da come libpq è compilato. Se c'è una funzione mancante, libpq non supporta la feature richiesta per quella funzione.
È importante usare versioni di libpq più recenti rispetto al Server PostgreSQL al quale ci si vuole collegare. Se si usa una versione di libpq più vecchia rispetto al Server PostgreSQL al quale ci si vuole collegare, si andrà probabilmente incontro a problemi.
Fin dalla versione 6.3 (03/02/1998) PostgreSQL usa gli unix domain socket di default. La porta TCP, di default, NON verrà aperta. La tabella sottostante descrive queste nuove possibilità di connessione. Questo socket può essere trovato in /tmp/.s.PGSQL.5432. Questa opzione può venire abilitata con la flag '-i' da postmaster e il suo significato è: "ascolta i socket TCP/IP così come gli Unix domain socket".
Tabella 3. Postmaster e PHP
Postmaster | PHP | Status |
---|---|---|
postmaster & | pg_connect("dbname=NomeMioDatabase"); | OK |
postmaster -i & | pg_connect("dbname=NomeMioDatabase"); | OK |
postmaster & | pg_connect("host=localhost dbname=NomeMioDatabase"); | Unable to connect to PostgreSQL server: connectDB() failed: Is the postmaster running and accepting TCP/IP (with -i) connection at 'localhost' on port '5432'? in /path/to/file.php on line 20. |
postmaster -i & | pg_connect("host=localhost dbname=NomeMioDatabase"); | OK |
Si può stabilire una connessione al server PostgreSQL usando le seguenti coppie di valori impostate nella stringa di comando: $conn = pg_connect("host=IlMioHost port=LaMiaPorta tty=myTTY options=LeMieOpzioni dbname=IlMioDB user=IlMioUtente password=LaMiaPassword ");
L'uso della sintassi in uso precedentemente: $conn = pg_connect ("host", "port", "options", "tty", "dbname") è deprecato.
Le variabili d'ambiente modificano il comportamento server/client di PostgreSQL. Per esempio, il modulo PostgreSQL si baserà sulla variabile PGHOST quando il nome dell'host è omesso nella stringa di connessione. Le variabili d'ambiente riconosciute sono diverse da versione a versione. Consultare il Manuale del Programmatore PostgreSQL (libpq - Variabili d'Ambiente) per ulteriori dettagli.
Assicurarsi di aver impostato le variabili d'ambiente per l'utente appropriato. Usare $_ENV o getenv() per controllare quali variabili d'ambiente sono disponibili al processo corrente.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
A partire da PostgreSQL 7.1.0, il tipo di dato text ha 1GB come dimensione massima. Nelle versioni più vecchie di PostgreSQL il tipo di dato text è limitato dalla dimensione del block. (Default 8KB. Massimo 32KB, specificato al momento della compilazione)
Per usare l'interfaccia large object (lo), è necessario includerla entro un blocco di una transazione. Un blocco di transazione inizia con un comando SQL BEGIN e se la transazione è stata valida, termina con COMMIT o END. Se la transazione fallisce, essa deve venire chiusa con ROLLBACK o ABORT.
Esempio 2. Utilizzare Large Objects
|
(PHP 4 >= 4.2.0, PHP 5)
pg_affected_rows -- Restituisce il numero delle tuple coinvolte dall'ultimo comandopg_affected_rows() restituisce il numero di tuple (istanze/record/righe) coinvolte dalle query INSERT, UPDATE, e DELETE eseguite da pg_query(). Se nessuna tupla è stata modificata da questa funzione, restituisce 0.
Nota: Questa funzione si chiamava pg_cmdtuples().
Vedere anche pg_query() e pg_num_rows().
pg_cancel_query() annulla una query asincrona inviata da pg_send_query(). Non è possibile annullare query eseguite attraverso pg_query().
Vedere anche pg_send_query() e pg_connection_busy()
(PHP 3 CVS only, PHP 4 >= 4.0.3, PHP 5)
pg_client_encoding -- Restituisce la codifica caratteri del clientpg_client_encoding() restituisce la codifica carattere del client sotto forma di stringa. La stringa può essere : SQL_ASCII, EUC_JP, EUC_CN, EUC_KR, EUC_TW, UNICODE, MULE_INTERNAL, LATINX (X=1...9), KOI8, WIN, ALT, SJIS, BIG5, WIN1250.
Nota: Questa funzione richiede PHP-4.0.3 o successivi e PostgreSQL-7.0 o successivi. Se libpq è compilata senza il supporto per la codifica multibyte, pg_set_client_encoding() restituisce sempre "SQL_ASCII". Le codifiche supportate dipendono dalla versione di PostgreSQL. Consultare il manuale di PostgreSQL per i dettagli sull'abilitazione del supporto della codifica multibyte e sulle codifiche riconosciute.
Questa funzione si chiamava pg_clientencoding().
Vedere anche pg_set_client_encoding().
pg_close() chiude la connessione non persistente verso un database PostgreSQL, identificata dalla risorsa connessione. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: iL'uso di pg_close() non è normalmente necessario, dal momento che le connessioni non persistenti vengono chiuse automaticamente alla fine dell'esecuzione dello script.
Se c'è una risorsa large object aperta sulla connessione, non chiudere quest'ultima finché la risorsa non è stata chiusa a sua volta.
pg_connect() restituisce una risorsa di connessione necessaria per l'utilizzo delle altre funzioni PostgreSQL.
pg_connect() stabilisce una connessione a un database PostgreSQL specificato da stringa_connessione. Restituisce una risorsa di connessione in caso di successo. Restituisce FALSE, se la connessione non può essere stabilita. stringa_connessione dovrebbe essere una stringa racchiusa tra apici.
Esempio 1. Uso di pg_connect
|
Se viene eseguita una seconda chiamata a pg_connect() con stessi argomenti nella stringa_connessione, non viene stabilita una nuova connessione, bensì viene restituita la risorsa che punta alla connessione già aperta. Si possono avere connessioni multiple allo stesso database se si usano stringhe di connessione differenti.
La sintassi a parametri multipli: $conn = pg_connect ("host", "port", "options", "tty", "dbname") è deprecata.
Vedere anche pg_pconnect(), pg_close(), pg_host(), pg_port(), pg_tty(), pg_options() e pg_dbname().
pg_connection_busy() restituisce TRUE se la connessione è occupata. In questo caso, la query precedentamente inviata è ancora in esecuzione. Se pg_get_result() viene chiamata, verrà bloccata.
Vedere anche pg_connection_status() e pg_get_result()
pg_connection_reset() ripristina la connessione. È utile per la gestione degli errori. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pg_connect(), pg_pconnect() e pg_connection_status()
pg_connection_status() restituisce lo stato di una connessione. I possibili valori sono PGSQL_CONNECTION_OK e PGSQL_CONNECTION_BAD.
Vedere anche pg_connection_busy().
(PHP 4 >= 4.3.0, PHP 5)
pg_convert -- Converte i valori di un array associativo in una forma compatibile con i comandi SQL.pg_convert() controlla e converte arrayassoc rendendolo compatibile con i comandi SQL.
Nota: Questa funzione è sperimentale.
Vedere anche pg_meta_data()
pg_copy_from() inserisce le tuple in una tabella etraendole dall'array tuple. Utilizza internamente il comando OPY per inserire i record. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche pg_copy_to()
pg_copy_to() copia una tabella in un array. Internamente utilizza il comando SQL COPY TO per inserire le tuple. Restituisce l'array risultante. Restituisce FALSE in caso di errore.
Vedere anche pg_copy_from()
pg_dbname() restituisce il nome del database associato alla risorsa connessione Restituisce FALSE, if connessione non è una valida risorsa di connessione PostgreSQL.
pg_delete() cancella le tuple indicate dalle condizioni specificate da arrayassoc composto da campo=>valore. Se opzioni è specificato, pg_convert() viene applicata a arrayassoc con l'opzione data.
Esempio 1. pg_delete
|
Nota: Questa funzione è sperimentale.
Vedere anche pg_convert()
pg_end_copy() sincronizza il frontend PostgreSQL (normalmente un processo del server web) con il server PostgreSQL dopo aver eseguito una operazione di copia attraverso pg_put_line(). pg_end_copy() deve essere invocato, altrimenti il server PostgreSQL può rimanere fuori sincronizzazione con il frontend e restituire un errore. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Per ulteriori dettagli ed esempio, vedere anche pg_put_line().
(PHP 4 >= 4.2.0, PHP 5)
pg_escape_bytea -- Aggiunge le sequenze di escape ai dati binari nel tipo byteapg_escape_bytea() aggiunge le sequenze di escape nei dati di tipo bytea. Restituisce una stringa con le sequenze.
Nota: Quando si esegue una SELECT su un tipo bytea, PostgreSQL restituisce dei byte formattati in ottale e con il prefisso \ (es. \032). Agli utenti è lasciato il compito di convertire questi valori in formato binario.
Questa funzione richiede una versione di PostgreSQL pari o superiore alla 7.2. Con PostgreSQL 7.2.0 e 7.2.1, il tipo bytea richiede un cast quando si abilita il supporto multi-byte. Es. INSERT INTO tabella (immagine) VALUES ('$immagine_con_escape'::bytea); PostgreSQL 7.2.2 e successivi non necessitano del cast. L'eccezione è che quando le codifiche di carattere del client e del backend non corrispondono, ci possono essere errori del flusso multi-byte. L'utente deve effettuare un cast a bytea per evitare questo errore.
Le nuove versioni di PostgreSQL avranno il supporto per la funzione di unescape. Il supporto per la funzione unescape verrà aggiunto non appena disponibile.
See also pg_escape_string()
pg_escape_string() aggiunge le sequenze di escape alle stringhe di tipo text/char. Restituisce la stringa modificata con le sequenze per PostgreSQL. L'uso di questa funzione è raccomandato al posto di addslashes().
Nota: Questa funzione richiede PostgreSQL 7.2 o successivi.
Vedere anche pg_escape_bytea()
pg_fetch_all() restituisce un array che contiene tutte le tuple (righe/record) contenuti nella risorsa risultato. Restituisce FALSE se non ci sono tuple.
Vedere anche pg_fetch_row(), pg_fetch_array(), pg_fetch_object() e pg_fetch_result().
Esempio 1. PostgreSQL fetch array
|
pg_fetch_array() restituisce un array che corrisponde alla riga caricata (tuple/record). Restituisce FALSE se non ci sono più righe.
pg_fetch_array() è una versione estesa di pg_fetch_row(). Oltre a salvare i dati in un array con indici numerici, li salva pure in un array associativo, utilizzando i nomi dei campi come chiave.
tupla è il numero della riga (record) che deve essere caricata. La prima riga è la 0.
tipo_risultato è un parametro opzionale che controlla come il risultato viene restituito. result_type è una costante e può assumere i seguenti valori: PGSQL_ASSOC, PGSQL_NUM, e PGSQL_BOTH. pg_fetch_array() restituisce un array associativo con il nome del campo come chiave con PGSQL_ASSOC, oppure l'indice del campo con PGSQL_NUM o entrambi con PGSQL_BOTH. Il default è PGSQL_BOTH.
Nota: tipo_risultato è stato aggiunto nel PHP 4.0.
pg_fetch_array() NON è più lento di pg_fetch_row(), inoltre è più facile da usare.
Esempio 1. PostgreSQL fetch array
|
Vedere anche pg_fetch_row(), pg_fetch_object() e pg_fetch_result().
Nota: Dalla versione 4.1.0, tupla è opzionale. La chiamata a pg_fetch_array() incrementa di 1 il puntatore alle tuple.
pg_fetch_assoc() returns an associative array that corresponds to the fetched row (tuples/records). It returns FALSE, if there are no more rows.
pg_fetch_assoc() is an extended version of pg_fetch_row(). In addition to storing the data in the numeric indices (field index) to the result array, it also stores the data in associative indices (field name) by default.
row is row (record) number to be retrieved. First row is 0.
pg_fetch_assoc() is NOT significantly slower than using pg_fetch_row(), while it provides a significant ease of use.
See also pg_fetch_row(), pg_fetch_array(), pg_fetch_assoc(), pg_fetch_object() and pg_fetch_result().
Esempio 1. PostgreSQL fetch array
|
pg_fetch_object() restituisce un oggetto avente le proprietà che corrispondono alla tupla scaricata. Restituisce FALSE se non ci sono più tuple o in caso di errore.
pg_fetch_object() è simile a pg_fetch_array(), con una differenza - viene restituito un oggetto invece che un array. Indirettamente, questo significa che si può accedere ai dati solo attraverso i nomi dei campi, e non attraverso i loro indici numerici (i nomi delle proprietà non possono essere numeri).
tupla è il numero della riga (record) da caricare. La prima tupla è la numero 0.
Per quanto riguarda la velocità di esecuzione, questa funzione è identica a pg_fetch_array(), ed è veloce quasi quanto pg_fetch_row() (la differenza è trascurabile).
Nota: Dalla versione 4.1.0, tupla è opzionale.
Dalla versione 4.3.0, tipo_risultato è di default a PGSQL_ASSOC mentre il default delle versioni precedenti era PGSQL_BOTH. La proprietà numerica è inutile, dal momento che un nome di proprietà numerico non è valido in PHP.
tipo_risultato potrebbe essere abbandonato nelle versioni future.
Esempio 1. Postgres fetch object
|
Vedere anche pg_query(), pg_fetch_array(), pg_fetch_row() e pg_fetch_result().
Nota: Dalla versione 4.1.0, row è diventato opzionale. La chiamata alla pg_fetch_object() incrementa di 1 il contatore di riga interno.
pg_fetch_result() restituisce i valori da una risorsa risultato ottenuta mediante pg_query(). tupla è un intero. campo è il nome del campo (stringa) o l'indice del campo (intero). I parametri tupla e campo indicano quale cella nella tabella risultante va restituita. La numerazione delle tuple parte da 0. Invece di indicare il nome del campo, si può usare l'indice del campo sotto forma di numero senza virgolette. Gli indici dei campo partono da 0.
PostgreSQL ha molti tipi di dato e solo quelli più usati sono supportati direttamente da questa funzione. Tutti gli integer, sono restituiti come valori integer. Tutti i float, e i tipi real sono restituiti come valori float. Boolean è restituito come "t" o "f". Tutti gli altri tipi, compresi gli array, sono restituiti come stringhe formattate nello stesso modo di default che si puo vedere nel programma psql.
pg_fetch_row() carica un record dal risultato della query associato alla risorsa identificata da result. La riga (record) è restituia sotto form di array. Ogni campo è identificato da un indice numerico, che inizia da 0.
Restituisce un array che corrisponde alla riga caricata, oppure FALSE se non ci sono altre tuple.
Esempio 1. Postgres fetch row
|
Vedere anche pg_query(), pg_fetch_array(), pg_fetch_object() e pg_fetch_result().
Nota: Dalla versione 4.1.0, row è opzionale. La chiamata a pg_fetch_row() incrementa il puntatore alle tuple di 1.
pg_field_is_null() controlla se un campo è NULL o meno. Restituisce se il campo nella tupla data è NULL. Restituisce 0 se il campo nella tupla NON è NULL. Il campo può essere specificato con un indice di colonna (numero) o come un nome di campo (stringa). La numerazione comincia da 0.
Nota: Questa funzione si chiamava g_fieldisnull().
pg_field_name() restituisce il nome del campo che occupa la posizione indicata da numero_campo, rispetto alla risorsa risultato. La numerazione dei campi parte da 0.
Nota: Questa funzione si chiamava pg_fieldname().
Vedere anche pg_field_num().
pg_field_num() restituisce il numero della colonna che corrisponde al campo nome_campo nella risorsa PostgreSQL risultato spacificata. La numerazione dei campi parte da 0. Questa funzione restituisce -1 in caso di errore.
Nota: Questa funzione si chiamava pg_fieldnum().
Vedere anche pg_field_name().
pg_field_prtlen() restituisce la reale lunghezza (numero di caratteri) di uno specifico valore in un risultato di PostgreSQL. La numerazione delle tuple parte da 0. Questa funzione restituisce -1 in caso di errore.
Nota: Questa funzione si chiamava pg_field_prtlen().
Vedere anche pg_field_size().
pg_field_size() restituisce la dimensione di memorizzazione (in bytes) del campo indicato all'interno di risultato. La numerazione dei campi comincia da 0. Una dimension del campo di -1 indica un campo a lunghezza variabile. Questa funzione restituisce FALSE in caso di errore.
Nota: Questa funzione si chiamava pg_fieldsize().
Vedere anche pg_field_prtlen() e pg_field_type().
pg_field_type() restituisce una stringa contenente il nome del tipo del campo specificato da numero_campo nella risorsa PostgreSQL specificata da risultato. La numerazione dei campi comincia da 0.
Nota: Questa funzione si chiamava pg_fieldtype().
Vedere anche pg_field_prtlen() e pg_field_name().
pg_free_result() deve essere chiamata solo se si è preoccupati di aver usato troppa memoria durante l'esecuzione dello script. Normalmente tutte le aree di memoria allocate per i risultati sono automaticamente deallocate alla fine dell'esecuzione. Se invece si è sicuri di non dover più utilizzare i dati del risultato, è possibile chiamare pg_free_result() con la risorsa result come argomento e la memoria associata verrà liberata. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Questa funzione si chiamava pg_freeresult().
See also pg_query().
pg_get_notify() gets notify message sent by NOTIFY SQL command. To recieve nofigy messages, LISTEN SQL command must be issued. If there is notify message on the connection, array contains message name and backend PID is returned. If there is no message, FALSE is returned.
See also pg_get_pid()
Esempio 1. PostgreSQL NOTIFY message
|
pg_get_pid() gets backend (database server process) PID. PID is useful to check if NOTIFY message is sent from other process or not.
See also pg_get_notify()
pg_get_result() estrae la risorsa risultato dalle query asincrone eseguite da pg_send_query(). pg_send_query() può inviare query multiple al server PostgreSQL server e pg_get_result() è utilizzat per recuperare i risultati uno ad uno. Restituisce la risorsa risultato. Se non ci sono più risultati, restituisce FALSE.
pg_host() restituisce il nome dell'host a cui la risorsa PostgreSQL connessione è connessa.
Vedere anche pg_connect() e pg_pconnect().
pg_insert() inserisce array_assoc composto da campo=>valore nella tabella specificata da nome_tabella. Se opzioni è specificato, pg_convert() è eseguita su array_assoc con le opzioni date.
Nota: Questa funzione è sperimentale.
Vedere anche pg_convert()
pg_last_error() restituisce l'ultimo messaggio di errore della connessione specificata.
I messaggi di errore possono essere sovrascritti da chiamate a funzioni interne a PostgreSQL(libpq). Quindi questa funzione potrebbe non restituire il messaggio di errore corretto, se più errori si sono verificati in una funzione interna di PostgreSQL.
Utilizzare pg_result_error(), pg_result_status() e pg_connection_status() per una migliore gestione degli errori.
Nota: Questa funzione si chiamava pg_errormessage().
Vedere anche pg_result_error().
(PHP 4 >= 4.0.6, PHP 5)
pg_last_notice -- Restituisce l'ultimo messaggio di notifica dal server PostgreSQLpg_last_notice() restituisce l'ultimo messaggio di notifica emesso dal server PostgreSQL specificato dal parametro connessione. Il server PostgreSQL invia messaggi di notifica in parecchi case, per esempio se le transazioni non possono essere continuate. Con pg_last_notice() è possibile evitare di eseguire query inutili, controllando se la notifica è relativa alla transazione o meno.
Avvertimento |
Questa funzione è SPERIMENTALE e non è completamente implementata allo stato attuale. pg_last_notice() è stato aggiunta nel PHP 4.0.6. Comunque, il PHP 4.0.6 ha dei problemi con la manipolazione dei messaggi di notifica. L'uso del modulo PostgreSQL con il PHP 4.0.6 non è raccomandato anche se non si fa uso di pg_last_notice(). Questa funzione è completamente implementata in PP 4.3.0. Le versioni di PHP precedenti alla 4.3.0 ignorano il parametro di connessione al database. |
Il tracciamento dei messaggi di notifica può essere reso opzionale impostando a 1 la variabile pgsql.ignore_notice nel file php.ini a partire dal PHP 4.3.0.
Il log dei messaggi di notifica può essere reso opzionale impostando a 0 la variabile pgsql.log_notice nel file php.ini a partire dal PHP 4.3.0. A meno che pgsql.ignore_notice sia impostato a 0, i messaggi di notifica non possono essere registrati.
See also pg_query() e pg_last_error().
pg_last_oid() è utilizzato per recuperare l'oid assegnato ad una tupla inserita (record), se la risorsa risultato deriva dall'ultimo comando inviato attraverso pg_query(), e se quest'ultimo è un SQL INSERT. Restituisce un intero positivo se esiste un oid valido. Restituisce invece FALSE in caso di errore o se l'ultimo comnado inviato da pg_query() non era un INSERT, oppure se l'INSERT ha fallito.
Il campo OID è diventato opzionale dal PostgreSQL 7.2. Quando il campo OID non è definito in una tabella, il programmatore deve utilizzare pg_result_status() per controllare se il record è stato inserito con successo.
Nota: Questa funzione si chiamava pg_getlastoid().
Vedere anche pg_query() e pg_result_status()
pg_lo_close() chiude un Large Object. large_object è una risorsa large object ottenuta attraverso pg_lo_open().
Per utilizzare l'interfaccia large object (lo), è necessario includere la chiamata in un blocco di transazione.
Nota: Questa funzione si chiamava pg_loclose().
Vedere anche pg_lo_open(), pg_lo_create() e pg_lo_import().
pg_lo_create() crea un Large Object e restituisce l'oid dello stesso. connessione specifica una connessione valida al database aperta da pg_connect() o pg_pconnect(). I modi di accesso di PostgreSQL INV_READ, INV_WRITE e INV_ARCHIVE non sono supportati, l'oggetto è sempre creato con accesso sia in lettura che in scrittura. INV_ARCHIVE è stato rimosso da PostgreSQL (versioni 6.3 e successive). La funzione restituisce l'oid del large object, altrimenti restituisce FALSE in caso di errore.
Per utilizzare l'interfaccia large object (lo) è necessario includerla in un blocco di transazione.
Nota: Questa funzione si chiamava pg_locreate().
L'argomento oid specifica l'oid del large object da salvare e l'argomento percorso specifica il percorso del file. Restituisce FALSE in caso di errore, TRUE altrimenti.
Per utilizzare l'interfaccia large object (lo), occorre includere il comando in un blocco di transazione.
Nota: Questa funzione si chiamava pg_loexport().
Vedere anche pg_lo_import().
Nelle versioni precedenti al PHP 4.2.0 la sintassi di questa funzione era differente, come nella seguente definizione:
int pg_lo_import ( string percorso [, resource connessione])Il parametro percorso specifica il percorso del file che deve essere importato nel large object. Restituisce FALSE in caso di errore, altrimenti l'oid del large object appena creato.
Per utilizzare l'interfaccia large object (lo), occorre includere il comando in un blocco di transazione.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Nota: Questa fuinzione si chiamava pg_loimport().
Vedere anche pg_lo_export() e pg_lo_open().
pg_lo_open() apre un Large Object e restituisce una risorsa (riferimento) large object. La risorsa incapsula le informazioni sulla connessione. oid specifica un oid valido di un large object e modo può essere "r", "w", o "rw". Restituisce FALSE se avviene un errore.
Avvertimento |
Non chiudere la connessione al database prima di aver chiuso il large object. |
Per utilizzare l'interfaccia large object (lo), occorre includere il comando in un blocco di transazione.
Nota: Questa funzione si chiamava pg_loopen().
Vedere anche pg_lo_close() e pg_lo_create().
(PHP 4 >= 4.2.0, PHP 5)
pg_lo_read_all -- Legge interamente un large object e lo manda direttamente al browserpg_lo_read_all() legge un large object e lo passa direttamente al browser dopo aver inviato tutti gli header in attesa. È pensata principalmente per inviare dati binari, come immagini o suoni. Restituisce il numero di byte letti. Restituisce FALSE in caso di errore.
Per utilizzare l'interfaccia large object (lo), occorre includere il comando in un blocco di transazione.
Nota: Questa funzione si chiamava pg_loreadall().
Vedere anche pg_lo_read().
pg_lo_read() legge al massimo lung byte da un large object e li restituisce sotto forma di stringa. large_object specifica una risorsa large object valida e lung specifica la lunghezza massima accettabile del segmento del large object. Restituisce FALSE in caso di errore.
Per utilizzare l'interfaccia large object (lo), occorre includere il comando in un blocco di transazione.
Nota: Questa funzione si chiamava pg_loread().
Vedere anche pg_lo_read_all().
pg_lo_seek() ricerca la posizione di un large object. whence è PGSQL_SEEK_SET, PGSQL_SEEK_CUR o PGSQL_SEEK_END.
Vedere anche pg_lo_tell().
pg_lo_tell() restituisce la posizione attuale (offset dall'inizio di un large object).
Vedere anche pg_lo_seek().
pg_lo_unlink() cancella un large object identificato da oid. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Per utilizzare l'interfaccia large object (lo), occorre includere il comando in un blocco di transazione.
Nota: Questa funzione si chiamava pg_lo_unlink().
Vedere anche pg_lo_create() e pg_lo_import().
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_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() 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() 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() restituisce una stringa contenente le opzioni specificate alla risorsa PostgreSQL connessione.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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() 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().
pg_port() restituisce il numero della porta a cui la risorsa PostgreSQL connessione è collegata.
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
|
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() 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() 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() 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() 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
|
Nota: Questa funzione è sperimentale.
Vedere anche pg_convert()
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() 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() 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() restituisce il noe della tty a cui viene mandato l'output del debug del server sulla risorsa connessione specificata.
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()
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() 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
|
Nota: Questa funzione è sperimentale.
Vedere anche pg_convert()
Process Control support in PHP implements the Unix style of process creation, program execution, signal handling and process termination. Process Control should not be enabled within a webserver environment and unexpected results may happen if any Process Control functions are used within a webserver environment.
This documentation is intended to explain the general usage of each of the Process Control functions. For detailed information about Unix process control you are encouraged to consult your systems documentation including fork(2), waitpid(2) and signal(2) or a comprehensive reference such as Advanced Programming in the UNIX Environment by W. Richard Stevens (Addison-Wesley).
PCNTL now uses ticks as the signal handle callback mechanism, which is much faster than the previous mechanism. This change follows the same semantics as using "user ticks". You use the declare() statement to specify the locations in your program where callbacks are allowed to occur. This allows you to minimize the overhead of handling asynchronous events. In the past, compiling PHP with pcntl enabled would always incur this overhead, whether or not your script actually used pcntl.
There is one adjustment that all pcntl scripts prior to PHP 4.3.0 must make for them to work which is to either to use declare() on a section where you wish to allow callbacks or to just enable it across the entire script using the new global syntax of declare().
Nota: Questo modulo non è disponibile su piattaforme Windows.
Process Control support in PHP is not enabled by default. You have to compile the CGI or CLI version of PHP with --enable-pcntl configuration option when compiling PHP to enable Process Control support.
Nota: Currently, this module will not function on non-Unix platforms (Windows).
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
The following list of signals are supported by the Process Control functions. Please see your systems signal(7) man page for details of the default behavior of these signals.
This example forks off a daemon process with a signal handler.
Esempio 1. Process Control Example
|
The pcntl_alarm() function creates a timer that will send a SIGALRM signal to the process after seconds seconds. If seconds is zero, no new alarm is created. Any call to pcntl_alarm() will cancel any previously set alarm.
pcntl_alarm() will return the time in seconds that any previously scheduled alarm had remaining before it was to be delivered, or 0 if there was no previously scheduled alarm.
pcntl_exec() executes the program path with arguments args. path must be the path to a binary executable or a script with a valid path pointing to an executable in the shebang ( #!/usr/local/bin/perl for example) as the first line. See your system's man execve(2) page for additional information.
args is an array of argument strings passed to the program.
envs is an array of strings which are passed as environment to the program. The array is in the format of name => value, the key being the name of the environmental variable and the value being the value of that variable.
pcntl_exec() returns FALSE on error and does not return on success.
The pcntl_fork() function creates a child process that differs from the parent process only in its PID and PPID. Please see your system's fork(2) man page for specific details as to how fork works on your system.
On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and a PHP error is raised.
See also pcntl_waitpid() and pcntl_signal().
pcntl_getpriority() gets the priority of pid. If pid is not specified, the pid of the current process is used. Because priority levels can differ between system types and kernel versions, please see your system's getpriority(2) man page for specific details.
pcntl_getpriority() returns the priority of the process or FALSE on error. A lower numerical value causes more favorable scheduling.
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
pcntl_setpriority() sets the priority of pid to priority. If pid is not specified, the pid of the current process is used.
priority is generally a value in the range -20 to 20. The default priority is 0 while a lower numerical value causes more favorable scheduling. Because priority levels can differ between system types and kernel versions, please see your system's setpriority(2) man page for specific details.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The pcntl_signal() function installs a new signal handler for the signal indicated by signo. The signal handler is set to handler which may be the name of a user created function, or either of the two global constants SIG_IGN or SIG_DFL. The optional restart_syscalls specifies whether system call restarting should be used when this signal arrives and defaults to TRUE.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: The optional restart_syscalls parameter became available in PHP 4.3.0.
Nota: The ability to use an object method as a callback became available in PHP 4.3.0. Note that when you set a handler to an object method, that object's reference count is increased which makes it persist until you either change the handler to something else, or your script ends.
Esempio 1. pcntl_signal() example
|
Nota: As of PHP 4.3.0 PCNTL uses ticks as the signal handle callback mechanism, which is much faster than the previous mechanism. This change follows the same semantics as using "user ticks". You must use the declare() statement to specify the locations in your program where callbacks are allowed to occur for the signal handler to function properly (as used in the above example).
See also pcntl_fork() and pcntl_waitpid().
The wait function suspends execution of the current process until a child has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function. If a child has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed. Please see your system's wait(2) man page for specific details as to how wait works on your system.
pcntl_wait() returns the process ID of the child which exited, -1 on error or zero if WNOHANG was provided as an option (on wait3-available systems) and no child was available.
If wait3 is available on your system (mostly BSD-style systems), you can provide the optional options parameter. If this parameter is not provided, wait will be used for the system call. If wait3 is not available, providing a value for options will have no effect. The value of options is the value of zero or more of the following two constants OR'ed together:
Tabella 1. Possible values for options if wait3 is available
WNOHANG | Return immediately if no child has exited. |
WUNTRACED | Return for children which are stopped, and whose status has not been reported. |
pcntl_wait() will store status information in the status parameter which can be evaluated using the following functions: pcntl_wifexited(), pcntl_wifstopped(), pcntl_wifsignaled(), pcntl_wexitstatus(), pcntl_wtermsig() and pcntl_wstopsig().
Nota: This function is equivalent to calling pcntl_waitpid() with a -1 pid and no options.
See also pcntl_fork(), pcntl_signal(), pcntl_wifexited(), pcntl_wifstopped(), pcntl_wifsignaled(), pcntl_wexitstatus(), pcntl_wtermsig(), pcntl_wstopsig() and pcntl_waitpid().
The pcntl_waitpid() function suspends execution of the current process until a child as specified by the pid argument has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function. If a child as requested by pid has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed. Please see your system's waitpid(2) man page for specific details as to how waitpid works on your system.
pcntl_waitpid() returns the process ID of the child which exited, -1 on error or zero if WNOHANG was used and no child was available
The value of pid can be one of the following:
Tabella 1. possible values for pid
< -1 | wait for any child process whose process group ID is equal to the absolute value of pid. |
-1 | wait for any child process; this is the same behaviour that the wait function exhibits. |
0 | wait for any child process whose process group ID is equal to that of the calling process. |
> 0 | wait for the child whose process ID is equal to the value of pid. |
Nota: Specifying -1 as the pid is equivalent to the functionality pcntl_wait() provides (minus options).
pcntl_waitpid() will store status information in the status parameter which can be evaluated using the following functions: pcntl_wifexited(), pcntl_wifstopped(), pcntl_wifsignaled(), pcntl_wexitstatus(), pcntl_wtermsig() and pcntl_wstopsig().
The value of options is the value of zero or more of the following two global constants OR'ed together:
Tabella 2. possible values for options
WNOHANG | return immediately if no child has exited. |
WUNTRACED | return for children which are stopped, and whose status has not been reported. |
See also pcntl_fork(), pcntl_signal(), pcntl_wifexited(), pcntl_wifstopped(), pcntl_wifsignaled(), pcntl_wexitstatus(), pcntl_wtermsig() and pcntl_wstopsig().
Returns the return code of a terminated child. This function is only useful if pcntl_wifexited() returned TRUE.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid() and pcntl_wifexited().
Returns TRUE if the child status code represents a successful exit.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid() and pcntl_wexitstatus().
(PHP 4 >= 4.1.0, PHP 5)
pcntl_wifsignaled -- Returns TRUE if status code represents a termination due to a signalReturns TRUE if the child process exited because of a signal which was not caught.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid() and pcntl_signal().
Returns TRUE if the child process which caused the return is currently stopped; this is only possible if the call to pcntl_waitpid() was done using the option WUNTRACED.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid().
Returns the number of the signal which caused the child to stop. This function is only useful if pcntl_wifstopped() returned TRUE.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid() and pcntl_wifstopped().
Returns the number of the signal that caused the child process to terminate. This function is only useful if pcntl_wifsignaled() returned TRUE.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid(), pcntl_signal() and pcntl_wifsignaled().
Queste funzioni permettono l'esecuzione di comandi sul sistema stesso, e rendono sicuri tali comandi. Queste funzioni sono anche strettamente correlate al operatore backtick.
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:
Vedere anche exec(), popen(), system() e l'operatore backtick.
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() 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.
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.
(PHP 4 >= 4.3.0, PHP 5)
proc_close -- Close a process opened by proc_open() and return the exit code of that process.proc_close() is similar to pclose() except that it only works on processes opened by proc_open(). proc_close() waits for the process to terminate, and returns 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() fetches data about a process opened using proc_open(). The collected information is returned in an array containing the following elements:
element | type | description |
---|---|---|
command | string | The command string that was passed to proc_open() |
pid | int | process id |
running | bool | TRUE if the process is still running, FALSE if it has terminated |
signaled | bool | TRUE if the child process has been terminated by an uncaught signal. Always set to FALSE on Windows. |
stopped | bool | TRUE if the child process has been stopped by a signal. Always set to FALSE on Windows. |
exitcode | int | the exit code returned by the process (which is only meaningful if running is FALSE) |
termsig | int | the number of the signal that caused the child process to terminate its execution (only meaningful if signaled is TRUE) |
stopsig | int | 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() 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() 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.
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().
(PHP 4 , PHP 5)
shell_exec -- Esegue un comando attraverso la shell e restituisce l'output come stringasystem() è 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.
Queste funzioni sono disponibili solo nei sistemi Windows 9.x, ME, NT4 e 2000. Sono state aggiunte in PHP 4.0.4.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Parametri di configurazione per il modulo stampante
Nome | Default | Modificabile |
---|---|---|
printer.default_printer | "" | PHP_INI_ALL |
(no version information, might be only in CVS)
printer_abort -- Cancella il file di spool dalla stampanteLa funzione cancella lo spool di stampa dalla stampante.
Il parametro handle deve indicare un handle valido di stampante.
(no version information, might be only in CVS)
printer_close -- Chiude una connessione aperta verso una stampanteQuesta 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.
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.
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()
|
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().
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.
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.
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.
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.
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.
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.
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()
|
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()
|
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()
|
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()
|
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()
|
(no version information, might be only in CVS)
printer_draw_roundrect -- Traccia un rettangolo con gli angoli arrotondatiLa 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()
|
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()
|
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.
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.
(no version information, might be only in CVS)
printer_get_option -- Recupera la configurazione della stampanteLa 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.
(no version information, might be only in CVS)
printer_list -- Restituisce un elenco delle stampanti collegate al serverLa 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.
(no version information, might be only in CVS)
printer_logical_fontheight -- Restituisce l'altezza logica del fontLa funzione calcola l'altezza logica del font per il parametro altezza. Il parametro handle deve indicare un handle valido di stampante.
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.
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()
|
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()
|
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()
|
(no version information, might be only in CVS)
printer_set_option -- Configura la connessione con la stampanteLa 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.
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.
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.
These functions allow you to check the spelling of a word and offer suggestions.
To compile PHP with pspell support, you need the aspell library, available from http://aspell.sourceforge.net/.
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.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
pspell_add_to_personal() adds a word to the personal wordlist. If you used pspell_new_config() with pspell_config_personal() to open the dictionary, you can save the wordlist later with pspell_save_wordlist(). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.
pspell_add_to_session() adds a word to the wordlist associated with the current session. It is very similar to pspell_add_to_personal()
pspell_check() checks the spelling of a word and returns TRUE if the spelling is correct, FALSE if not.
pspell_clear_session() clears the current session. The current wordlist becomes blank, and, for example, if you try to save it with pspell_save_wordlist(), nothing happens.
Esempio 1. pspell_add_to_personal()
|
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/.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
pspell_config_ignore() should be used on a config before calling pspell_new_config(). This function allows short words to be skipped by the spellchecker. Words less then n characters will be skipped.
pspell_config_mode() should be used on a config before calling pspell_new_config(). This function determines how many suggestions will be returned by pspell_suggest().
The mode parameter is the mode in which spellchecker will work. There are several modes available:
PSPELL_FAST - Fast mode (least number of suggestions)
PSPELL_NORMAL - Normal mode (more suggestions)
PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)
pspell_config_personal() should be used on a config before calling pspell_new_config(). The personal wordlist will be loaded and used in addition to the standard one after you call pspell_new_config(). If the file does not exist, it will be created. The file is also the file where pspell_save_wordlist() will save personal wordlist to. The file should be writable by whoever PHP runs as (e.g. nobody). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.
pspell_config_repl() should be used on a config before calling pspell_new_config(). The replacement pairs improve the quality of the spellchecker. When a word is misspelled, and a proper suggestion was not found in the list, pspell_store_replacement() can be used to store a replacement pair and then pspell_save_wordlist() to save the wordlist along with the replacement pairs. The file should be writable by whoever PHP runs as (e.g. nobody). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.
Esempio 1. pspell_config_repl()
|
pspell_config_runtogether() should be used on a config before calling pspell_new_config(). This function determines whether run-together words will be treated as legal compounds. That is, "thecat" will be a legal compound, 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.
(PHP 4 >= 4.0.2, PHP 5)
pspell_config_save_repl -- Determine whether to save a replacement pairs list along with the wordlistpspell_config_save_repl() should be used on a config before calling pspell_new_config(). It determines whether pspell_save_wordlist() will save the replacement pairs along with the wordlist. Usually there is no need to use this function because if pspell_config_repl() is used, the replacement pairs will be saved by pspell_save_wordlist() anyway, and if it is not, the replacement pairs will not be saved. Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.
(PHP 4 >= 4.0.2, PHP 5)
pspell_new_config -- Load a new dictionary with settings based on a given configpspell_new_config() opens up a new dictionary with settings specified in a config, created with with pspell_config_create() and modified with pspell_config_*() functions. This method provides you with the most flexibility and has all the functionality provided by pspell_new() and pspell_new_personal().
The config parameter is the one returned by pspell_config_create() when the config was created.
pspell_new_personal() opens up a new dictionary with a personal wordlist and returns the dictionary link identifier for use in other pspell functions. The wordlist can be modified and saved with pspell_save_wordlist(), if desired. However, the replacement pairs are not saved. In order to save replacement pairs, you should create a config using pspell_config_create(), set the personal wordlist file with pspell_config_personal(), set the file for replacement pairs with pspell_config_repl(), and open a new dictionary with pspell_new_config().
The personal parameter specifies the file where words added to the personal list will be stored. It should be an absolute filename beginning with '/' because otherwise it will be relative to $HOME, which is "/root" for most systems, and is probably not what you want.
The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.
The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.
The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.
The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.
The mode parameter is the mode in which spellchecker will work. There are several modes available:
PSPELL_FAST - Fast mode (least number of suggestions)
PSPELL_NORMAL - Normal mode (more suggestions)
PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)
PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, 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.
For more information and examples, check out inline manual pspell website:http://aspell.net/.
pspell_new() opens up a new dictionary and returns the dictionary link identifier for use in other pspell functions.
The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.
The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.
The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.
The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.
The mode parameter is the mode in which spellchecker will work. There are several modes available:
PSPELL_FAST - Fast mode (least number of suggestions)
PSPELL_NORMAL - Normal mode (more suggestions)
PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)
PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, 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.
For more information and examples, check out inline manual pspell website:http://aspell.net/.
pspell_save_wordlist() saves the personal wordlist from the current session. The dictionary has to be open with pspell_new_personal(), and the location of files to be saved specified with pspell_config_personal() and (optionally) pspell_config_repl(). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.
Esempio 1. pspell_add_to_personal()
|
pspell_store_replacement() stores a replacement pair for a word, so that replacement can be returned by pspell_suggest() later. In order to be able to take advantage of this function, you have to use pspell_new_personal() to open the dictionary. In order to permanently save the replacement pair, you have to use pspell_config_personal() and pspell_config_repl() to set the path where to save your custom wordlists, and then use pspell_save_wordlist() for the changes to be written to disk. Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.
Esempio 1. pspell_store_replacement()
|
The readline() functions implement an interface to the GNU Readline library. These are functions that provide editable command lines. An example being the way Bash allows you to use the arrow keys to insert characters or scroll through command history. Because of the interactive nature of this library, it will be of little use for writing Web applications, but may be useful when writing scripts meant using PHP from the command line.
Nota: Questo modulo non è disponibile su piattaforme Windows.
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/.
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].
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
This function adds a line to the command line history.
This function clears the entire command line history.
This function registers a completion function. You must supply the name of an existing function which accepts a partial command line and returns an array of possible matches. This is the same kind of functionality you'd get if you hit your tab key while using Bash.
If called with no parameters, this function returns an array of values for all the setting readline uses. The elements will be indexed by the following values: done, end, erase_empty_line, library_version, line_buffer, mark, pending_input, point, prompt, readline_name, and terminal_name.
If called with one parameter, the value of that setting is returned. If called with two parameters, the setting will be changed to the given value.
This function returns an array of the entire command line history. The elements are indexed by integers starting at zero.
This function reads a command history from a file.
This function writes the command history to a file.
This function returns a single string from the user. You may specify a string with which to prompt the user. The line returned has the ending newline removed. You must add this line to the history yourself using readline_add_history().
This module contains an interface to the GNU Recode library. 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.
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.
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. |
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Recode the file referenced by file handle input into the file referenced by file handle output according to the recode request. Returns FALSE, if unable to comply, TRUE otherwise.
This function does not currently process filehandles referencing remote files (URLs). Both filehandles must refer to local files.
Recode the string string according to the recode request request. Returns the recoded string or FALSE, if unable to perform the recode request.
A simple recode request may be "lat1..iso646-de". See also the GNU Recode documentation of your installation for detailed instructions about recode requests.
La sintassi utilizzata dalle espressioni regolari di queste funzioni ricorda da vicino Perl. Le espressioni regolari devono essere racchiuse tra delimitatori, ad esempio /. Ogni carattere che non sia alfanumerico od il backslash (\) può essere usato come delimitatore. Se il carattere usato come delimitatore deve essere utilizzato all'interno dell'espressione, questo deve essere preceduto dal carattere di escape (\). Infine, a partire dalla versione 4.0.4 di PHP, si possono anche usare i delimitatori stile Perl come (), {}, [], ed <>. Per maggiori dettagli vedere Sintassi dei criteri di riconoscimento.
Il delimitatore finale può essere seguito da vari modificatori che agiscono sul criterio di riconoscimento. Per maggiori informazioni si rimanda al capitolo Modificatori di criterio (Pattern Modifiers).
Utilizzando le funzioni POSIX-esteso il PHP è in grado di supportare le espressioni regolari scritte con la sintassi POSIX-esteso.
Avvertimento |
Occorre prestare attenzione ad alcune limitazioni di PCRE. Maggiori informazioni in merito possono essere reperite alla pagina http://www.pcre.org/pcre.txt for more info. |
Il supporto delle espressioni regolari è ottenuto mediante la libreria PCRE, che è un software open source, scritto da Philip Hazel, ed il cui copyright è detenuto dalla Università di Cambridge, Inghilterra. La libreria è disponibile all'indirizzo ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/.
A partire dalla versione 4.2.0 di PHP queste funzioni sono abilitate per default. Queste funzioni possono essere disattivate usando --without-pcre-regex. Utilizzare --with-pcre-regex=DIR per specificare la directory DIR in cui sono posizionati i file di include e le librerie di PCRE, nel caso non si desideri utilizzare le librerie incluse. Nelle vecchie versioni di PHP, occorre configurare e compilare il PHP con --with-pcre-regex[=DIR] per attivare queste funzioni.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 1. Costanti di PREG
costante | descrizione |
---|---|
PREG_PATTERN_ORDER | Ordina i risultati in modo tale che $matches[0] sia l'array di tutti i testi riconosciuti, $matches[1] sia l'array delle stringhe identificate dal primo criterio posto tra parentesi, e così via. Questa costante si usa solo con preg_match_all(). |
PREG_SET_ORDER | Ordina i risultati in modo tale che $matches[0] sia l'array del primo set di testi riconosciuti, $matches[1] sia l'array del secondo set, e così via. Questa costante si usa solo con preg_match_all(). |
PREG_OFFSET_CAPTURE | Vedere la descrizione di PREG_SPLIT_OFFSET_CAPTURE. Questa costante è disponibile a partire dalla versione 4.3.0 di PHP. |
PREG_SPLIT_NO_EMPTY | Questa costante indica a preg_split() di restituire solo segmenti non vuoti. |
PREG_SPLIT_DELIM_CAPTURE | Questa costante indica a preg_split() di catturare le espressioni tra parentesi nel criterio di delimitazione. Questa costante è disponibile a partire dalla versione 4.0.5 di PHP. |
PREG_SPLIT_OFFSET_CAPTURE | Se viene impostato questo flag, per ogni testo riconosciuto viene restituito l'offset nella stringa di ricerca. Occorre notare che questo cambia il tipo di valore restituito nell'array, ogni elemento è, a sua volta, un'array composto dalla stringa riconosciuta, all'indice 0, e dall'offset della stringa nell'indice 1. Questa costante è disponibile a partire dalla versione 4.3.0 di PHP e si utilizza solo nella funzione preg_split(). |
Di seguito saranno elencati i valori attualmente previsti. I nomi posti tra parentesi si riferiscono ai corrispettivi nomi usati internamente da PCRE.
- i (PCRE_CASELESS)
Se si attiva questo modificatore, l'espressione regolare viene riconosciuta senza distinguere tra le lettere maiuscole e minuscole.
- m (PCRE_MULTILINE)
Per default, PCRE tratta il testo su cui fare la ricerca come una "singola linea" di caratteri (anche se in realtà può contenere diversi "a capo" (newline)). Il carattere di "inizio riga" (^) indica solamente l'inizio del testo passato. Analogamente il carattere di "fine riga" ($) indica la fine del testo o prima se vi sono dei caratteri di "a capo" (a meno che non sia attivato il modificatore D). In questo modo si comporta anche Perl.
Invece quando viene indicato questo modificatore, "inizio riga" e "fine riga" vengono identificati in base ai caratteri di "a capo" presenti nel testo (rispettivamente subito dopo e subito prima di questo carattere). Questo comportamento è equivalente al modificatore /m di Perl. Se nel testo passato non vi sono caratteri di "a capo" o non vi sono occorrenze dei caratteri ^ o $ nell'espressione regolare, l'uso di questo modificatore non ha effetto.
- s (PCRE_DOTALL)
Se si attiva questo modificatore, il carattere . usato nell'espressione regolare indica tutti i possibili caratteri compreso il carattere di "a capo" (newline). Senza questo modificatore il carattere "a capo" viene escluso. Questo modificare è equivalente a /s di Perl. Una espressione regolare contenente una forma negativa, come [^a], riconosce sempre un "a capo" a prescindere da questo modificatore.
- x (PCRE_EXTENDED)
Se si attiva questo modificatore, verranno ignorati gli spazi presenti nell'espressione regolare, tranne quelli preceduti dal carattere di escape (\) o posti all'interno di una classe di caratteri. Saranno, inoltre, ignorati i caratteri posti tra il simbolo # (se non è preceduto dall'escape, ed è posto al di fuori di una classe di caratteri) ed il successivo carattere di "a capo" (newline). Questo comportamento equivale al flag /x di Perl e consente di inserire dei commenti all'interno di espressioni regolari complesse. Gli spazi bianchi non devono mai comparire all'interno di sequenze speciali di caratteri, come, ad esempio, la sequenza (?( che introduce ad un criterio condizionale.
- e
Se viene specificato questo modificatore, la funzione preg_replace() valuta la stringa di sostituzione come codice PHP, quindi utilizza il risultato come testo da sostituire alle stringhe cercate.
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.
La libreria PCRE è costituita da una serie di funzioni che utilizzano come criterio di riconoscimento le espressioni regolari mutuando la stessa sintassi e la stessa semantica di Perl 5, a parte qualche lieve differenza descritta di seguito. L'attuale implementazione corrisponde alla versione 5.005 di Perl.
In questo capitolo saranno descritte le differenze rispetto a Perl 5.005.
Per default, lo spazio bianco indica tutti i caratteri riconoscibili dalla funzione isspace() della libreria C, ciò non pregiudica la possibilità di compilare PCRE con un set di caratteri alternativi. Normalmente isspace() riconosce gli spazi, il salto pagina, il carattere 'a capo' (newline), il carattere carriage return, la tabulazione orizzontale e verticale. Perl 5 non riconosce nel set dei caratteri indicati dallo "spazio bianco" la tabulazione verticale. Infatti il carattere di escape \v è stato presente per diverso tempo nella documentazione di Perl, ma di fatto non viene riconosciuto. Tuttavia lo stesso carattere viene trattato come spazio bianco fino alla versione 5.002 di Perl. Nelle versioni 5.004 e 5.005 non viene riconosciuto il carattere \s.
PCRE non supporta occorrenze ripetute in espressioni che "guardano avanti". Perl lo permette, ma non nel modo a cui si possa pensare. Ad esempio, (?!a){3}, non indica che i tre caratteri successivi non debbano essere delle "a", ma indica per tre volte che il carattere successivo non debba essere una "a".
Il riconoscimento di criteri parziali che possono verificarsi all'interno di espressioni che "guardano avanti" negative sono contati, ma i loro riferimenti non sono inseriti nel vettore degli offset. Perl valorizza le sue variabili da qualsiasi criterio che sia riconosciuto prima che l'espressione regolare fallisca nel riconoscere qualcosa, ma questo solo se l'espressione che "guarda avanti" contiene almeno un ramo alternativo.
Sebbene il carattere di 0 binario sia supportato nella stringa in cui si deve svolgere la ricerca, non è ammesso nel testo dell'espressione regolare, questo perché il testo viene passato come stringa C conclusa dal carattere zero. Si può comunque utilizzare la sequenza "\\x00" per richiedere il riconoscimento dello zero binario.
Non sono supportate le seguenti sequenze di escape di Perl: \l, \u, \L, \U, \E e \Q. Infatti queste sono implementate nelle funzioni di gestione delle stringhe di Perl e non nel suo motore di riconoscimento delle espressioni regolari.
L'asserzione di Perl \G non è supportata.
Ovviamente PCRE non supporta il costrutto (?{code}).
Al momento in cui si scrive, in Perl 5.005_02 vi sono alcune particolarità riguardanti la parametrizzazione delle stringhe catturate quando parte del criterio di riconoscimento viene ripetuto. Ad esempio, il riconoscimento di "aba" con il criterio /^(a(b)?)+$/, valorizza $2 con la lettera "b", usando il testo "aabbaa" con il criterio /^(aa(bb)?)+$/ non si ha la valorizzazione di $2. Tuttavia se il criterio di riconoscimento viene variato in /^(aa(b(b))?)+$/, sia $2 che $3 vengono valorizzate. Nelle versione 5.004 di Perl, la variabile $2 viene valorizzata in entrambi i casi, come pure è TRUE in PCRE. Se in futuro Perl cambierà nella gestione anche PCRE potrà cambiare di conseguenza.
Un'altra discrepanza non ancora risolta riguarda il criterio di riconoscimento /^(a)?(?(1)a|b)+$/, che in Perl 5.005_02 riconosce la stringa "a", mentre non accade in PCRE. Tuttavia in entrambi ( Perl e PCRE ) il riconoscimento di "a" con il criterio /^(a)?a/ non valorizza $1.
PCRE prevede alcune estensione alla gestione delle espressioni regolari di Perl:
Sebbene le asserzioni che "guardano indietro" richiedano testi di lunghezza fissa, è ammesso che ciascun ramo alternativo del criterio di ricerca possa intercettare stringhe di lunghezza differente. Al contrario Perl 5.005 richiede che tutte le stringhe abbiamo la stessa lunghezza.
Se viene settato PCRE_DOLLAR_ENDONLY e non viene attivato PCRE_MULTILINE, il meta-carattere $ indica soltanto la fine della stringa.
Se si attiva PCRE_EXTRA, un carattere backslash (\) seguito da una lettera che non abbia un significato speciale genera un errore.
Se si attiva PCRE_UNGREEDY, si inverte la "voracità" delle occorrenze, in modo da non essere voraci per default, ma lo tornano ad essere se seguiti da "?".
Di seguito verrà descritta la sintassi e la semantica delle espressioni regolari così come sono supportate da PCRE. La descrizione delle espressioni regolari può essere reperita anche nei manuali di Perl e in numerosi altri libri, alcuni dei quali ricchi di esempi. Ad esempio il libro di Jeffrey Friedl intitolato "Mastering Regular Expressions", edito da O'Reilly (ISBN 1-56592-257-3), li tratta in modo dettagliato. Questa descrizione, invece, viene intesa come una documentazione di riferimento. Una espressione regolare è un criterio utilizzato per identificare parti di un testo partendo da sinistra verso destra. La maggior parte delle lettere identifica se stessa nel testo oggetto del riconoscimento. Ad esempio il banale testo La volpe veloce intercetta la parte del testo uguale all'espressione regolare.
La potenza delle espressioni regolari deriva dalla possibilità di inserire criteri alternativi oppure ripetuti. Questi sono codificati nel criterio di ricerca tramite l'uso di meta-caratteri, lettere che non indicano se stesse, ma sono interpretate in modo particolare.
Esistono due differenti set di meta-caratteri: quelli che sono riconosciuti ovunque tranne che all'interno di parentesi quadrate, e quelli che sono riconosciuti all'interno di parentesi quadrate. I meta-caratteri che si usano all'esterno delle parentesi quadrate sono:
carattere di escape generico con diversi utilizzi
indica l'inizio del testo (o della linea in modalità multi-linea)
indica la fine del testo (o della linea in modalità multi-linea)
indica qualsiasi carattere tranne "a capo" (per default)
carattere di inizio della definizione di classe
carattere di fine della definizione di classe
inizio di un ramo alternativo
inizio di un criterio di riconoscimento parziale
fine del criterio di riconoscimento parziale
estende il significato di (, oppure 0 o 1 occorrenza, oppure occorrenza minima
0 o più occorrenze
1 o più occorrenze
inizia l'intervallo minimo/massimo di occorrenze
termina l'intervallo minimo/massimo di occorrenze
carattere di escape generico con diversi utilizzi
nega la classe, ma solo se posto all'inizio
indica un intervallo
chiude la classe di caratteri
Il carattere backslash (\) ha diversi utilizzi. Primo uso: se viene anteposto a caratteri non alfanumerici, rimuove gli eventuali significati speciali che il carattere può avere. Questo utilizzo di backslash come carattere di escape può essere svolto sia all'interno delle classi di caratteri sia all'esterno.
Ad esempio, un criterio che deve riconoscere il carattere "*" conterrà "\*". Ciò si applica indipendentemente dal carattere seguente, sia esso interpretabile come meta-carattere o meno. Nel caso in cui un carattere non alfanumerico debba identificare se stesso è opportuno farlo precedere dal "\". In particolare per identificare un backslash occorre scrivere "\\".
Se nel criterio di riconoscimento si specifica l'opzione PCRE_EXTENDED, lo spazio bianco (diversamente da quando si trova all'interno di una classe di caratteri), e i caratteri posti tra "#" e un "a capo" all'esterno di una classe di caratteri sono ignorati. Un backslash può essere usato come escape per inserire uno spazio bianco od il carattere "#" come parte del criterio di riconoscimento.
Un secondo utilizzo del backslash consiste nel codificare in modo visibile dei caratteri non visibili. Non ci sono restrizioni nella presenza di caratteri non-stampabili, a parte lo zero binario terminante la stringa dell'espressione regolare. Di seguito saranno elencate le sequenze di caratteri che è preferibile utilizzare per la loro semplicità al posto delle corrispondenti codifiche binarie.
allarme, il carattere BEL (hex 07)
"control-x", dove x è un qualsiasi carattere
escape (hex 1B)
salto pagina (hex 0C)
"a capo" (newline) (hex 0A)
carriage return (hex 0D)
tabulazione (hex 09)
carattere il cui codice esadecimale è hh
carattere il cui codice ottale è ddd, oppure riferimento all'indietro
Il preciso effetto di "\cx" è il seguente: se "x" è una lettera minuscola, viene convertita in lettera maiuscola. In pratica viene invertito il sesto bit (hex 40) del carattere. Quindi "\cz" diventa hex 1A, ma "\c{" diventa hex 3B, mentre "\c;" diventa hex 7B.
Dopo la sequenza "\x", saranno letti due numeri esadecimali (per le lettere non si distingue tra maiuscolo e minuscolo)
Dopo la sequenza "\0" saranno lette due cifre in ottale. In entrambi i casi se vi sono meno di due cifre, saranno usati i numeri presenti. Pertanto la sequenza "\0\x\07" indica 2 zeri binari seguiti dal carattere BEL. Occorre accertarsi di passare le cifre necessarie dopo lo zero iniziale se il carattere che segue può essere scambiato per una cifra in ottale.
Più complicata è la gestione del backslash seguito da una cifra diversa da 0. Al di fuori di una classe di caratteri, PCRE tratta le cifre che trova come numeri decimali. Se il numero è inferiore a 10, oppure vi sono state almeno altrettante parentesi sinistre, la sequenza viene considerata come un riferimento all'indietro. Più avanti, nella parte dei criteri parziali, sarà descritto come funzionano questi riferimenti.
All'interno di una classe di caratteri, oppure nel caso in cui il numero decimale è maggiore di 9 e non ci sono stati altrettanti criteri parziali, PCRE rilegge le prime 3 cifre seguenti il backslash in ottale e genera il carattere dagli 8 bit meno significativi del valore ottenuto. Ogni altra cifra seguente indica se stessa. Ad esempio:
è un'altro modo per indicare uno spazio
ha il medesimo significato dell'esempio precedente che non vi sono 40 sotto-criteri
è sempre un riferimento all'indietro
può essere un riferimento all'indietro o un'altro modo per indicare il carattere di tabulazione
è ancora il carattere di tabulazione
il carattere di tabulazione seguito da "3"
è il carattere con il codice ottale 113 (poiché non ci possono essere più di 99 riferimenti all'indietro)
è un byte con tutti i bit a 1
può essere un riferimento all'indietro o uno zero binario seguito da "8" e da "1"
Occorre rilevare che valori ottali maggiori di 100 non devono essere preceduti dallo zero, questo perché la libreria considera solo tre cifre.
Tutte le sequenze che definiscono il valore di un singolo byte possono essere utilizzate sia all'interno sia all'esterno delle classe di caratteri. Inoltre, all'interno delle classi di caratteri, la sequenza "\b" viene interpretata come carattere di backspace (hex 08), mentre all'esterno ha un'altro significato (come descritto più avanti).
Il terzo utilizzo possibile per il backslash consiste nello specificare il tipo di carattere:
qualsiasi cifra decimale
qualsiasi carattere che non sia una cifra decimale
qualsiasi carattere identificato come spazio bianco
qualsiasi carattere che non sia identificato come spazio bianco
qualsiasi carattere che sia una "parola" (word)
qualsiasi carattere che non sia una "parola" (word)
Ciascuna coppia di sequenze di escape suddivide il set completo dei caratteri in due insiemi disgiunti. Un dato carattere deve essere identificato da un solo insieme di ciascuna coppia.
I caratteri definiti "parole" sono quelle lettere o cifre o il carattere underscore (_), cioè qualsiasi carattere che possa essere parte di una "parola" in Perl. In PCRE le definizioni di lettere e cifre vengono gestite tramite le tabelle dei caratteri, che possono variare in base a specifici parametri di localizzazione (vedere il paragrafo intitolato "Supporto alle localizzazioni"). Ad esempio, nella localizzazione fr (relativa alla Francia), qualche codice carattere maggiore di 128 è utilizzato per le lettere accentate, e queste sono identificate tramite la sequenza \w.
Queste sequenze di tipi di caratteri possono apparire sia all'interno sia all'esterno delle classi di caratteri. Ciascuna di esse identifica un carattere del tipo appropriato. Se durante la fase di identificazione di un testo, si giunge al termine della stringa in cui si esegue il riconoscimento e si hanno ancora di queste sequenze da incrociare, l'operazione di identificazione fallirà perché, ovviamente, non vi sono più caratteri in cui riconoscere le suddette sequenze.
Il quarto utilizzo per il backslash riguarda la costruzione di particolari asserzioni. L'asserzione è una condizione che deve essere soddisfatta ad un certo punto del riconoscimento, senza "consumare" caratteri dalla stringa oggetto del riconoscimento. Più avanti verranno descritte asserzioni più complicate, costruite tramite l'uso di sotto-criteri di riconoscimento, per ora saranno illustrate delle semplici asserzioni costruite con il backslash:
limite di una parola
non limite di una parola
inizio dell'oggetto di ricerca (a prescindere dalla modalità multi-linea)
fine dell'oggetto di ricerca oppure newline alla fine (a prescindere dalla modalità multi-linea)
fine dell'oggetto di ricerca (a prescindere dalla modalità multi-linea)
Queste asserzioni non possono apparire all'interno di una classe di caratteri (attenzione che la sequenza "\b" all'interno di una classe di caratteri indica il carattere backspace).
Viene definito limite di una parola la posizione nella stringa oggetto della ricerca, nella quale il carattere corrente ed il carattere precedente non soddisfano la sequenza \w o la sequenza \W (ad esempio uno soddisfa la sequenza \w e l'altro carattere soddisfa la sequenza \W), oppure quella posizione, all'inizio o alla fine della stringa, nella quale rispettivamente il primo o l'ultimo carattere soddisfa la sequenza \w.
Le asserzioni \A, \Z e \z differiscono dai tradizionali caratteri "^" e "$" (descritti di seguito) per il fatto di identificare sempre l'inizio o la fine della stringa oggetto di ricerca a prescindere da quale opzione sia stata attivata. Infatti queste asserzioni non sono alterate da PCRE_MULTILINE oppure da PCRE_DOLLAR_ENDONLY. La differenza tra \Z e \z consiste nel fatto che \Z identifica sia il carattere precedente il newline posto al termine della stringa sia la fine della stringa, mentre \z identifica solo la fine.
In condizioni normali, il carattere "^", posto all'esterno di una classe di caratteri, indica un asserzione che è vera soltanto se il punto da cui si inizia a identificare il testo si trova all'inizio della stringa oggetto della ricerca. Al contrario, se il carattere "^" si trova all'interno di una classe di caratteri, assume altri significati (vedere i capitoli seguenti).
Non è necessario che il carattere "^" sia la prima lettera del criterio di riconoscimento nei casi in cui si utilizzino dei criteri di riconoscimento alternativi. Tuttavia è necessario che sia la prima lettera nei rami alternativi in cui compare. Se si inserisce il carattere "^" in tutte le alternative, caso che ricorre quando si vuole riconoscere un testo a partire dall'inizio della stringa, si dice che si è costruito un criterio di ricerca "ancorato". (Esistono anche altre costruzioni che portano all'ancoraggio di un criterio di ricerca).
Il carattere dollaro "$" è una asserzione che è TRUE soltanto se il punto a cui si è arrivati ad identificare il testo si trova alla fine della stringa oggetto della ricerca, o nella lettera immediatamente precedente il carattere di "a capo", che (per default) è l'ultimo carattere del testo. Il dollaro "$" non deve essere necessariamente l'ultima lettera di un criterio di riconoscimento se in questo si sono utilizzati dei criteri alternativi. Deve, comunque, essere l'ultima lettera nei criteri ove compare. Il carattere dollaro "$" non ha significati speciali all'interno di una classe di caratteri.
Il comportamento del simbolo "$" può essere variato in modo da identificare la reale fine della stringa oggetto di ricerca attivando il flag PCRE_DOLLAR_ENDONLY durante la compila o durante la fase di riconoscimento. Ciò non influisce sull'asserzione \Z.
Il comportamento dei simboli "^" e "$" può essere influenzato dall'opzione PCRE_MULTILINE. Quando viene attivata, questi caratteri identificano rispettivamente, oltre ai tradizionali inizio e fine testo, la lettera immediatamente successiva ed immediatamente precedente il carattere "\n" presente all'interno della stringa oggetto di ricerca. Per esempio il criterio /^abc$/ riconosce il testo "def\nabc" solo in modalità multi-linea. Di conseguenza i criteri di riconoscimento che sono "ancorati" in modalità singola linea, non lo sono in modalità multi-linea. L'opzione PCRE_DOLLAR_ENDONLY viene ignorata se si attiva il flag PCRE_MULTILINE .
Occorre rilevare che le sequenze \A, \Z e \z possono essere utilizzate per riconoscere l'inizio e la fine del testo in entrambe le modalità, e, se tutti i criteri alternativi iniziano con \A, si ha ancora un criterio "ancorato" a prescindere che sia attivata o meno l'opzione PCRE_MULTILINE.
Il carattere punto ".", all'esterno di una classe di caratteri, identifica qualsiasi carattere, anche quelli non stampabili, ma (per default) non il carattere "a capo". Invece se si abilita l'opzione PCRE_DOTALL si avrà anche il riconoscimento del carattere "a capo". La gestione del simbolo "." è svincolata dalla gestione dei simboli "^" ed "$", l'unica relazione che possono avere riguarda il carattere "a capo". Il punto "." non ha significati speciali all'interno delle classi di caratteri.
Un parentesi quadrata aperta "[" inizia una classe di caratteri; una parentesi quadrata chiusa "]" termina la definizione della classe. Di suo il carattere di parentesi quadrata chiusa non ha significati speciali. Se occorre inserire la parentesi chiusa all'interno di una classe di caratteri, questa deve essere la prima lettera (ovviamente deve seguire il carattere "^", se presente) oppure deve essere preceduta dal carattere di escape "\".
Una classe di caratteri identifica un singolo carattere nella stringa oggetto di ricerca; il carattere deve comparire nel set di caratteri definito dalla classe, a meno che il primo carattere della classe non sia l'accento circonflesso "^", in tal caso il carattere non deve essere nel set definito dalla classe. Se è richiesto l'inserimento del carattere "^" nel set definito dalla classe, questo non deve essere la prima lettera dopo la parentesi di apertura, oppure deve essere preceduto dal carattere di escape (\).
Ad esempio, la classe [aeiou] identifica ogni vocale minuscola, mentre [^aeiou] identifica tutti i caratteri che non siano delle vocali minuscole. Occorre notare che il simbolo "^" è un modo pratico per indicare i caratteri che sono nella classe, citando quelli che non lo sono. Questa non è una asserzione: consuma un carattere della stringa oggetto di ricerca e fallisce se ci si trova alla fine del testo.
In un riconoscimento senza distinzione tra minuscole e maiuscole, ogni lettera della classe identifica sia la versione maiuscola sia la minuscola. Così, ad esempio, la classe [aeiou] identifica sia "A" sia "a", e, in questo caso, [^aeiou] non identifica "A", mentre con la distinzione delle maiuscole [^aeiou] identifica la lettera "A".
Il carattere di "a capo" (newline) non viene trattato in modo speciale nelle classi di caratteri, indipendentemente dalle opzioni PCRE_DOTALL o PCRE_MULTILINE. La classe [^a] riconosce sempre il carattere "a capo".
Il segno meno (-) può essere usato per definire un intervallo all'interno della classe. Ad esempio, [d-m] identifica ogni lettera compresa tra d ed m inclusi. Se occorre inserire il segno meno (-) come carattere da riconoscere o lo si fa precedere dal carattere di escape (\), oppure lo si mette in una posizione tale che non possa essere identificato come definizione di un intervallo (ad esempio all'inizio o alla fine della definizione della classe).
Non è possibile usare il carattere "]" come limite di un intervallo. Un criterio definito come [W-]46], viene inteso come una classe di due caratteri (W e -) seguita dalla stringa 46], in tal modo sarebbero riconosciuti i testi "W46]" oppure "-46]". Quindi è necessario precedere la lettera "]" con il carattere di escape (\), in questo modo [W-\]46], viene interpretata correttamente come una singola classe contenente un range seguito da due caratteri separati. In alternativa, per delimitare l'intervallo si può utilizzare la notazione ottale di "]".
Gli intervalli utilizzano la sequenza di caratteri ASCII. Inoltre possono essere utilizzati per definire caratteri con specifica numerica (ad esempio [\000-\037]). Nei casi in cui si abiliti il riconoscimento senza distinzione tra lettere maiuscole e minuscole, gli intervalli comprendenti lettere identificano sia la lettera maiuscola che minuscola. Ad esempio, [W-c] è equivalente ad [][\^_`wxyzabc] (con il riconoscimento a prescindere dalla lettera maiuscole e minuscole), e, se si utilizza la tabella dei caratteri locali francesi "fr", [\xc8-\xcb] identifica la lettera "e" accentata sia maiuscola sia minuscola.
Nelle classi di caratteri si possono utilizzare le sequenze \d, \D, \s, \S, \w e \W per aggiungere altri tipi di caratteri alla classe. Ad esempio, [\dABCDEF] riconosce qualsiasi cifra esadecimale. Il carattere "^" può essere utilizzato con i caratteri maiuscoli per indicare un set di caratteri più ristretto che l'identificazione del set di caratteri minuscoli. Ad esempio, la classe [^\W_] identifica qualsiasi lettera o cifra ma non il trattino basso (_).
Tutti i caratteri non alfabetici, eccetto \, -, ^ (posto all'inizio) e ] non sono speciali per la classi di caratteri, e non sono dannosi se preceduti dal caratteri di escape (\).
La barra verticale (|) viene utilizzata per separare criteri di riconoscimento alternativi. Ad esempio il seguente criterio gilbert|sullivan può riconoscere "gilbert" oppure "sullivan". Ci possono essere innumerevoli alternative, compresa un'alternativa vuota (per identificare una stringa vuota). Il processo di riconoscimento prova tutte le alternative possibili (da sinistra a destra) fino a quando non ne trova una che sia soddisfatta. Se le alternative sono nella definizione di un criterio parziale il riconoscimento ha successo quando avviene su tutto il criterio.
Le opzioni PCRE_CASELESS, PCRE_MULTILINE , PCRE_DOTALL e PCRE_EXTENDED possono essere cambiate "al volo" dall'interno del criterio di riconoscimento, utilizzando le sequenze di lettere definite per queste opzioni in Perl, racchiuse tra "(?" ed ")". Le lettere utilizzabili sono:
Tabella 1. Lettere per le opzioni interne
i | per PCRE_CASELESS |
m | per PCRE_MULTILINE |
s | per PCRE_DOTALL |
x | per PCRE_EXTENDED |
Ad esempio, (?im) abilita il riconoscimento senza distinzione tra lettere maiuscole e minuscole e la modalità multi-linea. E' anche possibile disabilitare queste opzioni facendo precedere la lettera dal segno meno (-), o combinare l'attivazione con la disattivazione come nel caso (?im-sx), in cui si attiva PCRE_CASELESS e PCRE_MULTILINE e si disattiva PCRE_DOTALL e PCRE_EXTENDED. Se la lettera compare sia prima che dopo il segno meno (-) l'opzione resta disabilitata.
L'ambito di validità delle opzioni dipende da dove sono i flag di abilitazione/disabilitazione nel criterio di ricerca. Nei casi in cui il settaggio di un'opzione avvenga all'esterno di un qualsiasi criterio parziale (come definito in seguito) gli effetti sono medesimi di quando l'attivazione/disattivazione avviene all'inizio del criterio di riconoscimento. Gli esempi seguenti si comportano tutti allo stesso modo:
(?i)abc
a(?i)bc
ab(?i)c
abc(?i)
In questi esempi si attiva PCRE_CASELESS per il criterio "abc". In altre parole, questo settaggio compiuto al primo livello si applica a tutto il criterio (a meno che non vi siano altre variazioni nelle sotto-regole di riconoscimento). Qualora vi siano più settaggi per lo stesso parametro, viene utilizzato quello più a destra.
Se si inserisce la variazione di un'opzione in una sotto-regola gli effetti sono differenti. Questa è una variazione rispetto al comportamento di Perl 5.005. Una variazione apportata all'interno di una sotto-regola, vale solo per la parte della sotto-regola che segue la variazione, pertanto (a(?i)b)c identifica abc, aBc e nessuna altra stringa ( si assume che PCRE_CASELESS non sia usato). Da ciò deriva che le opzioni possono avere comportamenti differenti nelle varie parti del criterio di riconoscimento. Ogni variazione apportata ad una ramo alternativo del criterio viene estesa alle alternative successive della medesima sotto-regola. Ad esempio, (a(?i)b|c) identifica "ab", "aB", "c" e "C", anche se per identificare "C" viene scartato il primo ramo prima di incontrare il settaggio dell'opzione. Questo accade perché gli effetti dei settaggi vengono inseriti nella fase di compila. Diversamente si avrebbero dei comportamenti molto bizzarri.
Le opzioni specifiche di PCRE PCRE_UNGREEDY e PCRE_EXTRA possono essere variate nel medesimo modo delle opzioni Perl compatibili, utilizzando rispettivamente i caratteri U e X. Il flag (?X) è particolare poiché deve comparire prima di qualsiasi opzione esso attivi anche quando si trova al primo livello. E' opportuno inserirlo all'inizio.
Le sotto-regole sono delimitate dalle parentesi tonde e possono essere annidate. La definizione di una parte di una regola di riconoscimento come sotto-regola può servire a:
1. Localizzare un set di alternative. Ad esempio nel seguente criterio di riconoscimento cat(aract|erpillar|) si riconosce una tra le parole "cat", "cataract" oppure "caterpil- lar". Se non fossero state usate le parentesi, il criterio avrebbe permesso il riconoscimento delle parole "cataract", "erpillar" oppure una stringa vuota.
2. Identificare e catturare parte del testo riconosciuto dalla sotto-regola (come illustrato in seguito). Quando il riconoscimento dell'intero criterio ha avuto successo, le porzioni della stringa oggetto della ricerca identificate dalle sotto-regole sono restituite alla funzione chiamante tramite l'argomento vettore della funzione pcre_exec(). Per determinare il numero ordinale di ciascuna sotto-regola si contano le parentesi aperte da sinistra verso destra partendo da 1.
Ad esempio, se si esegue un riconoscimento nella frase "the red king" con il seguente criterio the ((red|white) (king|queen)) si ottengono i testi "red king", "red" e "king", rispettivamente identificati dalla sotto-regola 1, 2 e 3.
Il fatto che le parentesi tonde adempiano a due funzioni non sempre porta a situazioni comprensibili. Spesso capita di dovere raggruppare delle sotto-regole senza per questo essere richiesta la cattura del testo. A tale scopo l'uso della sequenza "?:" dopo la parentesi di apertura permette di indicare che questa sotto-regola non deve catturare il testo, e non deve essere conteggiata nel numero d'ordine delle sotto-regole di cattura. Ad esempio, applicando il criterio the ((?:red|white) (king|queen)) alla frase "the white queen", si catturano i testi "white queen" e "queen", rispettivamente numerati 1 e 2. Il numero massimo di testi catturabili è 99, il numero massimo di sotto-regole, a prescindere che siano di cattura o meno, è 200.
Come utile abbreviazione, nei casi in cui l'attivazione di alcune opzioni debba essere fatta all'inizio di una sotto-regola non di cattura, la lettera dell'opzione può comparire tra la "?" e ":". Pertanto i due criteri
(?i:saturday|sunday)
(?:(?i)saturday|sunday)
riconoscono esattamente lo stesso set di parole. Poiché i rami alternativi sono provati da sinistra verso destra, e le opzioni non sono azzerate fino a quando non si è conclusa la sotto-regola, una opzione attivata in un ramo alternativo si applica a tutte le alternative che seguono. Pertanto, nell'esempio di prima, sia la parola "SUNDAY" che la parola "Saturday" sono testi identificati correttamente.
Le ripetizioni sono il numero delle occorrenze che possono essere indicate dopo i seguenti elementi:
un singolo carattere, possibilmente preceduto dal carattere di escape (\)
il metacarattere .
una classe di caratteri
un riferimento all'indietro (vedere la sezione successiva)
una sotto-regola (a meno che non si tratti di una asserzione - vedere più avanti)
In generale una occorrenza specifica un numero minimo e massimo di riconoscimenti previsti tramite la specifica dei due limiti, posti tra parentesi graffe e separati da una virgola. Entrambi i numeri devono essere minori di 65536 ed il primo deve essere minore o uguale rispetto al secondo. Ad esempio: z{2,4} identifica "zz", "zzz" oppure "zzzz". La parentesi graffa chiusa di suo non rappresenta un carattere speciale. Se si omette il secondo numero, ma si lascia la virgola, non si indica un limite superiore; se sia la virgola sia il secondo numero sono omessi, l'occorrenza specifica l'esatto numero di riconoscimenti richiesti. Il criterio [aeiou]{3,} identifica almeno 3 o più vocali consecutive, mentre \d{8} identifica esattamente 8 cifre. Una parentesi graffa aperta che compaia in una posizione in cui non sia prevista una occorrenza, o che comunque non sia riconducibile alla sintassi di una occorrenza, viene tratta come il carattere "{". Ad esempio {,6} non indica delle occorrenze, ma una stringa di 4 caratteri.
L'indicazione {0} è permessa. Indica di comportarsi come se l'elemento precedente all'occorrenza non fosse presente.
Per praticità (e compatibilità verso il passato) si usano 3 abbreviazioni per le occorrenze più comuni:
E' anche possibile creare un ciclo infinito facendo seguire ad una sotto-regola che non identifica alcun carattere una occorrenza priva di limite superiore. Ad esempio: (a?)*
Le versioni precedenti di Perl e di PCRE segnalavano un errore durante la fase di compila per questi criteri. Tuttavia, poiché vi sono casi dove questi criteri possono essere utili, queste regole sono accettate, ma, se la ripetizione non riconosce alcun carattere, il ciclo viene interrotto.
Per default le occorrenze sono "bramose", infatti identificano più testi possibile (fino al numero massimo permesso), senza per questo fare fallire il riconoscimento della parte rimanente del criterio di ricerca. Il classico esempio dove questo comportamento può essere un problema, riguarda il riconoscimento dei commenti nei programmi C. Questi compaiono tra le sequenze /* ed */, ma all'interno, nel commento, si possono usare sia il carattere *, sia il carattere /. Il tentativo di individuare i commenti C con il seguente criterio /\*.*\*/ se applicato al commento /* primo commento */ nessun commento /* secondo commento */ non ha successo, perché identifica l'intera stringa a causa della "bramosia" dell'elemento ".*".
Tuttavia, se un'occorrenza è seguita da un punto interrogativo, questa cessa di essere "bramosa", e identifica il numero minimo di testi permessi. Pertanto il criterio /\*.*?\*/ si comporta correttamente con i commenti C. Il significato delle varie occorrenze non è stato cambiato, si è soltanto modificato il numero delle occorrenze da riconoscere. Attenzione a non confondere questo uso del punto interrogativo con il suo proprio significato. Dati i due utilizzi del ?, può anche capitare di averli entrambi come in \d??\d che, preferibilmente, identifica una cifra, ma può riconoscerne due se questa è l'unica via per soddisfare il riconoscimento dell'intero criterio.
Se si attiva l'opzione PCRE_UNGREEDY (un'opzione disponibile anche in Perl), per default le occorrenze non sono "bramose", ma ogni singola occorrenza può essere resa "bramosa" se seguita dal punto interrogativo. In altre parole si è invertito il normale comportamento.
Quando si indica un numero minimo di occorrenze maggiore di 1, per una sotto-regola posta tra parentesi, oppure si indica un numero massimo di occorrenze, la fase di compila richiede più spazio in proporzione ai valori minimo e massimo.
Se un criterio inizia con .* oppure .{0,} e si è attivata l'opzione PCRE_DOTALL (equivalente al /s di Perl), permettendo al . di identificare il carattere di "a capo", si dice che il criterio è implicitamente ancorato, perché qualsiasi elemento che segue sarà confrontato con ciascun carattere della stringa oggetto della ricerca, e pertanto non vi è nessuna posizione, a parte la prima, da cui ripartire per ritentare il riconoscimento dell'intero criterio. PCRE tratta tale criterio come se fosse preceduto dalla sequenza \A. Nei casi in cui è noto a priori che la stringa oggetto di ricerca non contiene caratteri di "a capo", vale la pena di attivare l'opzione PCRE_DOTALL se il criterio di ricerca inizia con ".*", per ottenere questa ottimizzazione, oppure, in alternativa, usare "^" per indicare in modo esplicito un ancoraggio.
Quando si ripete una sotto-regola di cattura, il testo estrapolato è la parte identificata dall'iterazione finale. Ad esempio se il criterio (tweedle[dume]{3}\s*)+ viene applicato al testo "tweedledum tweedledee", il testo estrapolato sarà "tweedledee". Tuttavia se vi sono delle sotto-regole annidate, il testo catturato può essere determinato dalle iterazioni precedenti. Ad esempio nel criterio /(a|(b))+/ applicato a "aba", la seconda stringa catturata è "b".
Esternamente ad una classe di caratteri, un backslah (\) seguito da una o più cifre maggiori di 0 è un riferimento all'indietro verso testi catturati precedentemente (ad esempio alla sinistra rispetto a dove ci si trova), conteggiati tramite il numero delle parentesi chiuse precedenti.
Tuttavia, se il numero che segue il backslash (\) è un valore inferiore a 10, si assume che si tratti sempre di un riferimento all'indietro, e pertanto viene generato un errore se nel criterio non vi sono almeno altrettante parentesi chiuse di sotto-regole di cattura. In altre parole per i numeri inferiori a 10 non è necessario che il numero parentesi precedenti (a sinistra) alla sotto-regola sia pari o maggiore al numero indicato. Vedere la sezione relativa al backslash per informazioni su come gestire le cifre seguenti il backslash.
Un riferimento all'indietro identifica ciò che è già stato catturato dalla sotto-regola, e non ciò che la sotto-regola stessa possa riconoscere. Ad esempio il criterio (sens|respons)e and \1ibility può riconoscere "sense and sensibility" oppure "response and responsibility", ma non il testo "sense and responsibility". Se al momento del riferimento all'indietro, è attiva la distinzione tra lettere maiuscole e minuscole, il formato della lettera diventa rilevante. Ad esempio, ((?i)rah)\s+\1 può identificare "rah rah" e "RAH RAH", ma non "RAH rah", anche se la sotto-regola originale eseguiva dei riconoscimenti a prescindere dalle lettere maiuscole e minuscole.
Nella medesima sotto-regola si possono avere più di un riferimento all'indietro. Se una sotto-regola non viene utilizzata in un particolare riconoscimento, un riferimento a questa ha sempre esito negativo. Ad esempio il criterio (a|(bc))\2 non avrà mai successo se l'identificazione della stringa inizia con "a" e non con "bc". Dato che sono possibili fino a 99 riferimenti all'indietro, tutte le cifre che seguono un backslash (\) sono considerate come parte di un potenziale numero di riferimento. Se il criterio continua con altri caratteri numerici, occorre stabilire un carattere per delimitare il numero del riferimento. Se si attiva l'opzione PCRE_EXTENDED questo carattere può essere lo spazio. Altrimenti si può usare un commento vuoto.
Un riferimento all'indietro non ha successo se viene inserito in una sotto regola prima che sia applicata. Con questo si intende, ad esempio, che (a\1) non avrà mai successo, ma, nel caso di una sottoregola ripetuta, si avrà un riscontro positivo. Ad esempio (a|b\1)+ identificherà qualsiasi numero di "a", ma anche "aba" oppure "ababaa" eccetera. In pratica a ciascuna iterazione della sotto-regola il riferimento andrà a sostituire la stringa riconosciuta tramite la sotto-regola dell'iterazione precedente. Affinchè il tutto funzioni, è necessario che la prima iterazione sia identificata senza l'ausilio del riferimento "all'indietro". Ciò può essere ottenuto o usando casi alternativi, come nell'esempio precedente, o usando le occorrenze indicando come numero minimo di occorrenze il valore zero.
L'asserzione è un test basato su un carattere, che può precedere o seguire l'attuale punto di riconoscimento, e non consuma alcun carattere. Le semplici asserzioni quali \b, \B, \A, \Z, \z, ^ e $ sono state descritte precedentemente. Asserzioni più complesse possono essere strutturate come delle sotto-regole. Se ne hanno di due tipologie: quelle che "guardano avanti" alla posizione attuale nella stringa oggetto del riconoscimento, e quelle che "guardano dietro" la posizione attuale.
Una asserzione definita come sotto-regola esegue il riconoscimento nel modo usuale, ma tale riconoscimento non sposta la posizione attuale nella stringa. Le asserzioni che "guardano avanti" cominciano per "(?=", se sono positive, per "(?!", se sono asserzioni negative. Ad esempio \w+(?=;) riconosce una parola seguita da ";", ma non include il punto e virgola nel riconoscimento, mentre foo(?!bar) identifica qualsiasi occorrenza di "foo" che non sia seguita da "bar". Attenzione che il criterio, apparentemente simile, (?!foo)bar non riconosce alcuna occorrenza di "bar" se questa è preceduta da qualsiasi testo che non sia "foo"; infatti l'espressione riconosce qualsiasi occorrenza di "bar", poiché l'asserzione (?!foo) è sempre TRUE quando i tre caratteri successivi sono "bar". Pertanto è necessario una asserzione che "guarda" all'indietro per ottenere effetto desiderato.
Le asserzioni che "guardano" indietro positive iniziano con "(?<=", e con "(?<!" le negative. Ad esempio: (?<!foo)bar riconosce una occorrenza di "bar" che non sia preceduta da "foo". Le asserzioni che "guardano" indietro hanno una limitazione: tutte le stringhe che riconoscono devono avere lunghezza fissa. Mentre, se si hanno casi alternativi, la limitazione della lunghezza fissa non sussiste. Quindi (?<=bullock|donkey) è una asserzione permessa, ma (?<!dogs?|cats?) genera un errore durante la fase di compila. Rami alternativi con lunghezze di stringa differenti sono permessi solo al primo livello dell'asserzione. Questa è da considerarsi una estensione rispetto a Perl 5.005, che richiede a tutte le alternative possibili la medesima lunghezza di stringa. Quindi una asserzione tipo (?<=ab(c|de)) non è permessa, poiché il suo singolo ramo di primo livello può identificare testi di due lunghezze differenti, ma è accettabile se riscritta usando due alternative di primo livello: (?<=abc|abde) L'implementazione di questo tipo di asserzioni consiste, per ciascuna alternativa, di uno spostamento all'indietro temporaneo per la lunghezza fissa necessaria, e ad un tentativo di riconoscimento del testo. Se non ci sono sufficienti caratteri precedenti alla posizione attuale, l'asserzione è destinata a fallire. L'uso accoppiato delle asserzioni che "guardano" indietro con sotto-regole a riconoscimento singolo può essere utile per identificare la fine dei testi; un esempio è illustrato al termine della sezione sulle sotto-regole a riconoscimento singolo.
Diverse asserzioni (di qualsiasi tipologia) possono essere utilizzate in modo consecutivo. Ad esempio: (?<=\d{3})(?<!999)foo riconosce "foo" preceduto da tre cifre che non siano "999". Occorre rilevare che ciascuna asserzione viene applicata singolarmente sul medesimo punto nella stringa oggetto di riconoscimento. Nell'esempio precedente per prima cosa si verifica che i tre caratteri precedenti siano cifre, quindi che non siamo "999". Questo esempio non identifica il testo se "foo" è preceduto da sei caratteri di cui i primi tre siano cifre e i secondi tre non siano "999". In pratica il testo "123abcfoo" non viene riconosciuto. Un criterio per riconoscere tale stringa può essere: (?<=\d{3}...)(?<!999)foo
In questo caso la prima asserzione controlla i primi sei caratteri verificando che i primi tre siano cifre, mentre la seconda asserzione verifica che i secondi tre caratteri non siano "999".
Le asserzioni possono essere annidate in qualsiasi combinazione. Il seguente esempio (?<=(?<!foo)bar)baz identifica il testo "baz" se è preceduto da "bar" il quale non deve essere preceduto da "foo", mentre (?<=\d{3}(?!999)...)foo è un'altro criterio che riconosce "foo" preceduto da tre cifre e da tre caratteri che non siano "999".
Le asserzioni definite come sotto-regole non catturano parte del testo e non possono essere ripetute (non avrebbe senso ripetere il medesimo riconoscimento sul medesimo testo). Se una di queste asserzioni contiene una sotto-regola di cattura questa viene conteggiata ai fini della numerazione delle regole di cattura. Tuttavia il testo viene effettivamente catturato solo nelle asserzioni positive, dato che non avrebbe senso farlo in quelle negative.
Le asserzioni possono essere composte fino ad un massimo di 200 sotto-regole. subpatterns.
Con l'indicazione del numero minimo e massimo di ripetizioni, il fallimento del riconoscimento della parte successiva del testo causa una ripetizione dell'identificazione con un numero di occorrenze diverse per verificare se in questa situazione anche il resto del testo viene identificato. In alcune situazioni può essere utile bloccare questo meccanismo, per la cambiata natura del criterio, oppure per fare fallire la ricerca prima di quando potrebbe accadere, oppure quando l'autore sa che non ci sono punti da cui ripartire.
Consideriamo, ad esempio, il criterio \d+foo applicato alla seguente linea 123456bar
Dopo avere identificato le 6 cifre ed avere mancato nel riconoscimento di "foo", il comportamento normale consiste nel tentare di procedere identificando 5 cifre per l'elemento \d+, quindi tentare con 4 e così via, prima di fallire definitivamente. Le sotto-regole a riconoscimento singolo permettono di specificare che, una volta riconosciuta una porzione della regola, questa non debba essere più considerata, in maniera tale da abortire immediatamente il riconoscimento se non si ha successo nell'identificare la parte restante del criterio. L'espressione per definire questo tipo di sotto-regola richiede un'altro tipologia di utilizzo speciale delle parentesi. Infatti iniziano con (?> come nell'esempio seguente: (?>\d+)bar
Questa tipologia di parentesi "inchioda" la parte di criterio una volta che avviene il riconoscimento, e, quindi, un fallimento successivo impedisce la ri-elaborazione di questo segmento. Tuttavia, occorre notare che gli elementi precedenti a questo si comportano in modo normale, e pertanto la ri-elaborazione, pur non toccando questo elemento, passa ai precedenti.
Una descrizione alternativa di questa tipologia di sotto-regola potrebbe essere che questo criterio identifica un testo come avrebbe fatto un singolo criterio se fosse stato ancorato alla posizione corrente.
Le sotto-regole a riconoscimento singolo non compiono la cattura del testo identificato. I casi semplici illustrati in precedenza possono essere considerati come una estremizzazione della ripetizione che porta ad inglobare tutto ciò che può. Pertanto, da una parte \d+ e \d+? sono sequenze che si adattano a riconoscere il numero corretto di cifre affinchè la ricerca abbia successo, dall'altra la sequenza (?>\d+) riconosce soltanto una sequenza di cifre.
Ovviamente queste costruzioni possono contenere diverse sotto-regole sia complesse, sia annidate.
Le sotto-regole a riconoscimento singolo possono essere usate congiuntamente alle asserzioni che guardano indietro, per definire una regola efficiente per riconoscere la fine della stringa. Ad esempio si consideri questo semplice criterio: abcd$ quando viene applicato ad un lungo testo può non avere successo. Questo perché il riconoscimento procede da sinistra verso destra, quindi PCRE prima cerca la "a", e poi cerca di riconoscere la parte restante del criterio. Se si modifica il criterio nel seguente modo ^.*abcd$ allora la sequenza iniziale .* in prima battuta identificherà tutto il testo, ma quando fallisce (poiché non vi sono più "a"), la ricerca tornerà indietro di uno (quindi tutto il testo tranne l'ultimo carattere), quindi, se continua non esserci la "a", si torna indietro di due, e così via. Continuando a tornare indietro alla ricerca della "a" si percorre tutto il testo da destra a sinistra, senza ottenere nulla di valido. Tuttavia se si riscrive il criterio come: ^(?>.*)(?<=abcd) non si attiva più lo scorrimento verso sinistra per .* , ma viene costretto a riconoscere tutto il testo (esito del primo tentativo). La asserzione successiva, esegue una verifica sulle ultime 4 lettere.Se fallisce, ciò avviene immediatamente, provocando un impatto sensibile nei tempi di elaborazione con testi molto lunghi.
Quando un criterio di riconoscimento contiene un elemento ripetuto senza limite all'interno di una sotto-regola che anch'essa possa ripetuta illimitatamente, l'uso delle sotto-regole a riconoscimento singolo è l'unico mezzo per evitare che certi mancati riconoscimenti richiedano molto tempo per essere rilevati. Ad esempio il criterio (\D+|<\d+>)*[!?] riconosce un numero indefinito di frammenti di testo contenenti a loro volta numeri o caratteri non numerici racchiusi tra <>, seguiti dai caratteri ! o ?. Quando il riconoscimento ha successo l'esecuzione è rapida, ma quando viene applicato al testo aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa richiede molto tempo prima di evidenziare l'errore. Questo accade perché la stringa può essere suddivisa tra i due elementi ripetuti in un elevato numero di modi che debbono essere verificati. Nell'esempio si usa [!?] piuttosto che un singolo carattere alla fine, questo perché sia Perl sia PCRE hanno una ottimizzazione che permette un veloce riconoscimento dell'errore se si usa un solo carattere. Infatti memorizzano l'ultimo carattere singolo richiesto per un riconoscimento, e, se non lo trovano nel testo, falliscono subito. Se il criterio viene modificato in ((?>\D+)|<\d+>)*[!?] le sequenze di caratteri non numerici non possono essere interrotte e pertanto il mancato riconoscimento viene rilevato più velocemente.
E' possibile forzare il processo di riconoscimento a obbedire alle sotto-regole in modo condizionato, oppure a scegliere tra due alternative in base al risultato di una asserzione, o piuttosto se la sotto-regola di cattura precedente ha riconosciuto il proprio testo. I due metodi possibili per esprimere una sotto-regola condizionale sono:
(?(condizione)yes-pattern)
(?(condizione)yes-pattern|no-pattern)
Se la condizione è soddisfatta, si usa la regola indicata in yes-pattern, altrimenti si applica il no-pattern (qualora sia specificato). Se nella sotto-regola vi sono più di due alternative, PCRE segnala un errore in fase di compila.
Vi sono due tipi di condizioni. Se il testo tra le parentesi consiste in una sequenza di cifre, allora la condizione è soddisfatta se la sotto-regola di cattura di quel numero è stata precedentemente riconosciuta. Si consideri il seguente criterio contenente degli spazi non significativi per renderlo più leggibile (si assuma che sia attiva l'opzione PCRE_EXTENDED) e lo si divida in tre parti per praticità di discussione: ( \( )? [^()]+ (?(1) \) )
La prima parte riconosce una parentesi aperta opzionale, e, se è presente, indica quello come primo segmento di stringa catturato. La seconda parte riconosce uno o più caratteri che non siano parentesi. Infine la terza parte è una sotto-regola condizionale che verifica se la prima parentesi è stata identifica o meno. Se accade, come nel caso in cui il testo inizi con una parentesi aperta, la condizione è TRUE, e quindi viene eseguito il ramo yes-pattern, richiedendo, conseguentemente, la parentesi chiusa. Diversamente, poiché non è specificato ramo no-pattern, non si esegue nessun altro riconoscimento. In altre parole questo criterio identifica un testo che possa essere racchiuso tra parentesi opzionali.
Se la condizione non è una sequenza di cifre, deve essere una asserzione. Questa può essere sia una asserzione che guarda avanti, sia una asserzione cha guarda indietro, sia positiva sia negativa. Si consideri il seguente criterio, ancora una volta contenente spazi non significativi, e con due alternative nella seconda linea:
(?(?=[^a-z]*[a-z])
\d{2}-[a-z]{3}-\d{2} | \d{2}-\d{2}-\d{2} )
La condizione è una asserzione che guarda avanti positiva, la quale identifica una sequenza opzionale di caratteri non alfabetici seguiti da una lettera. In altre parole, si testa la presenza di almeno una lettera nel testo. Se la lettera viene trovata si applica il primo criterio per il riconoscimento del testo, altrimenti viene applicato il secondo criterio. Questo criterio riconosce stringhe in due formati dd-aaa-dd oppure dd-dd-dd, dove aaa sono lettere e dd sono numeri.
La sequenza (?# indica l'inizio di un commento che si conclude con la successiva parentesi chiusa. Parentesi annidate non sono permesse. I caratteri che fanno parte di un commento non giocano alcun ruolo nella fase di riconoscimento.
Se viene attivata l'opzione PCRE_EXTENDED, un carattere # privo della sequenza di escape (\) all'esterno di una classe di caratteri apre un commento che continua fino al carattere di "a capo".
Si consideri il caso in cui si debba riconoscere una stringa tra parentesi, si supponga inoltre di dovere ammettere un numero arbitrario di parentesi annidate. Senza l'uso della ricorsione, il miglior metodo consiste nel preparare un criterio che identifichi un numero finito di parentesi annidate. Però, in questo modo non si gestisce un numero arbitrario si parentesi annidate. Nella versione 5.6 di Perl è stata introdotta, a livello sperimentale, la possibilità per i criteri di riconoscimento di essere ricorsivi. Allo scopo è stata definita la sequenza speciale (?R). Il criterio illustrato di seguito risolve il problema delle parentesi (si assume che l'opzione PCRE_EXTENDED sia attivata in modo da ignorare gli spazi): \( ( (?>[^()]+) | (?R) )* \)
In principio si identifica la parentesi di apertura. Quindi si cerca un numero indefinito di stringhe che possano essere composte da caratteri che non siano parentesi, oppure che siano riconosciute ricorsivamente dal criterio (ad esempio una stringa correttamente tra parentesi). Infine si cerca la parentesi di chiusura.
In questo particolare esempio si hanno arbitrarie ripetizioni annidate, e quindi l'uso delle sotto-regole a riconoscimento singolo per il riconoscimento della stringa priva di parentesi è particolarmente utile se il criterio viene applicato ad un testo non riconoscibile. Ad esempio, applicando il criterio a (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() si ottiene un esito di mancato riconoscimento rapidamente. Se, al contrario, non si fosse usato il criterio a riconoscimento singolo, sarebbe occorso molto tempo per avere un esito dato che vi sono moltissimi modi in cui i caratteri di ripetizione + e * possono essere applicati al testo, richiedendo, pertanto, la verifica di tutte le combinazioni prima di fornire l'esito negativo.
Il valori restituiti da una sotto-regola di cattura sono quelli ottenuti dal livello di ricorsione più esterno. Se il criterio illustrato in precedenza venisse applicato al testo (ab(cd)ef) Il valore ottenuto sarebbe "ef", che rappresenta l'ultimo valore catturato al livello più alto. Se si aggiungono altre parentesi al criterio, ottenendo \( ( ( (?>[^()]+) | (?R) )* ) \) allora il testo ottenuto sarebbe "ab(cd)ef", cioè il valore delle parentesi di livello più alto. Se nel criterio vi sono più di 15 sotto-regole di cattura, PCRE ha necessità di ottenere maggiore memoria per archiviare le informazioni durante la ricorsione. Questa memoria è ottenuta utilizzando pcre_malloc, al termine verrà liberata con pcre_free. Se non può essere ottenuta ulteriore memoria, si ha il salvataggio delle informazioni dei primi 15 testi catturati, dato che non vi è modo di restituire un messaggio di memoria insufficiente dalla ricorsione.
Certi elementi utilizzati per i criteri di riconoscimento sono più efficienti di altri. E' più efficiente usare le classi di caratteri come [aeiou] piuttosto che un gruppo di alternative come (a|e|i|o|u). In generale la costruzione più semplice per ottenere un dato scopo è la più efficiente. Nel libro di Jeffrey Friedl sono illustrate varie tecniche sull'ottimizzazione delle espressioni regolari.
Quando un criterio comincia con .* ed è attiva l'opzione PCRE_DOTALL, il criterio è implicitamente ancorato da PCRE, dato che può rico- noscere solo l'inizio della stringa. Tuttavia, se non è attivo PCRE_DOTALL, PCRE non può fare questa ottimizzazione, perché il meta-carattere . non ri- conosce più il carattere di "a capo", e quindi se la stringa contiene dei caratteri di "a capo", il riconoscimento può par- tire dal carattere immediatamente successivo ad uno di questi e non dall'inizio. Ad esempio il criterio (.*) second può eseguire un riconoscimento nel testo "first\nand second" (dove \n indica il carattere "a capo") ottenendo "and" come prima stringa catturata. perché ciò accada è necessario che PCRE possa iniziare il riconoscimento dopo ogni "a capo".
Se si deve usare un simile criterio in stringhe che non conten- gono caratteri di "a capo", le performance migliori si possono ottenere abilitando PCRE_DOTALL, oppure iniziando il criterio con ^.* in modo da richiedere un ancoraggio esplicito. Così si risparmia a PCRE di scandirsi il testo alla ricerca di un "a capo" da cui ripartire per la ri- cerca.
Occorre prestare attenzione ai criteri che contengono ripeti- zioni indefinite annidate. Possono richiedere molto tempo se applicati a stringhe non riconoscibili. Si consideri il fram- mento (a+)*
Questo può riconoscere "aaaa" in 33 modi differenti, e questo numero può crescere molto rapidamente se la stringa da ricono- scere è più lunga. (Il carattere di ripetizione * può eseguire riconoscimenti per 0,1,2,3 o 4 ripetizioni, e per ciascuna di esse, tranne lo 0, il carattere di ripetizione + può esegui- re riconoscimenti per diversi numeri di volte). Quindi se la parte successiva del criterio è tale da non permettere il com- pletamento del riconoscimento, PCRE, per principio, ugualmente tenta tutte le possibili variazioni, richiedendo diverso tempo.
Una ottimizzazione riesce a catturare qualche caso semplice come in (a+)*b dove si indica che seguirà un carattere alfanumerico. PCRE, prima di imbarcarsi nella procedura standard di riconoscimen- to, verifica se nel testo vi è la lettera "b", e se non c'è restituisce immediatamente un esito negativo. Tuttavia se non viene indicata una lettera seguente questa ottimizzazione non può essere utilizzata. Se ne può notare la differenza analiz- zando il comportamento del criterio (a+)*\d rispetto al precedente. Il primo, utilizzato con una stringa composta da "a", fallisce immediatamente, l'ultimo richiede un tempo apprezzabile, soprattutto se applicato a stringhe con più di 20 caratteri.
(PHP 4 , PHP 5)
preg_grep -- Restituisce una matrice degli elementi riconosciuti tramite le espressioni regolariLa funzione preg_grep() restituisce una matrice composta dagli elementi dell'array testo che soddisfano i criteri impostati nel parametro espressione_regolare.
Il parametro flags può assumere i seguenti valori:
Con questo valore, la funzione preg_grep()gli elementi della matrice di input che non soddisfano la data espressione_regolare. Questo valore è disponibile a partire da PHP 4.2.0.
A partire dalla versione 4.0.4 di PHP, la matrice risultante dalla funzione preg_grep(), viene indicizzata utilizzando le chiavi dalla matrice di input. Se non si desidera un comportamento simile, applicare la funzione array_values() alla matrice ottenuta da questa funzione per ricalcolare gli indici.
(PHP 3>= 3.0.9, PHP 4 , PHP 5)
preg_match_all -- Esegue un riconoscimento globale con le espressioni regolariLa funzione ricerca tutte le espressioni regolari passate nel parametro espressione_regolare all'interno della stringa testo. I testi riconosciuti sono posti all'interno della matrice TestiRiconosciuti, nell'ordine specificato da flags.
Dopo avere riconosciuto il primo segmento di testo, le ricerche seguenti saranno effettuate a partire dall'ultima ricerca specificata.
Il parametro flags può essere la combinazione dei seguenti flag (da notare che non ha senso utilizzare PREG_PATTERN_ORDER in unione a PREG_SET_ORDER):
I testi riconosciuti saranno organizzati in modo tale da avere in $TestiRiconosciuti[0] la matrice di tutti i testi riconosciuti, in $TestiRiconosciuti[1] la matrice di tutti i testi che soddisfino il primo criterio di riconoscimento posto tra parentesi tonde, in $TestiRiconosciuti[2] si avranno i testi che soddisfino il secondo criterio e cosi via.
<?php preg_match_all("|<[^>]+>(.*)</[^>]+>|U", "<b>example: </b><div align=left>this is a test</div>", $out, PREG_PATTERN_ORDER); echo $out[0][0].", ".$out[0][1]."\n"; echo $out[1][0].", ".$out[1][1]."\n"; ?> |
Questo esempio produrrà:
<b>example: </b>, <div align=left>this is a test</div> example: , this is a test |
Nell'esempio, $out[0] contiene la matrice di tutte le stringhe che soddisfano i criteri impostati, $out[1] contiene la matrice dei testi delimitati dai tag.
Usando questo parametro come ordine dei riconoscimenti, si avrà in $TestiRiconosciuti[0] una matrice con il primo set di testi riconosciuti, in $TestiRiconosciuti[1], la matrice con il secondo set di testi riconosciuti e così via.
<?php preg_match_all("|<[^>]+>(.*)</[^>]+>|U", "<b>example: </b><div align=\"left\">this is a test</div>", $out, PREG_SET_ORDER); echo $out[0][0].", ".$out[0][1]."\n"; echo $out[1][0].", ".$out[1][1]."\n"; ?> |
Questo esempio visualizzerà:
<b>example: </b>, example: <div align="left">this is a test</div>, this is a test |
In questo esempio $out[0] è la matrice del primo set di testi riconosciuti. Nel dettaglio $out[0][0] conterrà il testo che incrocia l'intero criterio impostato, $out[0][1] conterrà il testo riconosciuto tramite il prima regola di riconoscimento presente nel criterio globale. Analogo discorso si può fare per $out[1]. In questo caso il ragionamento verrà svolto su un secondo segmento della stringa che soddisfi le condizioni poste dal criterio di riconoscimento.
Se viene impostato questo flag, per ogni testo riconosciuto viene restituito l'offset della stringa. Occorre notare che questo cambia il tipo di valore restituito nell'array, infatti ogni elemento è, a sua volta, un'array composto dalla stringa riconosciuta, all'indice 0, e dall'offset della stringa nell'indice 1. Questa costante è disponibile a partire dalla versione 4.3.0 di PHP.
Qualora non si specifichi il parametro flags, si assume per default il valore PREG_PATTERN_ORDER.
Normalemente la ricerca parte dall'inizio della stringa oggetto di ricerca. Con il parametro opzionale offset si può specificare da dove cominciare la ricerca. Equivale a passare substr()($testo, $offset) alla funzione preg_match() al posto del parametro testo. Il parametro offset è disponibile a partire dalla versione 4.3.3 di PHP.
La funzione restituisce il numero dei riconoscimenti completi svolti (che possono essere zero), oppure FALSE se si verificano degli errori.
Esempio 2. Ricerca di tag HTML
Questo esempio visualizzerà:
|
Vedere anche preg_match(), preg_replace() e preg_split().
Esegue un riconoscimento nel parametro testo utilizzando l'espressione regolare indicata in criterio.
Se viene fornito il terzo parametro, testi_riconosciuti, questo verrà valorizzato con i risultati della ricerca. In dettaglio $testi_riconosciuti[0] conterrà il testo che si incrocia con l'intero criterio di ricerca, $testi_riconosciuti[1] conterrà il testo che soddisfa il primo criterio posto tra parentesi, $testi_riconosciuti[2] il secondo e così via.
Il parametro flags può assumere i seguenti valori:
Se viene impostato questo flag, per ogni testo riconosciuto viene restituito l'offset della stringa. Occorre notare che questo cambia il tipo di valore restituito nell'array, infatti ogni elemento è, a sua volta, un'array composto dalla stringa riconosciuta, all'indice 0, e dall'offset della stringa nell'indice 1. Questa costante è disponibile a partire dalla versione 4.3.0 di PHP.
Normalemente la ricerca parte dall'inizio della stringa oggetto di ricerca. Con il parametro opzionale offset si può specificare da dove cominciare la ricerca. Equivale a passare substr()($testo, $offset) alla funzione preg_match() al posto del parametro testo. Il parametro offset è disponibile a partire dalla versione 4.3.3 di PHP.
La funzione preg_match() restituisce il numero di volte in cui è avvenuto il riconoscimento del criterio. Questo può essere 0 (nessun riconoscimento) oppure 1 se preg_match() si ferma dopo il primo riconoscimento. In condizioni normali, preg_match_all() continua il riconoscimento fino alla fine del parametro testo. preg_match() restituirà FALSE se si verifica un errore.
Suggerimento: Non utilizzare la funzione preg_match() se si desidera controllare se una stringa è contenuta in un'altra. Piuttosto utilizzare strpos() oppure strstr() che sono più veloci.
Esempio 2. Cerca la parola "web"
|
Esempio 3. Estrapolazione del dominio da un URL
L'esempio visualizzerà:
|
Vedere anche preg_match_all(), preg_replace() e preg_split().
(PHP 3>= 3.0.9, PHP 4 , PHP 5)
preg_quote -- Inserisce il carattere di escape nei caratteri delle espressioni regolariLa funzione preg_quote() inserisce il carattere di escape (\) davanti ad ogni carattere presente in stringa che sia parte della sintassi di una espressione regolare. Questa funzione è utile nei casi in cui si generino, durante l'esecuzione, delle stringhe da usare come criteri di riconoscimento, e queste possano contenere dei caratteri speciali per le espressioni regolari.
Se viene specificato un carattere come parametro delimitatore, anche a questo sarà anteposto il carattere di escape (\). Ciò è particolarmente utile per porre il carattere di escape nei delimitatori richiesti dalle funzioni PCRE. Il carattere di delimitazione più comunemente utilizzato è /.
I caratteri speciali per le espressioni regolari sono: . \\ + * ? [ ^ ] $ ( ) { } = ! < > | :
Esempio 2. Esempio di come rendere in corsivo una qualsiasi parola di un testo
|
(PHP 4 >= 4.0.5, PHP 5)
preg_replace_callback -- Esegue ricerche e sostituzioni con espressioni regolari usando il callbackFondamentalmente questa funzione si comporta come preg_replace(), eccetto che per la presenza del callback. Con quest'ultimo parametro si indica una funzione da richiamare a cui verrà passata una matrice con i testi riconosciuti in testo. La funzione di callback dovrebbe restituire la stringa da sostituire.
Esempio 1. Esempio dell'uso di preg_replace_callback()
|
Spesso si ha la necessità di richiamare la funzione callback soltanto in un unico posto. In questo caso si può utilizzare create_function() per dichiarare una funzione anonima come callback per preg_replace_callback().In questo modo si hanno tutte le informazioni per la chiamata in un unico posto e non si disperde con funzioni di callback non utilizzate altrove.
Esempio 2. preg_replace_callback() e create_function()
|
Vedere anche preg_replace() e create_function().
(PHP 3>= 3.0.9, PHP 4 , PHP 5)
preg_replace -- Esegue una ricerca ed una sostituzione con le espressioni regolariLa funzione ricerca in testo i criteri impostati in espressione_regolare. Se riconosce dei testi, li sostituisce con sostituto. Se si specifica limite, verranno sostituiti solamente limite testi riconosciuti; se viene omesso, oppure impostato a -1, verranno sostituiti tutti i testi riconosciuti.
Il parametro sostituto può contenere riferimenti nella forma di \\n, oppure, a partire dalla versione 4.0.4 di PHP, $n , con la preferenza per la seconda sintassi. Questo tipo di riferimento verrà sostituito dal testo che soddisfa l'n -esimo criterio presente in espressione_regolare . Sono ammessi numeri compresi tra 0 e 99 inclusi. Il valore 0 (\\0 oppure $0) si riferisce al testo riconosciuto tramite tutta l'espressione regolare passata. Nel conteggio dei criteri di riconoscimento presenti, sono contate le parentesi aperte da sinistra verso destra partendo da 1.
Quando si lavora con un criterio di sostituzione in cui un riferimento all'indietro è immediatamente seguito da un'altro numero (ad esempio un numero che segue immediatamente il criterio riconosciuto), non si possono utilizzare le solite notazioni, \\1, per i riferimenti all'indietro. Ad esempio, il testo \\11 confonderebbe preg_replace() poichè non saprebbe se si desidera il riferimento all'indietro \\1 seguito dal numero 1, oppure se è desiderato il riferimento \\11 seguito da niente. In questi casi la soluzione consiste nell'uso di \${1}1. In questo modo si crea un riferimento all'indietro $1 isolato dal numero 1.
Se verranno riconosciuti dei testi, la funzione restituisce la nuova versione di testo, altrimenti il parametro sarà restituito inalterato.
Ogni parametro passato alla funzione preg_replace(), (eccetto limite) può essere una matrice ad una dimensione. Quando si utilizzano matrici con espressione_regolare e sostituto, le chiavi sono processate nell'ordine con cui appaiono nella matrice. Questo non è necessariamente l'ordine numerico dell'indice. Se si utilizzano degli indici per identificare quale espressione_regolare debba essere sostituita da sostituto, occorre eseguire la funzione ksort() su ciascuna matrice prima di eseguire preg_replace().
Esempio 2. Uso di matrici indicizzate con preg_replace()
Output:
Utilizzando ksort su entrambe le matrici otteniamo cio che vogliamo.
Output :
|
Se il campo testo è una matrice, la ricerca e la sostituzione sarà eseguita su ogni elemento della matrice, e conseguentemente la funzione restituirà una matrice.
Se espressione_regolare ed sostituto sono entrambi delle matrici, la funzione preg_replace() utilizza gli elementi di ciascuna matrice per la ricerca e la sostituzione delle stringhe in testo. Nel caso in cui la matrice passata in sostituto abbia meno elementi che espressione_regolare, la funzione utilizzerà una stringa vuota per compensare gli elementi mancanti nella fase di sostituzione. Se, invece, espressione_regolare è una matrice, mentre il campo sostituto è una stringa, quest'ultima sarà usata come valore da sostituire ad ogni testo riconosciuto. Un discorso contrario non ha senso.
Il modificatore /e, permette alla funzione di considerare il testo posto in sostituto come codice PHP dopo aver valorizzato gli opportuni riferimenti. Suggerimento: accertarsi che sostituto sia del codice PHP valido, altrimenti si ottiene un errore di parsing alla linea della funzione preg_replace().
Esempio 5. Esempio di conversione di codice HTML in testo
|
Nota: Il parametro limite è stato aggiunto successivamente alla versione 4.0.1pl2 di PHP.
Vedere anche preg_match(), preg_match_all() e preg_split().
(PHP 3>= 3.0.9, PHP 4 , PHP 5)
preg_split -- Suddivisione di una stringa tramite le espressioni regolariLa funzione restituisce una matrice di parti di testo suddivisi tramite i criteri indicati da espressione_regolare.
Se viene specificato il parametro limite, la funzione restituisce tante parti del testo iniziale quante sono indicate da limite. Può essere usato il valore -1 per indicare "nessun limite". Ciò torna utile in abbinamento all'uso del parametro flags.
Il parametro flags può essere la combinazione dei seguenti flag (la combinazione di più flag avviene con l'operatore |):
Specificando questo flag, la funzione preg_split() restituisce spezzoni di testo non vuoti.
Con l'uso di questo flag, la funzione cattura e restituisce eventuali espressioni poste tra parentesi nel parametro espressione_regolare. Questo flag è stato aggiunto nella versione 4.0.5.
Se viene impostato questo flag, per ogni testo riconosciuto viene restituito l'offset della stringa. Occorre notare che questo cambia il tipo di valore restituito nell'array; infatti ogni elemento è, a sua volta, un'array composto dalla stringa riconosciuta, all'indice 0, e dall'offset della stringa nell'indice 1. Questa costante è disponibile a partire dalla versione 4.3.0 di PHP.
Esempio 3. Suddivisione di una stringa in testi riconosciuti con i relativi offset.
visualizzerà
|
Nota: Il parametro flags è stato aggiunto nella versione 4 Beta 3 di PHP.
Vedere anche spliti(), split(), implode(), preg_match(), preg_match_all() e preg_replace().
(PHP 4 >= 4.0.5)
qdom_error -- Restituisce la stringa d'errore dell'ultima operazione QDOM o FALSE se non ci sono stati erroriAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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.
Avvertimento |
Non variare TYPE se non si sa cosa si sta facendo. |
Per abilitare il supporto a regex occorre configurare il PHP con --with-regex[=TYPE]. TYPE può essere: system, apache, php. Per default si usa php.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Esempio 1. Esempi di espressione regolare
|
Per maggiori dettagli sulle espressioni regolari compatibili con Perl vedere il capitolo sulle funzioni PCRE. La funzione fnmatch() fornisce il riconoscimento dei caratteri jolly tipici della linea di comando.
La funzione ricerca all'interno del parametro stringa sottostringhe che incrocino con le condizioni specificate in espressione_regolare. Quando sono trovate, queste vengono sostituite con il testo specificato in testo_sostitutivo.
La funzione restituisce la stringa modificata. (Ciò implica che se non ci sono sottostringhe che soddisfino l' espressione regolare, la funzione restituisce la stringa originaria).
Se in espressione_regolare si specificano delle sottostringhe utilizzando le parentesi, anche nel campo testo_sostitutivo si possono specificare delle sottostringhe di formato \\digit , che saranno sostituite dalle stringhe soddisfacenti la digit'esima condizione posta tra parentesi; \\0 indica l'intera stringa. La funzione prevede che si possano utlizzare fino a nove sottostringhe. E' previsto che le parentesi siano nidificate, in questo caso il conteggio si basa sulle parentesi aperte.
Se nessuna parte di stringa viene riconosciuta, il parametro viene restituito invariato.
Come esempio il seguente frammento di codice visualizzerà la frase "Questo fu un test" tre volte:
Un aspetto a cui occorre prestare attenzione riguarda l'uso di numero intero per il parametro testo_sostitutivo, si potrebbero ottenere risultati diversi da quanto atteso. Questo accade perchè la funzione ereg_replace() interpreta il numero come posizione ordinale di un carattere comportandosi di conseguenza. Ad esempio:
Esempio 2. ereg_replace() esempio
|
Suggerimento: Poichè utilizza espressioni regolari con sintassi compatibile con Perl, preg_replace(), è spesso una alternativa più veloce a ereg_replace().
Vedere anche ereg(), eregi(), eregi_replace(), str_replace() e preg_match().
Nota: Poichè utilizza espressioni regolari con sintassi compatibile con PERL, preg_match(), è spesso una alternativa più veloce a ereg().
Ricerca in stringa testi che possano incrociarsi con l'espressione regolare indicata in espressione_regolare distinguendo tra lettere minuscole e maiuscole.
Se le parti di testo poste tra parentesi nel campo espressione_regolare sono incontrate nella stringa e la funzione viene chiamata utilizzando il terzo parametro regs, il testo riconosciuto sarà memorizzato nella matrice regs. L'indice 1, $regs[1], conterrà la sottostringa che parte dalla prima parentesi sinistra; $regs[2] conterrà la sottostringa a partire dalla seconda e così via. L'indice 0, $regs[0], conterrà la copia completa della stringa riconosciuta.
Nota: Fino alla versione di PHP 4.1.0 compresa, $regs conterrà esattamente 10 elementi, anche se il numero delle stringhe riconosciute sia maggiore o minore di 10. Ciò non limita ereg() nella ricerca di più sottostringhe. Se non si riconoscono testi, $regs non sarà modificato da ereg().
La funzione ritorna 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:
Vedere anche eregi(), ereg_replace(), eregi_replace(), preg_match(), strpos() e strstr().
(PHP 3, PHP 4 , PHP 5)
eregi_replace -- Sostituzioni con espressioni regolari senza distinzione tra maiuscole e minuscoleQuesta funzione è identica a ereg_replace(), tranne che per il fatto che non distingue tra lettere maiuscole e lettere minuscole.
Vedere anche ereg(), eregi() e ereg_replace().
(PHP 3, PHP 4 , PHP 5)
eregi -- Riconoscimento di espressioni regolari senza distinzione tra maiuscole e minuscoleQuesta funzione è identica a ereg(), tranne che per il fatto che non distingue tra lettere maiuscole e lettere minuscole.
Vedere anche ereg(), ereg_replace(), eregi_replace(), stripos() e stristr().
(PHP 3, PHP 4 , PHP 5)
split -- Suddivide una stringa in una matrice utilizzando le espressioni regolariSuggerimento: Poichè utilizza espressioni regolari con sintassi compatibile con Perl, preg_split(), è spesso una alternativa più veloce a split(). Se non si ha necessità delle capacità delle espressioni regolari, è più veloce l'utilizzo di explode(), che non richiede l'overhead del motore delle espressioni regolari.
La funzione restituisce una matrice di stringhe che sono delle sottostringhe del parametro stringa. Queste sono ottenute suddividendo il parametro secondo i limiti indicati dal parametro sensibile alle maiuscole espressione_regolare. Se viene specificato il parametro limite, la funzione restituisce una matrice con un numero di elementi al massimo pari a limite. L'ultimo elemento della matrice contiene la parte restante del parametro stringa fornito. Se si verificano errori la funzione split() restituisce FALSE.
Esempio di come estrapolare i primi 4 campi da una linea del file /etc/passwd:
Se nella stringa passata vi sono n occorrenze del parametro espressione_regolare, la matrice restituita conterrà n+1 elementi. Invece, nel caso in cui non vi siano occorrenze della espressione_regolare, la matrice restituita conterrà un solo elemento. Ovviamente questo è valido anche nel caso in cui il parametro stringa è vuoto.
Nell'esempio che segue, si vedrà come analizzare una data il cui testo può contenere barre, punti o trattini:
Gli utenti che cercano un modo di emulare il comportamento di Perl @chars = split('', $str), sono rimandati agli esempi di preg_split().
Occorre fare attenzione al fatto che il parametro espressione_regolare è una espressione regolare e, pertanto, se si devono riconoscere caratteri che sono considerati speciali per le espressioni regolari, occorre codificarli con i caratteri di escape. Se si ritiene che la funzione split () ( o anche le altre funzioni derivate da regex ) si comportino in modo anomalo, è opportuno leggere il file regex.7, incluso nella cartella regex/ della distribuzione di PHP. Questo file è nel formato del manuale di unix (man), pertanto per visualizzarlo occorre eseguire il comando man /usr/local/src/regex/regex.7.
Vedere anche: preg_split(), spliti(), explode(), implode(), chunk_split() e wordwrap().
(PHP 4 >= 4.0.1, PHP 5)
spliti -- Suddivide una stringa in una matrice usando le espressioni regolari senza distinguere tra maiuscole e minuscoleQuesta funzione ha un comportamento identico a split() tranne che per il fatto di non distinguere tra lettere maiuscole e minuscole.
(PHP 3, PHP 4 , PHP 5)
sql_regcase -- Genera una espressione regolare per riconoscimenti senza distinguere tra maiuscole e minuscoleLa funzione restituisce una espressione regolare che sia in grado di riconoscere il parametro stringa, a prescindere dalle lettere maiuscole minuscole. L'espressione regolare restituita corrisponde a stringa con ciascun carattere alfabetico riportato tra parentesi. Ogni parentesi contiene il singolo carattere in maiuscolo ed in minuscolo. I rimanenti caratteri sono riportati immutati.
Questa funzione torna utile quando si devono ottenere espressioni regolari non distinguono tra lettere maiuscole e minuscole da passare a prodotti che supportano espressioni regolari che distinguono il tipo di lettera.
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
SHMMAX | dimensione massima della memoria condivisa, solitamente 131072 bytes |
SHMMIN | dimensione 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.
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.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 2. Opzioni per la configurazione dei Semafori
Nome | Default | Modificabile |
---|---|---|
sysvmsg.value | "42" | PHP_INI_ALL |
sysvmsg.string | "foobar" | PHP_INI_ALL |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
(PHP 4 >= 4.2.0, PHP 5)
ftok -- Converte il percorso e un identificatore di progetto in un chiave IPC di System VLa 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().
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().
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_NOWAIT | Se 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_EXCEPT | Usando 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().
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().
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().
(PHP 4 >= 4.3.0, PHP 5)
msg_set_queue -- Valorizza le informazioni nella struttura dati della coda dei messaggimsg_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() 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().
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().
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.
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.
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.
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.
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.
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.
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
shm_put_var -- Inserisce o aggiorna una variabile nella memoria condivisaLa 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.
Rimuove la variabile identificata da variable_key e libera la memoria occupata.
Nota: Questa funzione non è utilizzabile sui sistemi Windows.
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.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Name of BS2000 PLAM library containing the loadable SESAM driver modules. Required for using SESAM functions. The BS2000 PLAM library must be set ACCESS=READ,SHARE=YES because it must be readable by the apache server's user id.
Name of SESAM application configuration file. Required for using SESAM functions. The BS2000 file must be readable by the apache server's user id.
The application configuration file will usually contain a configuration like (see SESAM reference manual):
Name of SESAM message catalog file. In most cases, this directive is not 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.
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
Directive | Meaning |
---|---|
php3_sesam_oml |
Name of BS2000 PLAM library containing the loadable SESAM
driver modules. Required for using SESAM functions.
Example: |
php3_sesam_configfile |
Name of SESAM application configuration file. Required for
using SESAM functions.
Example: It will usually contain a configuration like (see SESAM reference manual): |
php3_sesam_messagecatalog |
Name of SESAM message catalog file. In most cases, this
directive is not 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: |
In addition to the configuration of the PHP/SESAM interface, you have to configure the SESAM-Database server itself on your mainframe as usual. That means:
starting the SESAM database handler (DBH), and
connecting the databases with the SESAM database handler
To get a connection between a PHP script and the database handler, the CNF and NAM parameters of the selected SESAM configuration file must match the id of the started database handler.
In case of distributed databases you have to start a SESAM/SQL-DCN agent with the distribution table including the host and database names.
The communication between PHP (running in the POSIX subsystem) and the database handler (running outside the POSIX subsystem) is realized by a special driver module called SQLSCI and SESAM connection modules using common memory. Because of the common memory access, and because PHP is a static part of the web server, database accesses are very fast, as they do not require remote accesses via ODBC, JDBC or UTM.
Only a small stub loader (SESMOD) is linked with PHP, and the SESAM connection modules are pulled in from SESAM's OML PLAM library. In the configuration, you must tell PHP the name of this PLAM library, and the file link to use for the SESAM configuration file (As of SESAM V3.0, SQLSCI is available in the SESAM Tool Library, which is part of the standard distribution).
Because the SQL command quoting for single quotes uses duplicated single quotes (as opposed to a single quote preceded by a backslash, used in some other databases), it is advisable to set the PHP configuration directives php3_magic_quotes_gpc and php3_magic_quotes_sybase to On for all PHP scripts using the SESAM interface.
Because of limitations of the BS2000 process model, the driver can be loaded only after the Apache server has forked off its server child processes. This will slightly slow down the initial SESAM request of each child, but subsequent accesses will respond at full speed.
When explicitly defining a Message Catalog for SESAM, that catalog will be loaded each time the driver is loaded (i.e., at the initial SESAM request). The BS2000 operating system prints a message after successful load of the message catalog, which will be sent to Apache's error_log file. BS2000 currently does not allow suppression of this message, it will slowly fill up the log.
Make sure that the SESAM OML PLAM library and SESAM configuration file are readable by the user id running the web server. Otherwise, the server will be unable to load the driver, and will not allow to call any SESAM functions. Also, access to the database must be granted to the user id under which the Apache server is running. Otherwise, connections to the SESAM database handler will fail.
The result cursors which are allocated for SQL "select type" queries can be either "sequential" or "scrollable". Because of the larger memory overhead needed by "scrollable" cursors, the default is "sequential".
When using "scrollable" cursors, the cursor can be freely positioned on the result set. For each "scrollable" query, there are global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT) and the scrolling offset which can either be set once by sesam_seek_row() or each time when fetching a row using sesam_fetch_row(). When fetching a row using a "scrollable" cursor, the following post-processing is done for the global default values for the scrolling type and scrolling offset:
Tabella 2. Scrolled Cursor Post-Processing
Scroll Type | Action |
---|---|
SESAM_SEEK_NEXT | none |
SESAM_SEEK_PRIOR | none |
SESAM_SEEK_FIRST | set scroll type to SESAM_SEEK_NEXT |
SESAM_SEEK_LAST | set scroll type to SESAM_SEEK_PRIOR |
SESAM_SEEK_ABSOLUTE | Auto-Increment internal offset value |
SESAM_SEEK_RELATIVE | none. (maintain global default offset value, which allows for, e.g., fetching each 10th row backwards) |
Because in the PHP world it is natural to start indexes at zero (rather than 1), some adaptions have been made to the SESAM interface: whenever an indexed array is starting with index 1 in the native SESAM interface, the PHP interface uses index 0 as a starting point. E.g., when retrieving columns with sesam_fetch_row(), the first column has the index 0, and the subsequent columns have indexes up to (but not including) the column count ($array["count"]). When porting SESAM applications from other high level languages to PHP, be aware of this changed interface. Where appropriate, the description of the respective PHP sesam functions include a note that the index is zero based.
When allowing access to the SESAM databases, the web server user should only have as little privileges as possible. For most databases, only read access privilege should be granted. Depending on your usage scenario, add more access rights as you see fit. Never allow full control to any database for any user from the 'net! Restrict access to PHP scripts which must administer the database by using password control and/or SSL security.
No two SQL dialects are ever 100% compatible. When porting SQL applications from other database interfaces to SESAM, some adaption may be required. The following typical differences should be noted:
Vendor specific data types
Some vendor specific data types may have to be replaced by standard SQL data types (e.g., TEXT could be replaced by VARCHAR(max. size)).
Keywords as SQL identifiers
In SESAM (as in standard SQL), such identifiers must be enclosed in double quotes (or renamed).
Display length in data types
SESAM data types have a precision, not a display length. Instead of int(4) (intended use: integers up to '9999'), SESAM requires simply int for an implied size of 31 bits. Also, the only datetime data types available in SESAM are: DATE, TIME(3) and TIMESTAMP(3).
SQL types with vendor-specific unsigned, zerofill, or auto_increment attributes
Unsigned and zerofill are not supported. Auto_increment is automatic (use "INSERT ... VALUES(*, ...)" instead of "... VALUES(0, ...)" to take advantage of SESAM-implied auto-increment.
int ... DEFAULT '0000'
Numeric variables must not be initialized with string constants. Use DEFAULT 0 instead. To initialize variables of the datetime SQL data types, the initialization string must be prefixed with the respective type keyword, as in: CREATE TABLE exmpl ( xtime timestamp(3) DEFAULT TIMESTAMP '1970-01-01 00:00:00.000' NOT NULL );
$count = xxxx_num_rows();
Some databases promise to guess/estimate the number of the rows in a query result, even though the returned value is grossly incorrect. SESAM does not know the number of rows in a query result before actually fetching them. If you REALLY need the count, try SELECT COUNT(...) WHERE ..., it will tell you the number of hits. A second query will (hopefully) return the results.
DROP TABLE thename;
In SESAM, in the DROP TABLE command, the table name must be either followed by the keyword RESTRICT or CASCADE. When specifying RESTRICT, an error is returned if there are dependent objects (e.g., VIEWs), while with CASCADE, dependent objects will be deleted along with the specified table.
SESAM does not currently support the BLOB type. A future version of SESAM will have support for BLOB.
At the PHP interface, the following type conversions are automatically applied when retrieving SQL fields:
Tabella 3. SQL to PHP Type Conversions
SQL Type | PHP Type |
---|---|
SMALLINT, INTEGER | integer |
NUMERIC, DECIMAL, FLOAT, REAL, DOUBLE | float |
DATE, TIME, TIMESTAMP | string |
VARCHAR, CHARACTER | string |
The special "multiple fields" feature of SESAM allows a column to consist of an array of fields. Such a "multiple field" column can be created like this:
When retrieving a result row, "multiple columns" are accessed like "inlined" additional columns. In the example above, "pkey" will have the index 0, and the three "multi(1..3)" columns will be accessible as indices 1 through 3.
For specific SESAM details, please refer to the SESAM/SQL-Server documentation (english) or the SESAM/SQL-Server documentation (german), both available online, or use the respective manuals.
result_id is a valid result id returned by sesam_query().
Returns the number of rows affected by a query associated with result_id.
The sesam_affected_rows() function can only return useful values when used in combination with "immediate" SQL statements (updating operations like INSERT, UPDATE and DELETE) because SESAM does not deliver any "affected rows" information for "select type" queries. The number returned is the number of affected rows.
See also sesam_query() and sesam_execimm().
Returns: TRUE on success, FALSE on errors
sesam_commit() commits any pending updates to the database.
Note that there is no "auto-commit" feature as in other databases, as it could lead to accidental data loss. Uncommitted data at the end of the current script (or when calling sesam_disconnect()) will be discarded by an implied sesam_rollback() call.
See also: sesam_rollback().
Returns TRUE if a connection to the SESAM database was made, or FALSE on error.
sesam_connect() establishes a connection to an SESAM database handler task. The connection is always "persistent" in the sense that only the very first invocation will actually load the driver from the configured SESAM OML PLAM library. Subsequent calls will reuse the driver and will immediately use the given catalog, schema, and user.
When creating a database, the "catalog" name is specified in the SESAM configuration directive //ADD-SQL-DATABASE-CATALOG-LIST ENTRY-1 = *CATALOG(CATALOG-NAME = catalogname,...)
The "schema" references the desired database schema (see SESAM handbook).
The "user" argument references one of the users which are allowed to access this "catalog" / "schema" combination. Note that "user" is completely independent from both the system's user id's and from HTTP user/password protection. It appears in the SESAM configuration only.
See also sesam_disconnect().
Returns an associative array of status and return codes for the last SQL query/statement/command. Elements of the array are:
Tabella 1. Status information returned by sesam_diagnostic()
Element | Contents |
---|---|
$array["sqlstate"] | 5 digit SQL return code (see the SESAM manual for the description of the possible values of SQLSTATE) |
$array["rowcount"] | number of affected rows in last update/insert/delete (set after "immediate" statements only) |
$array["errmsg"] | "human readable" error message string (set after errors only) |
$array["errcol"] | error column number of previous error (0-based; or -1 if undefined. Set after errors only) |
$array["errlin"] | error line number of previous error (0-based; or -1 if undefined. Set after errors only) |
In the following example, a syntax error (E SEW42AE ILLEGAL CHARACTER) is displayed by including the offending SQL statement and pointing to the error location:
Esempio 1. Displaying SESAM error messages with error position
|
See also: sesam_errormsg() for simple access to the error string only
Returns: always TRUE.
sesam_disconnect() closes the logical link to a SESAM database (without actually disconnecting and unloading the driver).
Note that this isn't usually necessary, as the open connection is automatically closed at the end of the script's execution. Uncommitted data will be discarded, because an implicit sesam_rollback() is executed.
sesam_disconnect() will not close the persistent link, it will only invalidate the currently defined "catalog", "schema" and "user" triple, so that any sesam function called after sesam_disconnect() will fail.
See also sesam_connect().
Returns the SESAM error message associated with the most recent SESAM error.
See also sesam_diagnostic() for the full set of SESAM SQL status information.
Returns: A SESAM "result identifier" on success, or FALSE on error.
sesam_execimm() executes an "immediate" statement (i.e., a statement like UPDATE, INSERT or DELETE which returns no result, and has no INPUT or OUTPUT variables). "select type" queries can not be used with sesam_execimm(). Sets the affected_rows value for retrieval by the sesam_affected_rows() function.
Note that sesam_query() can handle both "immediate" and "select-type" queries. Use sesam_execimm() only if you know beforehand what type of statement will be executed. An attempt to use SELECT type queries with sesam_execimm() will return $err["sqlstate"] == "42SBW".
The returned "result identifier" can not be used for retrieving anything but the sesam_affected_rows(); it is only returned for symmetry with the sesam_query() function.
<?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().
Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
sesam_fetch_array() is an alternative version of sesam_fetch_row(). Instead of storing the data in the numeric indices of the result array, it stores the data in associative indices, using the field names as keys.
result_id is a valid result id returned by sesam_query() (select type queries only!).
For the valid values of the optional whenceand offset parameters, see the sesam_fetch_row() function for details.
sesam_fetch_array() fetches one row of data from the result associated with the specified result identifier. The row is returned as an associative array. Each result column is stored with an associative index equal to its column (aka. field) name. The column names are converted to lower case.
Columns without a field name (e.g., results of arithmetic operations) and empty fields are not stored in the array. Also, if two or more columns of the result have the same column names, the later column will take precedence. In this situation, either call sesam_fetch_row() or make an alias for the column.
A special handling allows fetching "multiple field" columns (which would otherwise all have the same column names). For each column of a "multiple field", the index name is constructed by appending the string "(n)" where n is the sub-index of the multiple field column, ranging from 1 to its declared repetition factor. The indices are NOT zero based, in order to match the nomenclature used in the respective query syntax. For a column declared as:
the associative indices used for the individual "multiple field" columns would be "multi(1)", "multi(2)", and "multi(3)" respectively.Subsequent calls to sesam_fetch_array() would return the next (or prior, or n'th next/prior, depending on the scroll attributes) row in the result set, or FALSE if there are no more rows.
Esempio 1. SESAM fetch array
|
See also: sesam_fetch_row() which returns an indexed array.
Returns a mixed array with the query result entries, optionally limited to a maximum of max_rows rows. Note that both row and column indexes are zero-based.
Tabella 1. Mixed result set returned by sesam_fetch_result()
Array Element | Contents |
---|---|
int $arr["count"] | number of columns in result set (or zero if this was an "immediate" query) |
int $arr["rows"] | number of rows in result set (between zero and max_rows) |
bool $arr["truncated"] | TRUE if the number of rows was at least max_rows, FALSE otherwise. Note that even when this is TRUE, the next sesam_fetch_result() call may return zero rows because there are no more result entries. |
mixed $arr[col][row] | result data for all the fields at row(row) and column(col), (where the integer index row is between 0 and $arr["rows"]-1, and col is between 0 and $arr["count"]-1). Fields may be empty, so you must check for the existence of a field by using the php isset() function. The type of the returned fields depend on the respective SQL type declared for its column (see SESAM overview for the conversions applied). SESAM "multiple fields" are "inlined" and treated like a sequence of columns. |
See also: sesam_fetch_row(), and sesam_field_array() to check for "multiple fields". See the description of the sesam_query() function for a complete example using sesam_fetch_result().
Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
The number of columns in the result set is returned in an associative array element $array["count"]. Because some of the result columns may be empty, the count() function can not be used on the result row returned by sesam_fetch_row().
result_id is a valid result id returned by sesam_query() (select type queries only!).
whence is an optional parameter for a fetch operation on "scrollable" cursors, which can be set to the following predefined constants:
Tabella 1. Valid values for "whence" parameter
Value | Constant | Meaning |
---|---|---|
0 | SESAM_SEEK_NEXT | read sequentially (after fetch, the internal default is set to SESAM_SEEK_NEXT) |
1 | SESAM_SEEK_PRIOR | read sequentially backwards (after fetch, the internal default is set to SESAM_SEEK_PRIOR) |
2 | SESAM_SEEK_FIRST | rewind to first row (after fetch, the default is set to SESAM_SEEK_NEXT) |
3 | SESAM_SEEK_LAST | seek to last row (after fetch, the default is set to SESAM_SEEK_PRIOR) |
4 | SESAM_SEEK_ABSOLUTE | seek to absolute row number given as offset (Zero-based. After fetch, the internal default is set to SESAM_SEEK_ABSOLUTE, and the internal offset value is auto-incremented) |
5 | SESAM_SEEK_RELATIVE | seek relative to current scroll position, where offset can be a positive or negative offset value. |
When using "scrollable" cursors, the cursor can be freely positioned on the result set. If the whence parameter is omitted, the global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT, and settable by sesam_seek_row()) are used. If whence is supplied, its value replaces the global default.
offset is an optional parameter which is only evaluated (and required) if whence is either SESAM_SEEK_RELATIVE or SESAM_SEEK_ABSOLUTE. This parameter is only valid for "scrollable" cursors.
sesam_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array (indexed by values between 0 and $array["count"]-1). Fields may be empty, so you must check for the existence of a field by using the 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
|
See also: sesam_fetch_array() which returns an associative array, and sesam_fetch_result() which returns many rows per invocation.
result_id is a valid result id returned by sesam_query().
Returns a mixed associative/indexed array with meta information (column name, type, precision, ...) about individual columns of the result after the query associated with result_id.
Tabella 1. Mixed result set returned by sesam_field_array()
Array Element | Contents |
---|---|
int $arr["count"] | Total number of columns in result set (or zero if this was an "immediate" query). SESAM "multiple fields" are "inlined" and treated like the respective number of columns. |
string $arr[col]["name"] | column name for column(col), where col is between 0 and $arr["count"]-1. The returned value can be the empty string (for dynamically computed columns). SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same column name. |
string $arr[col]["count"] | The "count" attribute describes the repetition factor when the column has been declared as a "multiple field". Usually, the "count" attribute is 1. The first column of a "multiple field" column however contains the number of repetitions (the second and following column of the "multiple field" contain a "count" attribute of 1). This can be used to detect "multiple fields" in the result set. See the example shown in the sesam_query() description for a sample use of the "count" attribute. |
string $arr[col]["type"] | PHP variable type of the data for column(col), where col is between 0 and $arr["count"]-1. The returned value can be one of depending on the SQL type of the result. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same PHP type. |
string $arr[col]["sqltype"] |
SQL variable type of the column data for
column(col), where col
is between 0 and $arr["count"]-1. The
returned value can be one of
|
string $arr[col]["length"] | The SQL "length" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "length" attribute is used with "CHARACTER" and "VARCHAR" SQL types to specify the (maximum) length of the string variable. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same length attribute. |
string $arr[col]["precision"] | The "precision" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "precision" attribute is used with numeric and time data types. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same precision attribute. |
string $arr[col]["scale"] | The "scale" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "scale" attribute is used with numeric data types. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same scale attribute. |
See also sesam_query() for an example of the sesam_field_array() use.
Returns the name of a field (i.e., the column name) in the result set, or FALSE on error.
For "immediate" queries, or for dynamic columns, an empty string is returned.
Nota: The column index is zero-based, not one-based as in SESAM.
See also: sesam_field_array(). It provides an easier interface to access the column names and types, and allows for detection of "multiple fields".
Releases resources for the query associated with result_id. Returns FALSE on error.
After calling sesam_query() with a "select type" query, this function gives you the number of columns in the result. Returns an integer describing the total number of columns (aka. fields) in the current result_id result set or FALSE on error.
For "immediate" statements, the value zero is returned. The SESAM "multiple field" columns count as their respective dimension, i.e., a three-column "multiple field" counts as three columns.
See also: sesam_query() and sesam_field_array() for a way to distinguish between "multiple field" columns and regular columns.
Returns: A SESAM "result identifier" on success, or FALSE on error.
A "result_id" resource is used by other functions to retrieve the query results.
sesam_query() sends a query to the currently active database on the server. It can execute both "immediate" SQL statements and "select type" queries. If an "immediate" statement is executed, then no cursor is allocated, and any subsequent sesam_fetch_row() or sesam_fetch_result() call will return an empty result (zero columns, indicating end-of-result). For "select type" statements, a result descriptor and a (scrollable or sequential, depending on the optional boolean scrollable parameter) cursor will be allocated. If scrollable is omitted, the cursor will be sequential.
When using "scrollable" cursors, the cursor can be freely positioned on the result set. For each "scrollable" query, there are global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT) and the scrolling offset which can either be set once by sesam_seek_row() or each time when fetching a row using sesam_fetch_row().
For "immediate" statements, the number of affected rows is saved for retrieval by the sesam_affected_rows() function.
See also: sesam_fetch_row() and sesam_fetch_result().
Esempio 1. Show all rows of the "phone" table as a HTML table
|
Returns: TRUE on success, FALSE on errors
sesam_rollback() discards any pending updates to the database. Also affected are result cursors and result descriptors.
At the end of each script, and as part of the sesam_disconnect() function, an implied sesam_rollback() is executed, discarding any pending changes to the database.
See also: sesam_commit().
Esempio 1. Discarding an update to the SESAM database
|
result_id is a valid result id (select type queries only, and only if a "scrollable" cursor was requested when calling sesam_query()).
whence sets the global default value for the scrolling type, it specifies the scroll type to use in subsequent fetch operations on "scrollable" cursors, which can be set to the following predefined constants:
Tabella 1. Valid values for "whence" parameter
Value | Constant | Meaning |
---|---|---|
0 | SESAM_SEEK_NEXT | read sequentially |
1 | SESAM_SEEK_PRIOR | read sequentially backwards |
2 | SESAM_SEEK_FIRST | fetch first row (after fetch, the default is set to SESAM_SEEK_NEXT) |
3 | SESAM_SEEK_LAST | fetch last row (after fetch, the default is set to SESAM_SEEK_PRIOR) |
4 | SESAM_SEEK_ABSOLUTE | fetch absolute row number given as offset (Zero-based. After fetch, the default is set to SESAM_SEEK_ABSOLUTE, and the offset value is auto-incremented) |
5 | SESAM_SEEK_RELATIVE | fetch relative to current scroll position, where offset can be a positive or negative offset value (this also sets the default "offset" value for subsequent fetches). |
offset is an optional parameter which is only evaluated (and required) if whence is either SESAM_SEEK_RELATIVE or SESAM_SEEK_ABSOLUTE.
Returns: TRUE if the values are valid, and the settransaction() operation was successful, FALSE otherwise.
sesam_settransaction() overrides the default values for the "isolation level" and "read-only" transaction parameters (which are set in the SESAM configuration file), in order to optimize subsequent queries and guarantee database consistency. The overridden values are used for the next transaction only.
sesam_settransaction() can only be called before starting a transaction, not after the transaction has been started already.
To simplify the use in PHP scripts, the following constants have been predefined in PHP (see SESAM handbook for detailed explanation of the semantics):
Tabella 1. Valid values for "Isolation_Level" parameter
Value | Constant | Meaning |
---|---|---|
1 | SESAM_TXISOL_READ_UNCOMMITTED | Read Uncommitted |
2 | SESAM_TXISOL_READ_COMMITTED | Read Committed |
3 | SESAM_TXISOL_REPEATABLE_READ | Repeatable Read |
4 | SESAM_TXISOL_SERIALIZABLE | Serializable |
Tabella 2. Valid values for "Read_Only" parameter
Value | Constant | Meaning |
---|---|---|
0 | SESAM_TXREAD_READWRITE | Read/Write |
1 | SESAM_TXREAD_READONLY | Read-Only |
The values set by sesam_settransaction() will override the default setting specified in the SESAM configuration file.
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
|
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.
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
|
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
|
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.
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() 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).
session_decode() decodifica i dati di sessione in data, impostando le varibili archiviate nella sessione.
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.
session_encode() restituisce una stringa con i contenuti della sessione corrente codificati.
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() 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() 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() restituisce il nome del corrente modulo di sessione. Se module è specificato, sarà invece usato quel modulo.
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()).
(PHP 4 >= 4.3.2, PHP 5)
session_regenerate_id -- Update the current session id with a newly generated onesession_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.
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() 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().
(PHP 4 , PHP 5)
session_save_path -- Assume o stabilisce il percorso di salvataggio sessione correntesession_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.
Imposta i parametri del cookie definiti nel file php.ini. L'effetto di questa funzione dura solo per la durata dello script.
(PHP 4 , PHP 5)
session_set_save_handler -- Imposta le funzioni di archiviazione sessioni a livello utentesession_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
|
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() 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(). |
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();
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.
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.
Per utilizzare shmop occorre compilare il PHP con il parametro --enable-shmop nella linea di configurazione.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Esempio 1. Descrizione delle operazioni con la memoria condivisa
|
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().
In questo esempio si chiude il blocco di memoria condivisa identificata da $shm_id.
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.
In questo esempio si cancella il segmento di memoria condivisa identificato da $shm_id.
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.
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.
Questo esempio apre un blocco di memoria condivisa con id di sistema restituito da ftok().
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.
Questo esempio legge 50 byte da un blocco di memoria condivisa e posiziona i dati nella variabile $shm_data.
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.
In questo esempio si memorizza nella variabile $shm_size la dimensione del blocco di memoria identificato da $shm_id.
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.
Questo esempio scrive i dati della variabile $my_string nel blocco di memoria condivisa, mentre $shm_bytes_written contiene il numero dei byte scritti.
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.
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.
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
|
The simplicity of SimpleXML appears most clearly when one extracts a string or number from a basic XML document.
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.
|
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.
|
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.
|
Esempio 6. Using Xpath SimpleXML includes builtin Xpath support. To find all <character> elements:
'//' 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.
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.
|
(no version information, might be only in CVS)
simplexml_element->asXML -- Return a well-formed XML string based on SimpleXML element.The asXML method formats the parent object's data in XML version 1.0.
asXML also works on Xpath results:
Esempio 2. Using asXML() on Xpath results
|
(no version information, might be only in CVS)
simplexml_element->attributes -- Identifies an element's attributes.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.
(no version information, might be only in CVS)
simplexml_element->children -- Finds children of given node.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
This script will output:
|
(no version information, might be only in CVS)
simplexml_element->xpath -- Runs Xpath query on XML data.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
This script will display:
Notice that the two results are equal. |
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.
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
This script will display, on success:
At this point, you can go about using $xml->title and any other elements. |
See also: simplexml_load_string()
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
This script will display:
At this point, you can go about using $xml->body and such. |
See also: simplexml_load_file().
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.
This extension makes use of the GNOME xml library. Download and install this library. You will need at least libxml-2.5.4.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. SOAP Configuration Options
Name | Default | Changeable |
---|---|---|
soap.wsdl_cache_enabled | "1" | PHP_INI_ALL |
soap.wsdl_cache_dir | "/tmp" | PHP_INI_ALL |
soap.wsdl_cache_ttl | 86400 | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
This 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
|
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
|
See also SoapClient::SoapClient(), SoapParam::SoapParam(), SoapVar::SoapVar(), SoapHeader::SoapHeader(), SoapFault::SoapFault(), and is_soap_fault().
(no version information, might be only in CVS)
SoapClient::__getFunctions -- Returns list of SOAP functionsThis function works only in WSDL mode.
See also SoapClient::SoapClient().
(no version information, might be only in CVS)
SoapClient::__getLastRequest -- Returns last SOAP requestThis function works only with SoapClient which was created with the trace option.
See also SoapClient::SoapClient().
(no version information, might be only in CVS)
SoapClient::__getLastResponse -- Returns last SOAP responseThis function works only with SoapClient which was created with the trace option.
See also SoapClient::SoapClient().
This function works only in WSDL mode.
See also SoapClient::SoapClient().
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.
It is possible to use PHP exception mechanism to throw SOAP Fault.
See also SoapClient::SoapClient(), SoapClient::__call(), SoapParam::SoapParam(), SoapVar::SoapVar(), and is_soap_fault().
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.
See also SoapClient::__call(), SoapParam::SoapParam(), and SoapVar::SoapVar().
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.
See also SoapClient::__call(), and SoapVar::SoapVar().
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
|
(no version information, might be only in CVS)
SoapServer::addFunction -- Adds one or several functions those will handle SOAP requestsExports 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
|
See also SoapServer::SoapServer(), and SoapServer::SetClass().
(no version information, might be only in CVS)
SoapServer::getFunctions -- Returns list of defined functionsThis functions returns the list of all functions which was added by SoapServer::addFunction() or SoapServer::setClass().
Esempio 1. Some examples
|
See also SoapServer::SoapServer(), SoapServer::addFunction(), and SoapServer::SetClass().
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.
See also SoapServer::SoapServer().
(no version information, might be only in CVS)
SoapServer::setClass -- Sets class which will handle SOAP requestsExports 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.
See also SoapServer::SoapServer(), SoapServer::addFunction(), and SoapServer::setPersistence().
(no version information, might be only in CVS)
SoapServer::setPersistence -- Sets persistence mode of SoapServerThis 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().
See also SoapServer::SoapServer(), and SoapServer::SetClass().
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
|
See also SoapClient::__call() and SoapParam::SoapParam().
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.
See also SoapClient::SoapClient(), and SoapFault::SoapFault().
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/).
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.
Per potere utilizzare questa funzioni, occorre compilare il PHP con il supporto per SQLite, oppure caricare dinamicamente il modulo da php.ini.
SQLite utilizza due risorse. La prima è la connessione con il database, la seconda è il set di risultati.
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
costante | significato |
---|---|
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. |
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 2. Parametri di configurazione di SQLite
Nome | Default | Modificabile |
---|---|---|
sqlite.assoc_case | 0 | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
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.
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.
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().
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().
Restituisce il numero di righe modificate dall'ultima istruzione SQL eseguita sul database referenziato da dbhandle.
Vedere anche sqlite_num_rows().
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().
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() è 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
|
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().
(PHP 5)
sqlite_create_function -- Registra una funzione utente "regolare" da utilizzare nelle istruzioni SQL.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()
|
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
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() è 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().
Restituisce una descrizione leggibile del error_code restituito dalla funzione sqlite_last_error().
Vedere anche sqlite_last_error().
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().
(no version information, might be only in CVS)
sqlite_exec -- Executes a result-less query against a given database.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().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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()
|
Vedere anche sqlite_fetch_array().
Dato il numero ordinale di colonna, field_index, restituisce il nome del campo dal set di risultati indicato in 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().
(PHP 5)
sqlite_last_error -- Restituisce il codice di errore dell'ultimo errore accorso sul database.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().
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.
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().
Restituisce, come stringa, la versione della libreria SQLite.
Vedere anche sqlite_libencoding().
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().
Restituisce il numero di campi presenti nel set di risultati result.
Vedere anche sqlite_column() e sqlite_num_rows().
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().
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()
|
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().
(PHP 5)
sqlite_popen -- Apre una connessione persistente ad un database SQLite. Crea il database se non esiste.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().
(PHP 5)
sqlite_query -- Esegue una query su un database e restituisce un puntatore al set di risultati.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() 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() 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().
(PHP 5)
sqlite_single_query -- Executes a query and returns either an array for one single column or the value of the first rowAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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
|
Vedere anche sqlite_udf_encode_binary(), sqlite_create_function() e sqlite_create_aggregate().
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() è 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().
PHP offers the ability to create Shockwave Flash files via Paul Haeberli's libswf module.
Nota: SWF support was added in PHP 4 RC2.
The libswf does not have support for Windows. The development of that library has been stopped, and the source is not available to port it to another systems.
For up to date SWF support take a look at the MING functions.
You need the libswf library to compile PHP with support for this extension. You can download libswf at ftp://ftp.sgi.com/sgi/graphics/grafica/flash/.
Once you have libswf all you need to do is to configure --with-swf[=DIR] where DIR is a location containing the directories include and lib. The include directory has to contain the swf.h file and the lib directory has to contain the libswf.a file. If you unpack the libswf distribution the two files will be in one directory. Consequently you will have to copy the files to the proper location manually.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
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
|
The swf_actiongeturl() function gets the URL specified by the parameter url with the target target.
The swf_actiongotoframe() function will go to the frame specified by framenumber, play it, and then stop.
The swf_actiongotolabel() function displays the frame with the label given by the label parameter and then stops.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
The swf_actionsettarget() function sets the context for all actions. You can use this to control other flash movies that are currently playing.
Toggle the flash movie between high and low quality.
The swf_actionwaitforframe() function will check to see if the frame, specified by the framenumber parameter has been loaded, if not it will skip the number of actions specified by the skipcount parameter. This can be useful for "Loading..." type animations.
The swf_addbuttonrecord() function allows you to define the specifics of using a button. The first parameter, states, defines what states the button can have, these can be any or all of the following constants: BSHitTest, BSDown, BSOver or BSUp. The second parameter, the shapeid is the look of the button, this is usually the object id of the shape of the button. The depth parameter is the placement of the button in the current frame.
Esempio 1. swf_addbuttonrecord() example
|
The swf_addcolor() function sets the global add color to the rgba color specified. This color is then used (implicitly) by the swf_placeobject(), swf_modifyobject() and the swf_addbuttonrecord() functions. The color of the object will be add by the rgba values when the object is written to the screen.
Nota: The rgba values can be either positive or negative.
Close a file that was opened by the swf_openfile() function. If the return_file parameter is set then the contents of the SWF file are returned from the function.
Esempio 1. Creating a simple flash file based on user input and outputting it and saving it in a database
|
The swf_definebitmap() function defines a bitmap given a GIF, JPEG, RGB or FI image. The image will be converted into a Flash JPEG or Flash color map format.
The swf_definefont() function defines a font given by the fontname parameter and gives it the id specified by the fontid parameter. It then sets the font given by fontname to the current font.
The swf_defineline() defines a line starting from the x coordinate given by x1 and the y coordinate given by y1 parameter. Up to the x coordinate given by the x2 parameter and the y coordinate given by the y2 parameter. It will have a width defined by the width parameter.
The swf_definepoly() function defines a polygon given an array of x, y coordinates (the coordinates are defined in the parameter coords). The parameter npoints is the number of overall points that are contained in the array given by coords. The width is the width of the polygon's border, if set to 0.0 the polygon is filled.
The swf_definerect() defines a rectangle with an upper left hand coordinate given by the x, x1, and the y, y1. And a lower right hand coordinate given by the x coordinate, x2, and the y coordinate, y2 . Width of the rectangles border is given by the width parameter, if the width is 0.0 then the rectangle is filled.
Define a text string (the str parameter) using the current font and font size. The docenter is where the word is centered, if docenter is 1, then the word is centered in x.
The swf_endbutton() function ends the definition of the current button.
Ends the current action started by the swf_startdoaction() function.
The swf_endshape() completes the definition of the current shape.
The swf_endsymbol() function ends the definition of a symbol that was started by the swf_startsymbol() function.
The swf_fontsize() function changes the font size to the value given by the size parameter.
Set the current font slant to the angle indicated by the slant parameter. Positive values create a forward slant, negative values create a negative slant.
Set the font tracking to the value specified by the tracking parameter. This function is used to increase the spacing between letters and text, positive values increase the space and negative values decrease the space between letters.
The swf_getbitmapinfo() function returns an array of information about a bitmap given by the bitmapid parameter. The returned array has the following elements:
"size" - The size in bytes of the bitmap.
"width" - The width in pixels of the bitmap.
"height" - The height in pixels of the bitmap.
The swf_getfontinfo() function returns an associative array with the following parameters:
Aheight - The height in pixels of a capital A.
xheight - The height in pixels of a lowercase x.
The swf_getframe() function gets the number of the current frame.
Label the current frame with the name given by the name parameter.
The swf_lookat() function defines a viewing transformation by giving the viewing position (the parameters view_x, view_y, and view_z) and the coordinates of a reference point in the scene, the reference point is defined by the reference_x, reference_y , and reference_z parameters. The twist controls the rotation along with viewer's z axis.
Updates the position and/or color of the object at the specified depth, depth. The parameter how determines what is updated. how can either be the constant MOD_MATRIX or MOD_COLOR or it can be a combination of both (MOD_MATRIX|MOD_COLOR).
MOD_COLOR uses the current mulcolor (specified by the function swf_mulcolor()) and addcolor (specified by the function swf_addcolor()) to color the object. MOD_MATRIX uses the current matrix to position the object.
The swf_mulcolor() function sets the global multiply color to the rgba color specified. This color is then used (implicitly) by the swf_placeobject(), swf_modifyobject() and the swf_addbuttonrecord() functions. The color of the object will be multiplied by the rgba values when the object is written to the screen.
Nota: The rgba values can be either positive or negative.
The swf_oncondition() function describes a transition that will trigger an action list. There are several types of possible transitions, the following are for buttons defined as TYPE_MENUBUTTON:
IdletoOverUp
OverUptoIdle
OverUptoOverDown
OverDowntoOverUp
IdletoOverDown
OutDowntoIdle
MenuEnter (IdletoOverUp|IdletoOverDown)
MenuExit (OverUptoIdle|OverDowntoIdle)
IdletoOverUp
OverUptoIdle
OverUptoOverDown
OverDowntoOverUp
OverDowntoOutDown
OutDowntoOverDown
OutDowntoIdle
ButtonEnter (IdletoOverUp|OutDowntoOverDown)
ButtonExit (OverUptoIdle|OverDowntoOutDown)
The swf_openfile() function opens a new file named filename with a width of width and a height of height a frame rate of framerate and background with a red color of r a green color of g and a blue color of b.
The swf_openfile() must be the first function you call, otherwise your script will cause a segfault. If you want to send your output to the screen make the filename: "php://stdout" (support for this is in 4.0.1 and up).
The swf_ortho2() function defines a two dimensional orthographic mapping of user coordinates onto the current viewport, this defaults to one to one mapping of the area of the Flash movie. If a perspective transformation is desired, the swf_perspective () function can be used.
(PHP 4 >= 4.0.1)
swf_ortho -- Defines an orthographic mapping of user coordinates onto the current viewportThe swf_ortho() function defines an orthographic mapping of user coordinates onto the current viewport.
The swf_perspective() function defines a perspective projection transformation. The fovy parameter is field-of-view angle in the y direction. The aspect parameter should be set to the aspect ratio of the viewport that is being drawn onto. The near parameter is the near clipping plane and the far parameter is the far clipping plane.
Nota: Various distortion artifacts may appear when performing a perspective projection, this is because Flash players only have a two dimensional matrix. Some are not to pretty.
Places the object specified by objid in the current frame at a depth of depth. The objid parameter and the depth must be between 1 and 65535.
This uses the current mulcolor (specified by swf_mulcolor()) and the current addcolor (specified by swf_addcolor()) to color the object and it uses the current matrix to position the object.
Nota: Full RGBA colors are supported.
The swf_polarview() function defines the viewer's position in polar coordinates. The dist parameter gives the distance between the viewpoint to the world space origin. The azimuth parameter defines the azimuthal angle in the x,y coordinate plane, measured in distance from the y axis. The incidence parameter defines the angle of incidence in the y,z plane, measured in distance from the z axis. The incidence angle is defined as the angle of the viewport relative to the z axis. Finally the twist specifies the amount that the viewpoint is to be rotated about the line of sight using the right hand rule.
The swf_popmatrix() function pushes the current transformation matrix back onto the stack.
(PHP 4 )
swf_posround -- Enables or Disables the rounding of the translation when objects are placed or movedThe swf_posround() function enables or disables the rounding of the translation when objects are placed or moved, there are times when text becomes more readable because rounding has been enabled. The round is whether to enable rounding or not, if set to the value of 1, then rounding is enabled, if set to 0 then rounding is disabled.
The swf_pushmatrix() function pushes the current transformation matrix back onto the stack.
The swf_rotate() rotates the current transformation by the angle given by the angle parameter around the axis given by the axis parameter. Valid values for the axis are 'x' (the x axis), 'y' (the y axis) or 'z' (the z axis).
The swf_scale() scales the x coordinate of the curve by the value of the x parameter, the y coordinate of the curve by the value of the y parameter, and the z coordinate of the curve by the value of the z parameter.
The swf_setfont() sets the current font to the value given by the fontid parameter.
The swf_setframe() changes the active frame to the frame specified by framenumber.
The swf_shapearc() function draws a circular arc from angle A given by the ang1 parameter to angle B given by the ang2 parameter. The center of the circle has an x coordinate given by the x parameter and a y coordinate given by the y, the radius of the circle is given by the r parameter.
Draw a cubic bezier curve using the x,y coordinate pairs x1, y1 and x2,y2 as off curve control points and the x,y coordinate x3, y3 as an endpoint. The current position is then set to the x,y coordinate pair given by x3,y3.
The swf_shapecurveto() function draws a quadratic bezier curve from the current location, though the x coordinate given by x1 and the y coordinate given by y1 to the x coordinate given by x2 and the y coordinate given by y2. The current position is then set to the x,y coordinates given by the x2 and y2 parameters
Sets the fill to bitmap clipped, empty spaces will be filled by the bitmap given by the bitmapid parameter.
Sets the fill to bitmap tile, empty spaces will be filled by the bitmap given by the bitmapid parameter (tiled).
The swf_shapefilloff() function turns off filling for the current shape.
The swf_shapefillsolid() function sets the current fill style to solid, and then sets the fill color to the values of the rgba parameters.
The swf_shapelinesolid() function sets the current line style to the color of the rgba parameters and width to the width parameter. If 0.0 is given as a width then no lines are drawn.
The swf_shapelineto() draws a line to the x,y coordinates given by the x parameter & the y parameter. The current position is then set to the x,y parameters.
The swf_shapemoveto() function moves the current position to the x coordinate given by the x parameter and the y position given by the y parameter.
The swf_startbutton() function starts off the definition of a button. The type parameter can either be TYPE_MENUBUTTON or TYPE_PUSHBUTTON. The TYPE_MENUBUTTON constant allows the focus to travel from the button when the mouse is down, TYPE_PUSHBUTTON does not allow the focus to travel when the mouse is down.
The swf_startdoaction() function starts the description of an action list for the current frame. This must be called before actions are defined for the current frame.
The swf_startshape() function starts a complex shape, with an object id given by the objid parameter.
Define an object id as a symbol. Symbols are tiny flash movies that can be played simultaneously. The objid parameter is the object id you want to define as a symbol.
The swf_textwidth() function gives the width of the string, str, in pixels, using the current font and font size.
The swf_translate() function translates the current transformation by the x, y, and z values given.
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.
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 |
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.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
(PHP 3>= 3.0.8, PHP 4 , PHP 5)
snmp_get_quick_print -- Restituisce il valore corrente per il parametro quick_print della libreria UCDLa funzione restituisce il valore del parametro quick_print della libreria UCD. Per default quick_print è settato ad off.
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.
(PHP 4 >= 4.3.3, PHP 5)
snmp_get_valueretrieval -- Return the method how the SNMP values will be returnedAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
snmp_set_enum_print -- Return all values that are enums with their enum value instead of the raw integerAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
snmp_set_oid_numeric_print -- Return all objects including their respective object id within the specified oneAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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.
(PHP 4 >= 4.3.3, PHP 5)
snmp_set_valueretrieval -- Specify the method how the SNMP values will be returnedAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 3>= 3.0.8, PHP 4 , PHP 5)
snmprealwalk -- Restituisce tutti gli oggetti compresi i rispettivi ID di oggetto
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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.
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.
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 3>= 3.0.8, PHP 4 , PHP 5)
snmpwalkoid -- Richiesta dell'albero delle informazioni di una macchina di reteLa 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.
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.
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. |
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 .
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
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
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'.
|
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.
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
(PHP 4 >= 4.2.0, PHP 5)
socket_clear_error -- Azzera gli erorri di un socket, oppure l'ultimo codice d'erroreAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
(PHP 4 >= 4.1.0, PHP 5)
socket_create_listen -- Apre un socket per accettare connessioni su una portaAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
(PHP 4 >= 4.1.0, PHP 5)
socket_create_pair -- Crea una coppia di socket non distinguibili e li memorizza in una matrice.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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
Dominio | Descrizione |
---|---|
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
Tipo | Descrizione |
---|---|
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
Nome | Descrizione |
---|---|
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()
|
Esempio 2. Esempio di IPC con socket_create_pair()
|
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
Dominio | Descrizione |
---|---|
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
Tipo | Descrizione |
---|---|
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
Nome | Descrizione |
---|---|
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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
Opzione | Descrizione |
---|---|
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().
(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 socketAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
(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 socketAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0)
socket_iovec_alloc -- Costruice una struttura 'struct iovec' da utilizzare con sendmsg, recvmsg, writev, e readvAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0)
socket_iovec_fetch -- Restituisce i dati contenuti nella struttura iovec specificata da iovec_id[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. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0)
socket_iovec_set -- Valorizza i dati contenuti in iovec_id[iovec_position] con new_valAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
(PHP 4 >= 4.1.0)
socket_readv -- Legge da un fd, utilizzando un array invia/ricevi definito da iovec_idAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0)
socket_recvmsg -- Funzione usata per ricevere messaggi da un socket, a prescindere che sia orientato alla connessione o menoAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
socket_select -- Esegue la system call select() su un set di socket con un dato timeoutAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()
|
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:
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:
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
(PHP 4 >= 4.1.0)
socket_sendmsg -- Invia un messaggio ad un socket, a prescindere che sia orientato alla connessione o menoAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
socket_sendto -- Invia un messaggio ad un socket, a prescindere che sia connesso o menoAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()
|
Vedere anche socket_send() e socket_sendmsg().
The socket_set_block() function removes the O_NONBLOCK flag on the socket specified by the socket parameter.
Esempio 1. socket_set_block() example
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also socket_set_nonblock() and socket_set_option()
(PHP 4 >= 4.1.0, PHP 5)
socket_set_nonblock -- Attiva la modalità "nonblocking" per il descrittore di file fdAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche socket_set_block() e socket_set_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. |
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().
(PHP 4 >= 4.1.0, PHP 5)
socket_shutdown -- Chiude un socket in ricezione, in invio o in entrambi i sensi.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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:
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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()
Dall'esempio precedente (se non viene eseguito con i privilegi di root) ci si aspetta il seguente messaggio:
|
Vedere anche socket_accept(), socket_bind(), socket_connect(), socket_listen() e socket_create().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
(PHP 4 >= 4.1.0)
socket_writev -- Scrive su un descrittore di file, fd, usando un array invia/ricevi definito da iovec_idAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
SPL is a collection of interfaces and classes that are meant to solve standard problems.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
This function returns the current array entry
Esempio 1. ArrayIterator::current() example
The above example will output:
|
This function moves the iterator to the next entry.
Esempio 1. ArrayIterator::next() example
The above example will output:
|
(no version information, might be only in CVS)
ArrayIterator::rewind -- Rewind array back to the startThis function rewinds the iterator to the begining.
Esempio 1. ArrayIterator::rewind() example
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
ArrayIterator::valid -- Check whether array contains more entriesThis function checks if the array contains any more entries.
Esempio 1. ArrayIterator::valid() example
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
ArrayObject::__construct -- Construct a new array objectThis constructs a new array object. The input parameter accepts an array or another ArrayObject.
Esempio 1. ArrayObject::__construct() example
The above example will output:
|
(no version information, might be only in CVS)
ArrayObject::count -- Return the number of elements in the IteratorAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
ArrayObject::getIterator -- Create a new iterator from an ArrayObject instanceThis function will return an iterator from an ArrayObject.
Esempio 1. ArrayObject::getIterator() example
The above example will output:
|
(no version information, might be only in CVS)
ArrayObject::offsetExists -- Returns whether the requested $index existsAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
ArrayObject::offsetGet -- Returns the value at the specified $indexAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
ArrayObject::offsetSet -- Sets the value at the specified $index to $newvalAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
ArrayObject::offsetUnset -- Unsets the value at the specified $indexAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
CachingIterator::hasNext -- Cehck whether the inner iterator has a valid next elementAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
CachingIterator::__toString -- Retrun the string representation of the current elementAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
CachingIterator::valid -- Check whether the current element is validAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
CachingRecursiveIterator::getChildren -- Return the inenr iteraor's children as a CachingRecursiveIteratorAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
CachingRecursiveIterator::hasChildren -- Check whether the current element of the inner iterator has childrenAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DirectoryIterator::__construct -- Constructs a new dir iterator from a path.Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DirectoryIterator::current -- Return this (needed for Iterator interface)Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DirectoryIterator::fileATime -- Get last access time of fileAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DirectoryIterator::fileCTime -- Get inode modification time of fileAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DirectoryIterator::fileMTime -- Get last modification time of fileAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DirectoryIterator::getChildren -- Returns an iterator for the current entry if it is a directoryAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DirectoryIterator::getFilename -- Return filename of current dir entryAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DirectoryIterator::getPathname -- Return path and filename of current dir entryAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DirectoryIterator::isDir -- Returns true if file is directoryAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DirectoryIterator::isDot -- Returns true if current entry is '.' or '..'Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DirectoryIterator::isExecutable -- Returns true if file is executableAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DirectoryIterator::isFile -- Returns true if file is a regular fileAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DirectoryIterator::isLink -- Returns true if file is symbolic linkAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DirectoryIterator::isReadable -- Returns true if file can be readAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DirectoryIterator::isWritable -- Returns true if file can be writtenAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DirectoryIterator::rewind -- Rewind dir back to the startAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DirectoryIterator::valid -- Check whether dir contains more entriesAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
FilterIterator::current -- Get the current element valueAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
FilterIterator::getInnerIterator -- Get the inner iteratorAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
FilterIterator::valid -- Check whether the current element is validAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
LimitIterator::getPosition -- Return the current positionAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
LimitIterator::rewind -- Rewind the iterator to the specified starting offsetAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
LimitIterator::valid -- Check whether the current element is validAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
ParentIterator::getChildren -- Return the inner iterator's children contained in a ParentIteratorAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
ParentIterator::hasChildren -- Check whether the inner iterator's current element has childrenAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
RecursiveDirectoryIterator::getChildren -- Returns an iterator for the current entry if it is a directoryAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
RecursiveDirectoryIterator::hasChildren -- Returns whether current entry is a directory and not '.' or '..'Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
RecursiveDirectoryIterator::key -- Return path and filename of current dir entryAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
RecursiveDirectoryIterator::next -- Move to next entryAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
RecursiveDirectoryIterator::rewind -- Rewind dir back to the startAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
RecursiveIteratorIterator::current -- Access the current element valueAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
RecursiveIteratorIterator::getDepth -- Get the current depth of the recursive iterationAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
RecursiveIteratorIterator::getSubIterator -- The current active sub iteratorAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
RecursiveIteratorIterator::key -- Access the current keyAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
RecursiveIteratorIterator::next -- Move forward to the next elementAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
RecursiveIteratorIterator::rewind -- Rewind the iterator to the first element of the top level inner iterator.Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
RecursiveIteratorIterator::valid -- Check whether the current position is validAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
SimpleXMLIterator::current -- Return current SimpleXML entryAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
SimpleXMLIterator::getChildren -- Returns an iterator for the current entry if it is a SimpleXML objectAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
SimpleXMLIterator::hasChildren -- Returns whether current entry is a SimpleXML objectAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
SimpleXMLIterator::key -- Return current SimpleXML keyAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
SimpleXMLIterator::rewind -- Rewind SimpleXML back to the startAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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.
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().
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.
Streams are an integral part of PHP as of version 4.3.0. No steps are required to enable them.
User designed wrappers can be registered via stream_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.
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.
Constant | Description |
---|---|
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_PATH | Flag indicating if the stream used the include path. |
STREAM_REPORT_ERRORS | Flag indicating if the wrapper is responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors. |
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.
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.
Esempio 1. Using file_get_contents() to retrieve data from multiple sources
|
Esempio 2. Making a POST request to an https server
|
Esempio 3. Writing data to a compressed file
|
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()
|
See also stream_context_set_option(), and Listing of supported wrappers with context options (Appendice L).
Returns an array of options on the specified stream or context.
Sets an option on the specified context. value is set to option for wrapper
params should be an associative array of the structure: $params['paramname'] = "paramvalue";.
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
|
See also copy().
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
|
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().
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().
(PHP 5)
stream_filter_register -- Register a stream filter implemented as a PHP class derived from php_user_filterstream_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 Value | Meaning |
---|---|
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. |
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.
Property | Contents |
---|---|
FilterClass->filtername | A 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->params | The contents of the params parameter passed to stream_filter_append() or stream_filter_prepend(). |
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
Output
|
Esempio 2. Registering a generic filter class to match multiple filter names.
|
See also stream_wrapper_register(), stream_filter_prepend(), and stream_filter_append().
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().
Returns an indexed array containing the name of all stream filters available on the running system.
Esempio 1. Using stream_get_filters()
Output will be similar to the following. Note: there may be more or fewer filters in your version of PHP.
|
See also stream_filter_register(), and stream_get_wrappers().
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.
(PHP 4 >= 4.3.0, PHP 5)
stream_get_meta_data -- Retrieves header/meta data from streams/file pointersReturns 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.
Returns an indexed array containing the name of all socket transports available on the running system.
See also stream_get_filters(), and stream_get_wrappers().
Returns an indexed array containing the name of all stream wrappers available on the running system.
See also stream_wrapper_register().
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.
(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_usecThe 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().
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().
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.
Nota: As of PHP 4.3, this function can (potentially) work on any kind of stream. In PHP 4.3, socket based streams are still the only kind supported in the PHP core, although streams from other extensions may support this function.
This function was previously called as set_socket_timeout() and later socket_set_timeout() but this usage is deprecated.
See also fsockopen() and fopen().
Output using fwrite() is normally buffered at 8K. This means that if there are two processes wanting to write to the same output stream (a file), each is paused after 8K of data to allow the other to write. stream_set_write_buffer() sets the buffering for write operations on the given filepointer stream to buffer bytes. If buffer is 0 then write operations are unbuffered. This ensures that all writes with fwrite() are completed before other processes are allowed to write to that output stream.
The function returns 0 on success, or EOF if the request cannot be honored.
The following example demonstrates how to use stream_set_write_buffer() to create an unbuffered stream.
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.
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
|
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.
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().
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
|
See also stream_socket_sendto(), stream_socket_client(), and stream_socket_server().
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:
Esempio 1. stream_socket_sendto() Example
|
See also stream_socket_recvfrom(), stream_socket_client(), and stream_socket_server().
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
|
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
|
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() 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.
Flag | Description |
---|---|
STREAM_USE_PATH | If path is relative, search for the resource using the include_path. |
STREAM_REPORT_ERRORS | If this flag is set, you are responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors. |
If the path is opened successfully, and STREAM_USE_PATH is set in options, you should set opened_path to the full path of the file/resource that was actually opened.
If the requested resource was opened successfully, you should return TRUE, otherwise you should return FALSE
void stream_close ( void )This method is called when the stream is closed, using fclose(). You must release any resources that were locked or allocated by the stream.
string stream_read ( int count)This method is called in response to fread() and fgets() calls on the stream. You must return up-to count bytes of data from the current read/write position as a string. If there are less than count bytes available, return as many as are available. If no more data is available, return either FALSE or an empty string. You must also update the read/write position of the stream by the number of bytes that were successfully read.
int stream_write ( string data)This method is called in response to fwrite() calls on the stream. You should store data into the underlying storage used by your stream. If there is not enough room, try to store as many bytes as possible. You should return the number of bytes that were successfully stored in the stream, or 0 if none could be stored. You must also update the read/write position of the stream by the number of bytes that were successfully written.
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.
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.
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.
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.
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.
Flag | Description |
---|---|
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_QUIET | If 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. |
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
|
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.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Per 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.
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.
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. ?> |
Vedere anche stripcslashes(), stripslashes(), htmlspecialchars() e quotemeta().
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.
Vedere anche stripslashes(), htmlspecialchars(), quotemeta() e get_magic_quotes_gpc().
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.
Questa funzione è un alias di rtrim().
Nota: chop() è differente rispetto alla omonima funzione di Perl chop(), la quale rimuove l'ultimo carattere della stringa.
La funzione restituisce una stringa di un carattere contenente il carattere indicato come codifica ASCII nel parametro ascii.
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.
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.
Vedere anche str_split(), explode(), split(), wordwrap() e RFC 2045.
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
convert_cyr_string -- Converte da un set di caratteri Cirillico ad un'altroQuesta 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
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione 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()
Questo esempio visualizzerà:
|
Vedere anche strpos() e substr_count().
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():
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()
|
Vedere anche md5() e il modulo Mcrypt.
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()
|
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.
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
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()
|
Vedere anche preg_split(), spliti(), split() e implode().
Write a string produced according to the formatting string format to the stream resource specified by handle..
The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to fprintf(), sprintf(), and printf().
Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:
An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below.
An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified.
An optional number, a width specifier that says how many characters (minimum) this conversion should result in.
An optional precision specifier that says how many decimal digits should be displayed for floating-point numbers. This option has no effect for other types than float. (Another function useful for formatting numbers is number_format().)
A type specifier that says what type the argument data should be treated as. Possible types:
% - a literal percent character. No argument is required. |
b - the argument is treated as an integer, and presented as a binary number. |
c - the argument is treated as an integer, and presented as the character with that ASCII value. |
d - the argument is treated as an integer, and presented as a (signed) decimal number. |
u - the argument is treated as an integer, and presented as an unsigned decimal number. |
f - the argument is treated as a float, and presented as a floating-point number. |
o - the argument is treated as an integer, and presented as an octal number. |
s - the argument is treated as and presented as a string. |
x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters). |
X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters). |
See also: printf(), sprintf(), sscanf(), fscanf(), vsprintf(), and number_format().
Esempio 1. sprintf(): zero-padded integers
|
Esempio 2. sprintf(): formatting currency
|
(PHP 4 , PHP 5)
get_html_translation_table -- Returns the translation table used by htmlspecialchars() and htmlentities()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().
Another interesting use of this function is to, with help of array_flip(), change the direction of the translation.
The content of $original would be: "Hallo & <Frau> & Krämer".See also htmlspecialchars(), htmlentities(), strtr(), and array_flip().
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()
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()
(PHP 4 >= 4.3.0, PHP 5)
html_entity_decode -- Convert all HTML entities to their applicable charactershtml_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 Name | Description |
---|---|
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone. |
ENT_QUOTES | Will convert both double and single quotes. |
ENT_NOQUOTES | Will 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 caratteri | Alias | Descrizione |
---|---|---|
ISO-8859-1 | ISO8859-1 | Western European, Latin-1 |
ISO-8859-15 | ISO8859-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. | |
cp866 | ibm866, 866 | Set di caratteri cirillico specifico del Dos. Supportato dalla 4.3.2. |
cp1251 | Windows-1251, win-1251, 1251 | Set di caratteri cirillico specifico di Windows, Supportato dalla 4.3.2. |
cp1252 | Windows-1252, 1252 | Set di caratteri specifico di Windows per l'Europa occidentale. |
KOI8-R | koi8-ru, koi8r | Russo. Supportato dalla 4.3.2. |
BIG5 | 950 | Cinese tradizionale, usato principalmente a Taiwan. |
GB2312 | 936 | Cinese semplificato, set di caratteri nazionale standard. |
BIG5-HKSCS | Big5 con estensioni per Hong Kong, cinese tradizionale. | |
Shift_JIS | SJIS, 932 | Giapponese. |
EUC-JP | EUCJP | Giapponese. |
Nota: Ogni altro set di caratteri non è riconosciuto e sarà sostituito con con il set ISO-8859-1.
Esempio 1. Decoding HTML entities
|
Nota: You might wonder why trim(html_entity_decode(' ')); doesn't reduce the string to an empty string, that's because the ' ' 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().
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 Name | Description |
---|---|
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone. |
ENT_QUOTES | Will convert both double and single quotes. |
ENT_NOQUOTES | Will 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 caratteri | Alias | Descrizione |
---|---|---|
ISO-8859-1 | ISO8859-1 | Western European, Latin-1 |
ISO-8859-15 | ISO8859-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. | |
cp866 | ibm866, 866 | Set di caratteri cirillico specifico del Dos. Supportato dalla 4.3.2. |
cp1251 | Windows-1251, win-1251, 1251 | Set di caratteri cirillico specifico di Windows, Supportato dalla 4.3.2. |
cp1252 | Windows-1252, 1252 | Set di caratteri specifico di Windows per l'Europa occidentale. |
KOI8-R | koi8-ru, koi8r | Russo. Supportato dalla 4.3.2. |
BIG5 | 950 | Cinese tradizionale, usato principalmente a Taiwan. |
GB2312 | 936 | Cinese semplificato, set di caratteri nazionale standard. |
BIG5-HKSCS | Big5 con estensioni per Hong Kong, cinese tradizionale. | |
Shift_JIS | SJIS, 932 | Giapponese. |
EUC-JP | EUCJP | 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().
See also html_entity_decode(), get_html_translation_table(), htmlspecialchars(), nl2br(), and urlencode().
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 '&'
'"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
''' (single quote) becomes ''' only when ENT_QUOTES is set.
'<' (less than) becomes '<'
'>' (greater than) becomes '>'
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 caratteri | Alias | Descrizione |
---|---|---|
ISO-8859-1 | ISO8859-1 | Western European, Latin-1 |
ISO-8859-15 | ISO8859-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. | |
cp866 | ibm866, 866 | Set di caratteri cirillico specifico del Dos. Supportato dalla 4.3.2. |
cp1251 | Windows-1251, win-1251, 1251 | Set di caratteri cirillico specifico di Windows, Supportato dalla 4.3.2. |
cp1252 | Windows-1252, 1252 | Set di caratteri specifico di Windows per l'Europa occidentale. |
KOI8-R | koi8-ru, koi8r | Russo. Supportato dalla 4.3.2. |
BIG5 | 950 | Cinese tradizionale, usato principalmente a Taiwan. |
GB2312 | 936 | Cinese semplificato, set di caratteri nazionale standard. |
BIG5-HKSCS | Big5 con estensioni per Hong Kong, cinese tradizionale. | |
Shift_JIS | SJIS, 932 | Giapponese. |
EUC-JP | EUCJP | 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().
Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.
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.
(PHP 3>= 3.0.17, PHP 4 >= 4.0.1, PHP 5)
levenshtein -- Calculate Levenshtein distance between two stringsThis 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 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().
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 element | Description | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
decimal_point | Decimal point character | ||||||||||
thousands_sep | Thousands separator | ||||||||||
grouping | Array containing numeric groupings | ||||||||||
int_curr_symbol | International currency symbol (i.e. USD) | ||||||||||
currency_symbol | Local currency symbol (i.e. $) | ||||||||||
mon_decimal_point | Monetary decimal point character | ||||||||||
mon_thousands_sep | Monetary thousands separator | ||||||||||
mon_grouping | Array containing monetary groupings | ||||||||||
positive_sign | Sign for positive values | ||||||||||
negative_sign | Sign for negative values | ||||||||||
int_frac_digits | International fractional digits | ||||||||||
frac_digits | Local 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 |
| ||||||||||
n_sign_posn |
|
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
|
The constant CHAR_MAX is also defined for the use mentioned above.
See also setlocale().
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()
|
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().
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
See also crc32(), md5_file(), and sha1().
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() 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:
The character = followed by a a (single byte) character f to be used as the numeric fill character. The default fill character is space.
Disable the use of grouping characters (as defined by the current locale).
Specify the formatting style for positive and negative numbers. If + is used, the locale's equivalent for + and - will be used. If ( is used, negative amounts are enclosed in parenthesis. If no specification is given, the default is +.
Suppress the currency symbol from the output string.
If present, it will make all fields left-justified (padded to the right), as opposed to the default which is for the fields to be right-justified (padded to the left).
Field width.
A decimal digit string specifying a minimum field width. Field will be right-justified unless the flag - is used. Default value is 0 (zero).
Left precision.
The maximum number of digits (n) expected to the left of the decimal character (e.g. the decimal point). It is used usually to keep formatted output aligned in the same columns, using the fill character if the number of digits is less than n. If the number of actual digits is bigger than n, then this specification is ignored.
If grouping has not been suppressed using the ^ flag, grouping separators will be inserted before the fill characters (if any) are added. Grouping separators will not be applied to fill characters, even if the fill character is a digit.
To ensure alignment, any characters appearing before or after the number in the formatted output such as currency or sign symbols are padded as necessary with space characters to make their positive and negative formats an equal length.
Right precision .
A period followed by the number of digits (p) after the decimal character. If the value of p is 0 (zero), the decimal character and the digits to its right will be omitted. If no right precision is included, the default will dictated by the current local in use. The amount being formatted is rounded to the specified number of digits prior to formatting.
Conversion characters .
The number is formatted according to the locale's international currency format (e.g. for the USA locale: USD 1,234.56).
The number is formatted according to the locale's national currency format (e.g. for the de_DE locale: DM1.234,56).
Returns the % 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.
|
See also: setlocale(), number_format(),sprintf(), printf() and sscanf().
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
Constant | Description |
---|---|
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_STR | String for Ante meridian. |
PM_STR | String for Post meridian. |
D_T_FMT | String that can be used as the format string for strftime() to represent time and date. |
D_FMT | String that can be used as the format string for strftime() to represent date. |
T_FMT | String that can be used as the format string for strftime() to represent time. |
T_FMT_AMPM | String that can be used as the format string for strftime() to represent time in 12-hour format with ante/post meridian. |
ERA | Alternate era. |
ERA_YEAR | Year in alternate era format. |
ERA_D_T_FMT | Date and time in alternate era format (string can be used in strftime()). |
ERA_D_FMT | Date in alternate era format (string can be used in strftime()). |
ERA_T_FMT | Time in alternate era format (string can be used in strftime()). |
LC_MONETARY Category Constants | |
INT_CURR_SYMBOL | International currency symbol. |
CURRENCY_SYMBOL | Local currency symbol. |
CRNCYSTR | Same value as CURRENCY_SYMBOL. |
MON_DECIMAL_POINT | Decimal point character. |
MON_THOUSANDS_SEP | Thousands separator (groups of three digits). |
MON_GROUPING | Like 'grouping' element. |
POSITIVE_SIGN | Sign for positive values. |
NEGATIVE_SIGN | Sign for negative values. |
INT_FRAC_DIGITS | International fractional digits. |
FRAC_DIGITS | Local fractional digits. |
P_CS_PRECEDES | Returns 1 if CURRENCY_SYMBOL precedes a positive value. |
P_SEP_BY_SPACE | Returns 1 if a space separates CURRENCY_SYMBOL from a positive value. |
N_CS_PRECEDES | Returns 1 if CURRENCY_SYMBOL precedes a negative value. |
N_SEP_BY_SPACE | Returns 1 if a space separates CURRENCY_SYMBOL from a negative value. |
P_SIGN_POSN |
|
N_SIGN_POSN | |
LC_NUMERIC Category Constants | |
DECIMAL_POINT | Decimal point character. |
RADIXCHAR | Same value as DECIMAL_POINT. |
THOUSANDS_SEP | Separator character for thousands (groups of three digits). |
THOUSEP | Same value as THOUSANDS_SEP. |
GROUPING | |
LC_MESSAGES Category Constants | |
YESEXPR | Regex string for matching 'yes' input. |
NOEXPR | Regex string for matching 'no' input. |
YESSTR | Output string for 'yes'. |
NOSTR | Output string for 'no'. |
LC_CTYPE Category Constants | |
CODESET | Return a string with the name of the character encoding. |
Nota: Questa funzione non è implementata su piattaforme Windows
See also setlocale() and localeconv().
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 />'.
See also htmlspecialchars(), htmlentities(), wordwrap(), and str_replace().
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 :
|
Returns the ASCII value of the first character of string. This function complements chr().
You can find an ASCII-table over here: http://www.asciitable.com.
See also chr().
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.
See also parse_url(), pathinfo(), set_magic_quotes_runtime(), and urldecode().
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
|
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
Produces output according to format, which is described in the documentation for sprintf().
See also print(), sprintf(), vprintf(), sscanf(), fscanf(), and flush().
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
quoted_printable_decode -- Convert a quoted-printable string to an 8 bit stringThis 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.
Returns a version of str with a backslash character (\) before every character that is among these:
. \\ + * ? [ ^ ] ( $ ) |
See also addslashes(), htmlentities(), htmlspecialchars(), nl2br(), and stripslashes().
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()
|
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
|
Esempio 2. setlocale() Examples for Windows
|
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()
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
See also sha1_file(), crc32(), and md5()
This calculates the similarity between two strings as described in Oliver [1993]. Note that this implementation does not use a stack as in Oliver's pseudo code, but recursive calls which may or may not speed up the whole process. Note also that the complexity of this algorithm is O(N**3) where N is the length of the longest string.
By passing a reference as third argument, similar_text() will calculate the similarity in percent for you. It returns the number of matching chars in both strings.
Calculates the soundex key of str.
Soundex keys have the property that words pronounced similarly produce the same soundex key, and can thus be used to simplify searches in databases where you know the pronunciation but not the spelling. This soundex function returns a string 4 characters long, starting with a letter.
This particular soundex function is one described by Donald Knuth in "The Art Of Computer Programming, vol. 3: Sorting And Searching", Addison-Wesley (1973), pp. 391-392.
Esempio 1. Soundex Examples
|
See also levenshtein(), metaphone(), and similar_text().
Returns a string produced according to the formatting string format.
The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to both sprintf() and printf().
Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:
An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below.
An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified.
An optional number, a width specifier that says how many characters (minimum) this conversion should result in.
An optional precision specifier that says how many decimal digits should be displayed for floating-point numbers. This option has no effect for other types than float. (Another function useful for formatting numbers is number_format().)
A type specifier that says what type the argument data should be treated as. Possible types:
% - a literal percent character. No argument is required. |
b - the argument is treated as an integer, and presented as a binary number. |
c - the argument is treated as an integer, and presented as the character with that ASCII value. |
d - the argument is treated as an integer, and presented as a (signed) decimal number. |
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:
See also printf(), sscanf(), fscanf(), vsprintf(), and number_format().
The function sscanf() is the input analog of printf(). sscanf() reads from the string str and interprets it according to the specified format. If only two parameters were passed to this function, the values parsed will be returned as an array.
Any whitespace in the format string matches any whitespace in the input string. This means that even a tab \t in the format string can match a single space character in the input string.
Esempio 1. sscanf() Example
|
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.
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().
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.
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.
Returns input_str repeated multiplier times. multiplier has to be greater than or equal to 0. If the multiplier is set to 0, the function will return an empty string.
This will output "-=-=-=-=-=-=-=-=-=-=".
See also for, str_pad(), and substr_count().
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
str_replace -- Replace all occurrences of the search string with the replacement stringThis 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
|
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().
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.
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() shuffles a string. One permutation of all possible is created.
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()
Output may look like:
|
See also chunk_split(), preg_split(), split(), count_chars(), str_word_count(), and for.
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()
Output may look like:
|
See also explode(), preg_split(), split(), count_chars(), and substr_count().
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
See also ereg(), strcmp(), substr(), stristr(), strncasecmp(), and strstr().
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().
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().
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().
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. |
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().
Returns a string with backslashes stripped off. Recognizes C-like \n, \r ..., octal and hexadecimal representation.
See also addcslashes().
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
|
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().
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.
See also addslashes() and get_magic_quotes_gpc().
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.
(PHP 4 , PHP 5)
strnatcasecmp -- Case insensitive string comparisons using a "natural order" algorithmThis 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().
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); ?> |
Standard string comparison Array ( [0] => img1.png [1] => img10.png [2] => img12.png [3] => img2.png ) Natural order string comparison Array ( [0] => img1.png [1] => img2.png [2] => img10.png [3] => img12.png ) |
Similar to other string comparison functions, this one returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
Note that this comparison is case sensitive.
See also ereg(), strcasecmp(), substr(), stristr(), strcmp(), strncmp(), strncasecmp(), strnatcasecmp(), strstr(), natsort() and natcasesort().
(PHP 4 >= 4.0.2, PHP 5)
strncasecmp -- Binary safe case-insensitive string comparison of the first n charactersThis function is similar to strcasecmp(), with the difference that you can specify the (upper limit of the) number of characters (len) from each string to be used in the comparison.
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
See also ereg(), strcasecmp(), strcmp(), substr(), stristr(), and strstr().
This function is similar to strcmp(), with the difference that you can specify the (upper limit of the) number of characters (len) from each string to be used in the comparison.
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() 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.
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
|
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().
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.
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
Outputs:
|
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().
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().
Returns the length of the initial segment of str1 which consists entirely of characters in str2.
The line of code:
will assign 2 to $var, because the string "42" will be the longest segment containing characters from "1234567890".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 strcspn().
Returns part of haystack string from the first occurrence of needle to the end of haystack.
If needle is not found, returns FALSE.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
Nota: This function is case-sensitive. For case-insensitive searches, use stristr().
Nota: If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.
See also ereg(), preg_match(), stristr(), strpos(), strrchr(), and substr().
strtok() splits a string (arg1) into smaller strings (tokens), with each token being delimited by any character from arg2. That is, if you have a string like "This is an example string" you could tokenize this string into its individual words by using the space character as the token.
Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string. To start over, or to tokenize a new string you simply call strtok with the string argument again to initialize it. Note that you may put multiple tokens in the token parameter. The string will be tokenized when any one of the characters in the argument are found.
The behavior when an empty part was found changed with PHP 4.1.0. The old behavior returned an empty string, while the new, correct, behavior simply skips the part of the string:
Also be careful that your tokens may be equal to "0". This evaluates to FALSE in conditional expressions.
Returns string with all alphabetic characters converted to lowercase.
Note that 'alphabetic' is determined by the current locale. This means that in i.e. the default "C" locale, characters such as umlaut-A (Ä) will not be converted.
See also strtoupper(), ucfirst(), ucwords() and mb_strtolower().
Returns string with all alphabetic characters converted to uppercase.
Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.
See also strtolower(), ucfirst(), ucwords() and mb_strtoupper().
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.
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.
Nota: This optional to and from parameters were added in PHP 4.0.0
See also ereg_replace().
(PHP 5)
substr_compare -- Binary safe optionally case insensitive comparison of 2 strings from an offset, up to length characterssubstr_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
|
substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.
See also count_chars(), strpos(), substr(), and strstr().
substr_replace() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement. The result is returned.
If start is positive, the replacing will begin at the start'th offset into string.
If start is negative, the replacing will begin at the start'th character from the end of string.
If length is given and is positive, it represents the length of the portion of string which is to be replaced. If it is negative, it represents the number of characters from the end of string at which to stop replacing. If it is not given, then it will default to strlen( string ); i.e. end the replacing at the end of string.
Esempio 1. substr_replace() example
|
See also str_replace() and substr().
substr() returns the portion of string specified by the start and length parameters.
If start is non-negative, the returned string will start at the start'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth.
Esempio 1. Basic substr() usage
|
If start is negative, the returned string will start at the start'th character from the end of string.
If length is given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of string). If string is less than 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.
See also strrchr(), substr_replace(), ereg(), trim(), mb_substr() and wordwrap().
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()
|
Nota: The optional charlist parameter was added in PHP 4.1.0
Returns a string with the first character of str capitalized, if that character is alphabetic.
Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.
See also strtolower(), strtoupper(), and ucwords().
Returns a string with the first character of each word in str capitalized, if that character is alphabetic.
The definition of a word is any string of characters that is immediately after a whitespace (These are: space, form-feed, newline, carriage return, horizontal tab, and vertical tab).
See also strtoupper(), strtolower() and ucfirst().
Display array values as a formatted string according to format (which is described in the documentation for sprintf()).
Operates as printf() but accepts an array of arguments, rather than a variable number of arguments.
See also printf(), sprintf(), vsprintf()
Return array values as a formatted string according to format (which is described in the documentation for sprintf()).
Operates as sprintf() but accepts an array of arguments, rather than a variable number of arguments.
(PHP 4 >= 4.0.2, PHP 5)
wordwrap -- Wraps a string to a given number of characters using a string break character.Returns a string with str wrapped at the column number specified by the optional width parameter. The line is broken using the (optional) break parameter.
wordwrap() will automatically wrap at column 75 and break using '\n' (newline) if width or break are not given.
If the cut is set to 1, the string is always wrapped at the specified width. So if you have a word that is larger than the given width, it is broken apart. (See second example).
Nota: The optional cut parameter was added in PHP 4.0.3
See also nl2br() and chunk_split().
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.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Sybase configuration options
Name | Default | Changeable |
---|---|---|
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.
Whether to allow persistent Sybase connections.
The maximum number of persistent Sybase connections per process. -1 means no limit.
The maximum number of Sybase connections per process, including persistent connections. -1 means no limit.
Minimum error severity to display.
Minimum message severity to display.
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.
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
Name | Default | Changeable |
---|---|---|
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.hostname | NULL | PHP_INI_ALL |
sybct.deadlock_retry_count | "-1" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
Whether to allow persistent Sybase-CT connections. The default is on.
The maximum number of persistent Sybase-CT connections per process. The default is -1 meaning unlimited.
The maximum number of Sybase-CT connections per process, including persistent connections. The default is -1 meaning unlimited.
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.
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.
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.
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.
The name of the host you claim to be connecting from, for display by sp_who. The default is none.
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().
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
The above example would produce the following output:
|
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() 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().
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().
See also sybase_pconnect() and sybase_close().
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().
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.
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
The above example would produce the following output (assuming the two tables only have each one column called "person_id"):
|
See also sybase_fetch_row(), sybase_fetch_assoc() and sybase_fetch_object().
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().
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().
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:
New behaviour:
object(stdclass)(3) { [0]=> string(3) "foo" ["foo"]=> string(3) "foo" [1]=> string(3) "bar" ["bar"]=> string(3) "bar" }
object(stdclass)(3) { ["foo"]=> string(3) "foo" ["bar"]=> string(3) "bar" }
Speed-wise, the function is identical to sybase_fetch_array(), and almost as quick as sybase_fetch_row() (the difference is insignificant).
See also sybase_fetch_array() and sybase_fetch_row().
Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
sybase_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
Subsequent call to sybase_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.
Tabella 1. Data types
PHP | Sybase |
---|---|
string | VARCHAR, TEXT, CHAR, IMAGE, BINARY, VARBINARY, DATETIME |
int | NUMERIC (w/o precision), DECIMAL (w/o precision), INT, BIT, TINYINT, SMALLINT |
float | NUMERIC (w/ precision), DECIMAL (w/ precision), REAL, FLOAT, MONEY |
NULL | NULL |
See also sybase_fetch_array(), sybase_fetch_assoc(), sybase_fetch_object(), sybase_data_seek() and sybase_result().
Seeks to the specified field offset. If the next call to sybase_fetch_field() won't include a field offset, this field would be returned.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also sybase_fetch_field().
sybase_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script ends. You may call sybase_free_result() with the result identifier as an argument and the associated result memory will be freed.
sybase_get_last_message() returns the last message reported by the server.
See also sybase_min_message_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() 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() 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() 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() returns the number of fields in a result set.
See also sybase_query(), sybase_fetch_field() and sybase_num_rows().
sybase_num_rows() returns the number of rows in a result set.
See also sybase_num_fields(), sybase_query() and sybase_fetch_row().
Returns a positive Sybase persistent link identifier on success, or FALSE on error.
sybase_pconnect() acts very much like sybase_connect() with two major differences.
First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (sybase_close() will not close links established by sybase_pconnect()()).
This type of links is therefore called 'persistent'.
See also sybase_connect().
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().
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() 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()
(PHP 4 >= 4.3.0, PHP 5)
sybase_set_message_handler -- Sets the handler called when a server message is raisedsybase_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 3. sybase_set_message_handler() unhandled messages
|
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
|
See also sybase_query().
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.
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:
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.
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.
To use Tidy, you will need libtidy installed, available on the tidy homepage http://tidy.sourceforge.net/.
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:
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.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Tidy Configuration Options
Name | Default | Changeable | Function |
---|---|---|---|
tidy.default_config | "" | PHP_INI_SYSTEM | default path for tidy config file |
tidy.clean_output | 0 | PHP_INI_PERDIR | turns on/off the output repairing by Tidy |
Avvertimento |
Do not turn on tidy.clean_output if you are generating non-html content such as dynamic images. |
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
constant | description |
---|---|
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
constant | description |
---|---|
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 |
ob_tidyhandler() is intended to be used as a callback function for ob_start() to repair the buffer.
See also ob_start().
(PHP 5)
tidy_access_count -- Returns the Number of Tidy accessibility warnings encountered for specified document.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
|
See also tidy_error_count() and tidy_warning_count().
Procedural style:
bool tidy_clean_repair ( resource tidy)Object oriented style:
bool tidy->cleanRepair ( void )This function cleans and repairs the given tidy resource.
See also tidy_repair_file() and tidy_repair_string().
(PHP 5)
tidy_config_count -- Returns the Number of Tidy configuration errors encountered for specified document.tidy_config_count() returns the number of errors encountered in the given configuration.
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
The above example will output:
|
See also tidy_parse_file() and tidy_parse_string().
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() returns the number of Tidy errors encountered for the specified document.
Esempio 1. tidy_error_count() example
The above example will output:
|
See also tidy_access_count() and tidy_warning_count().
(PHP 5)
tidy_get_body -- Returns a TidyNode Object starting from the <body> tag of the tidy parse treeProcedural 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.
Nota: Questa funzione è disponibile solo con Zend Engine 2, ciò implica PHP >= 5.0.0.
See also tidy_get_head() and tidy_get_html().
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
The above example will output:
|
See also tidy_reset_config() and tidy_save_config().
(PHP 5)
tidy_get_error_buffer -- Return warnings and errors which occurred parsing the specified documentObject oriented style (property):
class tidy {tidy_get_error_buffer() returns warnings and errors which occurred parsing the specified document.
Esempio 1. tidy_get_error_buffer() example
The above example will output:
|
See also tidy_access_count(), tidy_error_count() and tidy_warning_count().
(PHP 5)
tidy_get_head -- Returns a TidyNode Object starting from the <head> tag of the tidy parse treeProcedural 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.
Nota: Questa funzione è disponibile solo con Zend Engine 2, ciò implica PHP >= 5.0.0.
See also tidy_get_body() and tidy_get_html().
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. |
(PHP 5)
tidy_get_html -- Returns a TidyNode Object starting from the <html> tag of the tidy parse treeProcedural 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
The above example will output:
|
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() returns a string with the repaired html.
Esempio 1. tidy_get_output() example
The above example will output:
|
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.
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.
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.
(PHP 5)
tidy_getopt -- Returns the value of the specified configuration option for the tidy document.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
The above example will output:
|
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. |
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. |
(no version information, might be only in CVS)
tidy_load_config -- Load an ASCII Tidy configuration file with the specified encodingThis 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.
(no version information, might be only in CVS)
tidy_node->attributes -- Returns an array of attribute objects for nodeAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
tidy_node->children -- Returns an array of child nodesAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
tidy_node->get_attr -- Return the attribute with the provided attribute idAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
tidy_node->get_nodes -- Return an array of nodes under this node with the specified idAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
tidy_node->hasChildren -- Returns true if this node has childrenAvvertimento |
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.
(no version information, might be only in CVS)
tidy_node->hasSiblings -- Returns true if this node has siblingsAvvertimento |
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.
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.
(no version information, might be only in CVS)
tidy_node->isComment -- Returns true if this node represents a commentAvvertimento |
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.
(no version information, might be only in CVS)
tidy_node->isHtml -- Returns true if this node is part of a HTML documentAvvertimento |
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.
(no version information, might be only in CVS)
tidy_node->isJste -- Returns true if this node is JSTEAvvertimento |
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.
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.
(no version information, might be only in CVS)
tidy_node->isText -- Returns true if this node represents text (no markup)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.
(no version information, might be only in CVS)
tidy_node->isXhtml -- Returns true if this node is part of a XHTML documentAvvertimento |
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.
(no version information, might be only in CVS)
tidy_node->isXml -- Returns true if this node is part of a XML documentAvvertimento |
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.
(no version information, might be only in CVS)
tidy_node->next -- Returns the next sibling to this nodeAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
tidy_node->prev -- Returns the previous sibling to this nodeAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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.
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().
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
The above example will output:
|
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().
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.
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().
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
The above example will output:
|
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().
(no version information, might be only in CVS)
tidy_reset_config -- Restore Tidy configuration to default valuesThis 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.
(no version information, might be only in CVS)
tidy_save_config -- Save current settings to named file. Only non-default values are written.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.
(no version information, might be only in CVS)
tidy_set_encoding -- Set the input/output character encoding for parsing markup.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.
(no version information, might be only in CVS)
tidy_setopt -- Updates the configuration settings for the specified tidy document.tidy_setopt() updates the specified option with a new value.
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.
(PHP 5)
tidy_warning_count -- Returns the Number of Tidy warnings encountered for specified document.tidy_warning_count() returns the number of Tidy warnings encountered for the specified document.
See also tidy_access_count() and tidy_error_count().
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.
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.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Nota: T_ML_COMMENT is not defined in PHP 5. All comments in PHP 5 are of token T_COMMENT.
Nota: T_DOC_COMMENT was introduced in PHP 5.
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
|
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
|
token_name() returns the symbolic name for a PHP token value. The symbolic name returned matches the name of the matching token constant.
See also List of Parser Tokens.
Dealing with URL strings: encoding, decoding and parsing.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
base64_decode() decodes encoded_data and returns the original data or FALSE on failure. The returned data may be binary.
See also base64_encode() and RFC 2045 section 6.8.
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.
See also base64_decode(), chunk_split(), convert_uuencode() and RFC 2045 section 6.8.
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
The above example will output something like:
|
(PHP 3>= 3.0.4, PHP 4 , PHP 5)
get_meta_tags -- Extracts all meta tag content attributes from a file and returns an arrayOpens filename and parses it line by line for <meta> tags in the file. This can be a local file or an URL. The parsing stops at </head>.
Setting use_include_path to 1 will result in PHP trying to open the file along the standard include path as per the include_path directive. This is used for local files, not URLs.
The value of the name property becomes the key, the value of the content property becomes the value of the returned array, so you can easily use standard array functions to traverse it or access single values. Special characters in the value of the name property are substituted with '_', the rest is converted to lower case. If two meta tags have the same name, only the last one is returned.
Esempio 2. What get_meta_tags() returns
|
Nota: As of PHP 4.0.5, get_meta_tags() supports unquoted HTML attributes.
See also htmlentities() and urlencode().
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 2. http_build_query() with numerically index elements.
|
Esempio 3. http_build_query() with complex arrays
this will output : (word wrapped for readability)
|
See also: parse_str(), parse_url(), urlencode(), and array_walk()
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
|
See also pathinfo(), parse_str(), dirname(), and basename().
Returns a string in which the sequences with percent (%) signs followed by two hex digits have been replaced with literal characters.
Nota: rawurldecode() does not decode plus symbols ('+') into spaces. urldecode() does.
See also rawurlencode(), urldecode() and urlencode().
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:
Or, if you pass information in a PATH_INFO component of the URL:
See also rawurldecode(), urldecode(), urlencode() and RFC 1738.
Decodes any %## encoding in the given string. The decoded string is returned.
See also urlencode(), rawurlencode() and rawurldecode().
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:
Note: Be careful about variables that may match HTML entities. Things like &, © and £ 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 & 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
|
See also urldecode(), htmlentities(), rawurldecode() and rawurlencode().
Per maggiori informazioni sul comportamento delle variabili vedere la sezione Variabili nel capitolo Riferimento al Linguaggio del manuale.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Configurazioni per il modulo Variabili
Nome | Default | Modificabile |
---|---|---|
unserialize_callback_func | "" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
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().
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.
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().
|
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.
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 .
(PHP 4 >= 4.0.4, PHP 5)
get_defined_vars -- Restituisce un'array contenente tutte le variabili definiteQuesta 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().
Questa funzione restituisce una stringa rappresentante il tipo di risorsa passato. Se il parametro passato non è una risorsa valida la funzione genera un errore.
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().
(PHP 4 >= 4.1.0, PHP 5)
import_request_variables -- Imposta la visibiltà a globale per le variabili GET/POST/CookieImposta 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().
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.
Restituisce TRUE se var è un array, FALSE in caso contrario.
Vedere anche is_float(), is_int(), is_integer(), is_string() e is_object().
Restituisce TRUE se var è di tipo boolean.
Vedere anche is_array(), is_float(), is_int(), is_integer(), is_string(), and is_object().
(PHP 4 >= 4.0.6, PHP 5)
is_callable -- Verifica se il contenuto dell'argomento può essere eseguito come funzioneVerifica 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 ?> |
(PHP 3, PHP 4 , PHP 5)
is_float -- Verifica se una variabile è di tipo float (decimale a virgola mobile)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(),
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().
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().
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().
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_resource() restituisce TRUE se la variabile individuata dal parametro var è di tipo resource, altrimenti restituisce FALSE.
Per maggiori dettagli fare riferimento alla documentazione di resource-type
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().
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().
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 @.
(PHP 4 , PHP 5)
print_r -- Stampa informazioni relative al contenuto di una variabile in formato leggibileNota: 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).
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().
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()
|
Vedere anche: unserialize().
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.
Vedere anche gettype(), Casting del tipo e Manipolazione del tipo.
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.
(PHP 3>= 3.0.5, PHP 4 , PHP 5)
unserialize -- Crea un valore PHP a partire da una rappresentazione archiviataLa 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.
|
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()
|
Vedere anche: serialize().
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.
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; ?> |
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"; ?> |
Se si usa unset() su una variabile statica all'interno di una funzione, unset() cancella la variabile e tutti i suoi riferimenti.
L'esempio precedente visualizzerà:Se si desidera cancellare una variabile globale dall'interno di una funzione, occorre usare unset() sull'array $GLOBALS nel seguente modo:
Nota: Poichè questo è un costrutto del linguaggio e non una funzione, non può essere chiamato con le variabili funzione
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.
Vedere anche var_export() e print_r().
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().
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.
In PHP 4, queste funzioni sono disponibili soltanto se il PHP viene configurato con --with-vpopmail[=DIR].
(4.0.5 - 4.2.3 only)
vpopmail_add_alias_domain_ex -- Aggiunge un alias ad un esistente dominio virtualeAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.0.5 - 4.2.3 only)
vpopmail_auth_user -- Tenta di validare un nome utente/dominio/password. Restituisce true/falseAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.0.5 - 4.2.3 only)
vpopmail_error -- Riceve il messaggio testuale dell'ultimo errore di vpopmail. Restituisce stringAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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. |
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Questo modulo definisce un solo tipo di risorsa utilizzata per i tipi di dati definiti dall'utente. Il nome i questa risorsa è "dynaparm".
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.
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
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.
(4.2.0 - 4.2.3 only)
w32api_init_dtype -- Crea un'istanza ai tipi di dati typename e li riempie con i valori fornitiAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.
(4.2.0 - 4.2.3 only)
w32api_invoke_function -- ....) Invoca la funzione funcname con gli argomenti passati dopo il nome della funzioneAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
(4.2.0 - 4.2.3 only)
w32api_register_function -- Registra la funzione function_name dalla libreria con PHPAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.
These functions are intended for work with WDDX.
In order to use WDDX, you will need to install the expat library (which comes with Apache 1.3.7 or higher).
After installing expat compile PHP with --enable-wddx.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
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 2. Using incremental packets with WDDX
This example will produce:
|
Nota: If you want to serialize non-ASCII characters you have to set the appropriate locale before doing so (see setlocale()).
wddx_add_vars() is used to serialize passed variables and add the result to the packet specified by the packet_id. The variables to be serialized are specified in exactly the same way as wddx_serialize_vars().
wddx_deserialize() takes a packet string and deserializes it. It returns the result which can be string, number, or array. Note that structures are deserialized into associative arrays.
wddx_packet_end() ends the WDDX packet specified by the packet_id and returns the string with the packet.
(PHP 3>= 3.0.7, PHP 4 , PHP 5)
wddx_packet_start -- Starts a new WDDX packet with structure inside itUse wddx_packet_start() to start a new WDDX packet for incremental addition of variables. It takes an optional comment string and returns a packet ID for use in later functions. It automatically creates a structure definition inside the packet to contain the variables.
wddx_serialize_value() is used to create a WDDX packet from a single given value. It takes the value contained in var, and an optional comment string that appears in the packet header, and returns the WDDX packet.
wddx_serialize_vars() is used to create a WDDX packet with a structure that contains the serialized representation of the passed variables.
wddx_serialize_vars() takes a variable number of arguments, each of which can be either a string naming a variable or an array containing strings naming the variables or another array, etc.
The above example will produce:
<wddxPacket version='1.0'><header/><data><struct><var name='a'><number>1</number></var> <var name='b'><number>5.5</number></var><var name='c'><array length='3'> <string>blue</string><string>orange</string><string>violet</string></array></var> <var name='d'><string>colors</string></var></struct></data></wddxPacket> |
XML (eXtensible Markup Language) è 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.
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 $@ |
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.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
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.
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.
I gestori di eventi XML definiti sono:
Tabella 1. Gestori XML supportati
Funzione PHP per attivare il gestore | Descrizione 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. |
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().
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 |
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.
Di seguito verranno illustrati alcuni esempi di script PHP per il parsing di documenti XML.
Il primo esempio visualizza, con indentazione, la struttura degli elementi di apertura di un documento.
Esempio 1. Visualizza la struttura degli elementi 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:
|
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
|
Esempio 4. xmltest.xml
|
Questo file è stato richiamato da xmltest.xml:
(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.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.
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:
Ciascuna b rappresenta un bit che può essere utilizzato per registrare le informazioni del carattere.
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.
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
xml_get_current_byte_index -- Restituisce il corrente indice di posizione per un parser XML
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).
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
xml_get_current_column_number -- Restituisce il numero di colonna corrente di un parser XML
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.
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
xml_get_current_line_number -- Restituisce il numero di linea corrente da un parser XML
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.
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().
(PHP 3>= 3.0.8, PHP 4 , PHP 5)
xml_parse_into_struct -- Analisi di dati XML in una struttura a matriceQuesta 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()
Eseguendo questo codice si otterrà:
|
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
|
Esempio 3. parsemoldb.php - analizza moldb.xml e genera una matrice di oggetti molecole
|
Il riferimento al parser XML da utilizzare.
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.
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().
(PHP 4 >= 4.0.5, PHP 5)
xml_parser_create_ns -- Crea un parser XML con il supporto dello spazio dei nomiLa 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().
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().
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
Riferimento al parser XML da cui ottenere l'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.
Riferimento al parser XML di cui si vuole valorizzare l'opzione,
Quale opzione valorizzare. Vedere più avanti.
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'opzione | tipo di dato | Descrizione |
---|---|---|
XML_OPTION_CASE_FOLDING | integer | Controlla se il case-folding è abilitato per questo parser XML. Abilitato per default. |
XML_OPTION_TARGET_ENCODING | string | 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. |
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)
Il primo parametro, parser, è un riferimento al parser XML chiamante il gestore.
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.
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)
Il primo parametro, parser, è un riferimento al parser XML chiamante il gestore.
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.
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
xml_set_element_handler -- Valorizza i gestori di inizio e fine elementoLa 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)
Il primo parametro, parser, è il riferimento al parser XML chiamante il gestore.
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.
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)
Il primo parametro, parser, è il riferimento al parser XML chiamante il gestore.
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.
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.
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
xml_set_external_entity_ref_handler -- Valorizza il gestore dei riferimenti a entità esterneIndica 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)
Il primo parametro, parser, è il riferimento al parser XML chiamante il gestore.
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)
Questa è la base per la risoluzione dell'identificatore system (systemid) delle entità esterne. Attualmente questo parametro è sempre valorizzato con una stringa vuota.
Il quarto parametro, system_id, è l'identificatore system come specificato nella dichiarazione dell'entità.
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.
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
xml_set_notation_decl_handler -- Valorizza il gestore delle dichiarazione delle notazioniIndica 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>?> |
La funzione indicata da gestore deve accettare
cinque parametri:
gestore ( resource parser, string nome_notazione, string base, string system_id, string public_id)
Il primo parametro, parser, è il riferimento al parser XML chiamante il gestore.
Questo è il parametro name della notazione, come dal formato descritto in precedenza.
Questa è la base per la risoluzione dell'identificatore system (system_id) delle entità esterne. Attualmente questo parametro è sempre valorizzato con una stringa vuota.
Identificatore system della dichiarazione della notazione esterna.
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.
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>"); ?> |
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
xml_set_processing_instruction_handler -- Indica il gestore delle istruzioni di processo (PI)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:
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)
Il primo parametro, parser, è il riferimento al parser XML chiamante il gestore.
Il secondo parametro, target, contiene la PI target.
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.
(PHP 4 >= 4.0.5, PHP 5)
xml_set_start_namespace_decl_handler -- Valorizza il gestore dei caratteri di dati
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.
(PHP 3>= 3.0.6, PHP 4 , PHP 5)
xml_set_unparsed_entity_decl_handler -- Valorizza il gestore delle dichiarazioni di entità non analizzateIndica 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)
Il primo parametro, parser, è il riferimento al parser XML chiamante il gestore.
Il nome dell'entità che sta per essere definita.
Questa è la base per la risoluzione dell'identificatore system (systemid) delle entità esterne. Attualmente questo parametro è sempre valorizzato con una stringa vuota.
Identificatore system per l'entità esterna.
Identificatore public per l'entità esterna.
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.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
xmlrpc_get_type -- Riceve il tipo di xmlrpc per un valore PHP. Maggiormente ì usato per le stringhe base64 e datetimeAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
xmlrpc_parse_method_descriptions -- Decodifica XML in una lista di method descriptionsAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
xmlrpc_server_add_introspection_data -- Aggiunge documentazione introspettivaAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
xmlrpc_server_call_method -- Struttura le richieste XML e i metodi di chiamataAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
xmlrpc_server_register_introspection_callback -- Registra una funzione PHP per generare la documentazioneAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
xmlrpc_server_register_method -- Registra una funzione PHP nel metodo di risorsa abbinato method_nameAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
xmlrpc_set_type -- Imposta il tipo di xmlrpc, base64 o datetime, per un valore di stringa PHPAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
xdiff extension creates and applies patches to both text and binary files.
To use xdiff, you will need libxdiff installed, available on the libxdiff homepage http://www.xmailserver.org/xdiff-lib.html.
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:
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.
(no version information, might be only in CVS)
xdiff_file_diff_binary -- Make binary diff of two files.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() 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() 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().
(no version information, might be only in CVS)
xdiff_file_patch_binary -- Patch a file with a binary diff.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().
(no version information, might be only in CVS)
xdiff_file_patch -- Patch a file with an unified diff.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().
(no version information, might be only in CVS)
xdiff_string_diff_binary -- Make binary diff of two strings.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().
(no version information, might be only in CVS)
xdiff_string_diff -- Make unified diff of two strings.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() 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().
(no version information, might be only in CVS)
xdiff_string_patch_binary -- Patch a string with a binary diff.xdiff_string_patch_binary() patches string str with binary patch in string patch.
Returns a patched string.
See also xdiff_file_patch_binary().
(no version information, might be only in CVS)
xdiff_string_patch -- Patch a string with an unified diff.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().
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.
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.
In this small tutorial we will learn how to transform an XML document into HTML.
Esempio 1. A simple XSL tree
|
Esempio 3. Making XML into HTML The following PHP code uses the XML and XSL extensions to transform XML into presentable HTML.
This should produce an HTML fragment similar to the following:
|
Procedural style
bool xsl_xsltprocessor_get_parameter ( string namespace, string name)Object oriented style (method)
class xsltprocessor {Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
xsl_xsltprocessor_has_exslt_support -- Determine if PHP has EXSLT supportProcedural style
bool xsl_xsltprocessor_has_exslt_support ( void )Object oriented style (method)
class xsltprocessor {Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.
Procedural style
bool xsl_xsltprocessor_import_stylesheet ( node index)Object oriented style (method)
class xsltprocessor {Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
xsl_xsltprocessor_register_php_functions -- Enables the ability to use PHP functions as XSLT functionsProcedural style
void xsl_xsltprocessor_register_php_functions ( void )Object oriented style (method)
class xsltprocessor {Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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.
Procedural style
bool xsl_xsltprocessor_remove_parameter ( string namespace, string name)Object oriented style (method)
class xsltprocessor {Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Procedural style
bool xsl_xsltprocessor_set_parameter ( string namespace, string name, string value)Object oriented style (method)
class xsltprocessor {Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Procedural style
bool >xsl_xsltprocessor_transform_to_doc ( node doc [, bool clone])Object oriented style (method)
class xsltprocessor {Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Procedural style
bool xsl_xsltprocessor_transform_to_uri ( node doc, string uri [, bool clone])Object oriented style (method)
class xsltprocessor {Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Procedural style
bool xsl_xsltprocessor_transform_to_xml ( node doc [, bool clone])Object oriented style (method)
class xsltprocessor {Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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.
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.
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.
(PHP 4 >= 4.3.0)
xslt_backend_info -- Returns the information on the compilation settings of the backendxslt_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() will always return Sablotron.
See also xslt_backend_info() and xslt_backend_version().
xslt_backend_version() returns the version number of Sablotron if available, FALSE otherwise.
See also xslt_backend_name() and xslt_backend_info().
Crea e restituisce un nuovo processore XSLT risorsa per la modifica dalle altre funzioni XSLT.
Restituisce un codice di errore che descrive l'ultimo errore successo sul processore XSLT indicato.
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().
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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
|
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
|
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
|
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">.
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.
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.
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).
Un riferimento all'XSLT parser.
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:
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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 ) |
(PHP 4 >= 4.0.6)
xslt_set_sax_handlers -- Imposta gli handler SAX da richiamare quando il document XML viene processato
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.0.5 - 4.0.6 only)
xslt_set_scheme_handler -- Imposta lo schema dell'handler per un processore XSLTImposta 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):
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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.
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:
If you are using YAZ as a shared extension, add (or uncomment) the following line in php.ini on Unix:
extension=php_yaz.so |
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.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. YAZ configuration options
Name | Default | Changeable |
---|---|---|
yaz.max_links | "100" | PHP_INI_ALL |
yaz.log_file | "" | PHP_INI_ALL |
PHP/YAZ keeps track of connections with targets (Z-Associations). A resource represents a connection to a target.
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
|
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().
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.
|
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.
|
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.
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
Username for authentication.
Group for authentication.
Password for authentication.
Cookie for session (YAZ proxy).
Proxy for connection (YAZ proxy).
A boolean. If TRUE the connection is persistent; If FALSE the connection is not persistent. By default connections are persistent.
A boolean. If TRUE piggyback is enabled for searches; If FALSE piggyback is disabled. By default piggyback is enabled. Enabling piggyback is more efficient and usually saves a network-round-trip for first time fetches of records. However, a few Z39.50 servers do not support piggyback or they ignore element set names. For those, piggyback should be disabled.
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.
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.
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.
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().
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().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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.
This function prepares for an Extended Services request using the Profile for the Use of Z39.50 Item Order Extended Service to Transport ILL (Profile/1). See this and the specification. The args parameter must be a hash array with information about the Item Order request to be sent. The key of the hash is the name of the corresponding ASN.1 tag path. For example, the ISBN below the Item-ID has the key item-id,ISBN.
The ILL-Request parameters are:
protocol-version-num
transaction-id,initial-requester-id,person-or-institution-symbol,person
transaction-id,initial-requester-id,person-or-institution-symbol,institution
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-person
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-institution
transaction-id,transaction-group-qualifier
transaction-id,transaction-qualifier
transaction-id,sub-transaction-qualifier
service-date-time,this,date
service-date-time,this,time
service-date-time,original,date
service-date-time,original,time
requester-id,person-or-institution-symbol,person
requester-id,person-or-institution-symbol,institution
requester-id,name-of-person-or-institution,name-of-person
requester-id,name-of-person-or-institution,name-of-institution
responder-id,person-or-institution-symbol,person
responder-id,person-or-institution-symbol,institution
responder-id,name-of-person-or-institution,name-of-person
responder-id,name-of-person-or-institution,name-of-institution
transaction-type
delivery-address,postal-address,name-of-person-or-institution,name-of-person
delivery-address,postal-address,name-of-person-or-institution,name-of-institution
delivery-address,postal-address,extended-postal-delivery-address
delivery-address,postal-address,street-and-number
delivery-address,postal-address,post-office-box
delivery-address,postal-address,city
delivery-address,postal-address,region
delivery-address,postal-address,country
delivery-address,postal-address,postal-code
delivery-address,electronic-address,telecom-service-identifier
delivery-address,electronic-address,telecom-service-addreess
billing-address,postal-address,name-of-person-or-institution,name-of-person
billing-address,postal-address,name-of-person-or-institution,name-of-institution
billing-address,postal-address,extended-postal-delivery-address
billing-address,postal-address,street-and-number
billing-address,postal-address,post-office-box
billing-address,postal-address,city
billing-address,postal-address,region
billing-address,postal-address,country
billing-address,postal-address,postal-code
billing-address,electronic-address,telecom-service-identifier
billing-address,electronic-address,telecom-service-addreess
ill-service-type
requester-optional-messages,can-send-RECEIVED
requester-optional-messages,can-send-RETURNED
requester-optional-messages,requester-SHIPPED
requester-optional-messages,requester-CHECKED-IN
search-type,level-of-service
search-type,need-before-date
search-type,expiry-date
search-type,expiry-flag
place-on-hold
client-id,client-name
client-id,client-status
client-id,client-identifier
item-id,item-type
item-id,call-number
item-id,author
item-id,title
item-id,sub-title
item-id,sponsoring-body
item-id,place-of-publication
item-id,publisher
item-id,series-title-number
item-id,volume-issue
item-id,edition
item-id,publication-date
item-id,publication-date-of-component
item-id,author-of-article
item-id,title-of-article
item-id,pagination
item-id,ISBN
item-id,ISSN
item-id,additional-no-letters
item-id,verification-reference-source
copyright-complicance
retry-flag
forward-flag
requester-note
forward-note
There are also a few parameters that are part of the Extended Services Request package and the ItemOrder package:
package-name
user-id
contact-name
contact-phone
contact-email
itemorder-item
This function prepares for retrieval of records after a successful search. The yaz_range() should be called prior to this function to specify the range of records to be retrieved.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
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.
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.
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.
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.
The syntax of the record is returned as a string, i.e. USmarc, GRS-1, XML, etc.
The name of database associated with record at the position is returned as a string.
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
If this record is present at position $p, then
|
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).
The record $rec can be processed with the Sablotron XSLT processor as follows:
For PHP5 the XSL extension can be used instead of Sablotron XSLT. |
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).
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
|
The schema must be specified as an OID (Object Identifier) in a raw dot-notation (like 1.2.840.10003.13.4) or as one of the known registered schemas: GILS-schema, Holdings, Zthes, ... This function should be called before yaz_search() or yaz_present().
yaz_search() prepares for a search on the connection given by 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 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
Construct | Description |
---|---|
@and query1 query2 | intersection of query1 and query2 |
@or query1 query2 | union of query1 and query2 |
@not query1 query2 | query1 and not query2 |
@set name | result set reference |
@attrset set query | specifies attribute-set for query. This construction is only allowed once - in the beginning of the whole query |
@attr [set] type=value query | applies attribute to query. The type and value are integers specifying the attribute-type and attribute-value respectively. The set, if given, specifies the attribute-set. |
Esempio 1. Query Examples You can search for simple terms, like this
The Query
This query applies two attributes for the same phrase.
This query
Another, more complex, one:
|
You can find information about attributes at the Z39.50 Maintenance Agency site.
Nota: If you would like to use a more friendly notation, use the CCL parser - functions yaz_ccl_conf() and yaz_ccl_parse().
Sets option name to value.
Tabella 1. PYP/YAZ Connection Options
Name | Description |
---|---|
implementationName | implementation name of server |
implementationVersion | implementation version of server |
implementationId | implementation ID of server |
schema | schema for retrieval. By default, no schema is used. Setting this option is equivalent to using function yaz_schema() |
preferredRecordSyntax | record syntax for retrieval. By default, no syntax is used. Setting this option is equivalent to using function yaz_syntax() |
start | offset for first record to be retrieved via yaz_search() or yaz_present(). First record is numbered has a start value of 0. Second record has start value 1. Setting this option in combination with option count has the same effect as calling yaz_range() except that records are numbered from 1 in yaz_range() |
count | maximum number of records to be retrieved via yaz_search() or yaz_present(). |
elementSetName | element-set-name for retrieval. Setting this option is equivalent to calling yaz_element(). |
This function sets sorting criteria and enables Z39.50 Sort. Call this function before yaz_search(). Using this function alone 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
Sort ascending
Sort descending
Case insensitive sorting
Case sensitive sorting
The syntax must be specified as an OID (Object Identifier) in a raw dot-notation (like 1.2.840.10003.5.10) or as one of the known registered record syntaxes (sutrs, usmarc, grs1, xml, etc.). This function should be called before yaz_search() or yaz_present().
This function carries out networked (blocked) activity for outstanding requests which have been prepared by the functions yaz_connect(), yaz_search(), yaz_present(), yaz_scan() and yaz_itemorder(). yaz_wait() returns when all 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().
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.
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.
None besides functions from standard Unix libraries which are always available (either libc or libnsl, configure will detect which one to use).
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
yp_cat() returns all map entries as an array with the maps key values as array indices and the maps entries as array data.
(PHP 4 >= 4.0.6, PHP 5)
yp_err_string -- Returns the error string associated with the given error codeyp_err_string() returns the error message associated with the given error code. Useful to indicate what exactly went wrong.
See also yp_errno().
yp_errno() returns the error code of the previous operation.
Possible errors are:
1 args to function are bad |
2 RPC failure - domain has been unbound |
3 can't bind to server on this domain |
4 no such map in server's domain |
5 no such key in map |
6 internal yp server or client error |
7 resource allocation failure |
8 no more records in map database |
9 can't communicate with portmapper |
10 can't communicate with ypbind |
11 can't communicate with ypserv |
12 local domain name not set |
13 yp database is bad |
14 yp version mismatch |
15 access violation |
16 database busy |
See also yp_err_string().
yp_first() returns the first key-value pair from the named map in the named domain, otherwise FALSE.
See also yp_next() and yp_get_default_domain().
yp_get_default_domain() returns the default domain of the node or FALSE. Can be used as the domain parameter for successive NIS calls.
A NIS domain can be described a group of NIS maps. Every host that needs to look up information binds itself to a certain domain. Refer to the documents mentioned at the beginning for more detailed information.
(PHP 3>= 3.0.7, PHP 4 , PHP 5)
yp_master -- Returns the machine name of the master NIS server for a mapyp_master() returns the machine name of the master NIS server for a map.
See also yp_get_default_domain().
yp_match() returns the value associated with the passed key out of the specified map or FALSE. This key must be exact.
See also yp_get_default_domain().
yp_next() returns the next key-value pair in the named map after the specified key or FALSE.
See also yp_first() and yp_get_default_domain().
yp_order() returns the order number for a map or FALSE.
See also yp_get_default_domain().
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.
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
|
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().
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().
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().
(PHP 4 >= 4.1.0)
zip_entry_compressionmethod -- Ottiene il metodo di compressione di una voce directoryRestituisce 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().
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().
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().
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().
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().
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().
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().
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à.
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.
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.
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
Nome | Default | Configurabile in |
---|---|---|
zlib.output_compression | "Off" | PHP_INI_ALL |
zlib.output_compression_level | "-1" | PHP_INI_ALL |
zlib.output_handler | "" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
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.
Livello di compressione utilizzato per la compressione trasparente dell'output.
Non si possino specificare ulteriori handler dell'output se zlib.output_compression è attivo. Questa impostazione è come output_handler ma con un ordine differente.
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.
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
|
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().
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().
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().
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:
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().
Returns TRUE if the gz-file pointer is at EOF or an error occurs; otherwise returns FALSE.
The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().
Identical to readgzfile(), except that gzfile() returns the file in an array.
You can use the optional second parameter and set it to "1", if you want to search for the file in the include_path, too.
See also readgzfile(), and gzopen().
Returns a string containing a single (uncompressed) character read from the file pointed to by zp. Returns FALSE on EOF (unlike gzeof()).
The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().
Returns a (uncompressed) string of up to length - 1 bytes read from the file pointed to by fp. Reading ends when length - 1 bytes have been read, on a newline, or on EOF (whichever comes first).
If an error occurs, returns FALSE.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
Identical to gzgets(), except that gzgetss() attempts to strip any HTML and PHP tags from the text it reads.
You can use the optional third parameter to specify tags which should not be stripped.
Nota: Allowable_tags was added in PHP 3.0.13, PHP 4.0b3.
See also gzgets(), gzopen(), and strip_tags().
This function takes data compressed by gzdeflate() and returns the original uncompressed data or FALSE on error. The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input data or more than the optional parameter length.
See also gzcompress(). gzuncompress(), gzdeflate(), and gzencode().
Opens a gzip (.gz) file for reading or writing. The mode parameter is as in fopen() ("rb" or "wb") but can also include a compression level ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman only compression as in "wb1h". (See the description of deflateInit2 in zlib.h for more information about the strategy parameter.)
gzopen() can be used to read a file which is not in gzip format; in this case gzread() will directly read from the file without decompression.
gzopen() returns a file pointer to the file opened, after that, everything you read from this file descriptor will be transparently decompressed and what you write gets compressed.
If the open fails, the function returns FALSE.
You can use the optional third parameter and set it to "1", if you want to search for the file in the include_path, too.
See also gzclose().
Reads to EOF on the given gz-file pointer and writes the (uncompressed) results to standard output.
If an error occurs, returns FALSE.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
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.
See also gzwrite(), gzopen(), gzgets(), gzgetss(), gzfile(), and gzpassthru().
Sets the file position indicator for zp to the beginning of the file stream.
If an error occurs, returns 0.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
Sets the file position indicator for the file referenced by zp to offset bytes into the file stream. Equivalent to calling (in C) gzseek(zp, offset, SEEK_SET).
If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek then compresses a sequence of zeroes up to the new starting position.
Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.
See also gztell() and gzrewind().
Returns the position of the file pointer referenced by zp; i.e., its offset into the file stream.
If an error occurs, returns FALSE.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
See also gzopen(), gzseek() and gzrewind().
This function takes data compressed by gzcompress() and returns the original uncompressed data or FALSE on error. The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input data or more than the optional parameter length.
See also gzdeflate(), gzinflate(), gzcompress(), gzencode().
gzwrite() writes the contents of string to the gz-file stream pointed to by zp. If the length argument is given, writing will stop after length (uncompressed) bytes have been written or the end of string is reached, whichever comes first.
gzwrite() returns the number of (uncompressed) bytes written to the gz-file stream pointed to by zp.
Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.
Reads a file, decompresses it and writes it to standard output.
readgzfile() can be used to read a file which is not in gzip format; in this case readgzfile() will directly read from the file without decompression.
Returns the number of (uncompressed) bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readgzfile, an error message is printed.
The file filename will be opened from the filesystem and its contents written to standard output.
You can use the optional second parameter and set it to "1", if you want to search for the file in the include_path, too.
See also gzpassthru(), gzfile(), and gzopen().
Returns the coding type used for output compression. Possible return values are gzip, deflate, or FALSE
See also the zlib.output_compression directive.
Sometimes, PHP "as is" simply isn't enough. Although these cases are rare for the average user, professional applications will soon lead PHP to the edge of its capabilities, in terms of either speed or functionality. New functionality cannot always be implemented natively due to language restrictions and inconveniences that arise when having to carry around a huge library of default code appended to every single script, so another method needs to be found for overcoming these eventual lacks in PHP.
As soon as this point is reached, it's time to touch the heart of PHP and take a look at its core, the C code that makes PHP go.
"Extending PHP" is easier said than done. PHP has evolved to a full-fledged tool consisting of a few megabytes of source code, and to hack a system like this quite a few things have to be learned and considered. When structuring this chapter, we finally decided on the "learn by doing" approach. This is not the most scientific and professional approach, but the method that's the most fun and gives the best end results. In the following sections, you'll learn quickly how to get the most basic extensions to work almost instantly. After that, you'll learn about Zend's advanced API functionality. The alternative would have been to try to impart the functionality, design, tips, tricks, etc. as a whole, all at once, thus giving a complete look at the big picture before doing anything practical. Although this is the "better" method, as no dirty hacks have to be made, it can be very frustrating as well as energy- and time-consuming, which is why we've decided on the direct approach.
Note that even though this chapter tries to impart as much knowledge as possible about the inner workings of PHP, it's impossible to really give a complete guide to extending PHP that works 100% of the time in all cases. PHP is such a huge and complex package that its inner workings can only be understood if you make yourself familiar with it by practicing, so we encourage you to work with the source.
The name Zend refers to the language engine, PHP's core. The term PHP refers to the complete system as it appears from the outside. This might sound a bit confusing at first, but it's not that complicated (see Figura 26-1). To implement a Web script interpreter, you need three parts:
The interpreter part analyzes the input code, translates it, and executes it.
The functionality part implements the functionality of the language (its functions, etc.).
The interface part talks to the Web server, etc.
The following sections discuss where PHP can be extended and how it's done.
As shown in Figura 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 can be loaded at script runtime using the function dl(). This function loads a shared object from disk and makes its functionality available to the script to which it's being bound. After the script is terminated, the external module is discarded from memory. This method has both advantages and disadvantages, as described in the following table:
Advantages | Disadvantages |
External modules don't require recompiling of PHP. | The shared objects need to be loaded every time a script is being executed (every hit), which is very slow. |
The size of PHP remains small by "outsourcing" certain functionality. | External additional files clutter up the disk. |
Every script that wants to use an external module's functionality has to specifically include a call to dl(), or the extension tag in php.ini needs to be modified (which is not always a suitable solution). |
Third parties might consider using the extension tag in php.ini to create additional external modules to PHP. These external modules are completely detached from the main package, which is a very handy feature in commercial environments. Commercial distributors can simply ship disks or archives containing only their additional modules, without the need to create fixed and solid PHP binaries that don't allow other modules to be bound to them.
Built-in modules are compiled directly into PHP and carried around with every PHP process; their functionality is instantly available to every script that's being run. Like external modules, built-in modules have advantages and disadvantages, as described in the following table:
Built-in modules are best when you have a solid library of functions that remains relatively unchanged, requires better than poor-to-average performance, or is used frequently by many scripts on your site. The need to recompile PHP is quickly compensated by the benefit in speed and ease of use. However, built-in modules are not ideal when rapid development of small additions is required.Of course, extensions can also be implemented directly in the Zend engine. This strategy is good if you need a change in the language behavior or require special functions to be built directly into the language core. In general, however, modifications to the Zend engine should be avoided. Changes here result in incompatibilities with the rest of the world, and hardly anyone will ever adapt to specially patched Zend engines. Modifications can't be detached from the main PHP sources and are overridden with the next update using the "official" source repositories. Therefore, this method is generally considered bad practice and, due to its rarity, is not covered in this book.
Nota: Prior to working through the rest of this chapter, you should retrieve clean, unmodified source trees of your favorite Web server. We're working with Apache (available at http://www.apache.org/) and, of course, with PHP (available at http://www.php.net/ - does it need to be said?).
Make sure that you can compile a working PHP environment by yourself! We won't go into this issue here, however, as you should already have this most basic ability when studying this chapter.
Before we start discussing code issues, you should familiarize yourself with the source tree to be able to quickly navigate through PHP's files. This is a must-have ability to implement and debug extensions.
The following table describes the contents of the major directories.
Directory | Contents |
php4 | Main PHP source files and main header files; here you'll find all of PHP's API definitions, macros, etc. (important). Everything else is below this directory. |
php4/ext | Repository for dynamic and built-in modules; by default, these are the "official" PHP modules that have been integrated into the main source tree. From PHP 4.0, it's possible to compile these standard extensions as dynamic loadable modules (at least, those that support it). |
php4/main | This directory contains the main php macros and definitions. (important) |
php4/pear | Directory for the PHP Extension and Application Repository. This directory contains core PEAR files. |
php4/sapi | Contains the code for the different server abstraction layers. |
php4/TSRM | Location of the "Thread Safe Resource Manager" (TSRM) for Zend and PHP. |
php4/Zend | Location of the Zend Engine files; here you'll find all of Zend's API definitions, macros, etc. (important). |
Discussing all the files included in the PHP package is beyond the scope of this chapter. However, you should take a close look at the following files:
php4/main/php.h, located in the main PHP directory. This file contains most of PHP's macro and API definitions.
php4/Zend/zend.h, located in the main Zend directory. This file contains most of Zend's macros and definitions.
php4/Zend/zend_API.h, also located in the Zend directory, which defines Zend's API.
Zend is built using certain conventions; to avoid breaking its standards, you should follow the rules described in the following sections.
For almost every important task, Zend ships predefined macros that are extremely handy. The tables and figures in the following sections describe most of the basic functions, structures, and macros. The macro definitions can be found mainly in zend.h and zend_API.h. We suggest that you take a close look at these files after having studied this chapter. (Although you can go ahead and read them now, not everything will make sense to you yet.)
Resource management is a crucial issue, especially in server software. One of the most valuable resources is memory, and memory management should be handled with extreme care. Memory management has been partially abstracted in Zend, and you should stick to this abstraction for obvious reasons: Due to the abstraction, Zend gets full control over all memory allocations. Zend is able to determine whether a block is in use, automatically freeing unused blocks and blocks with lost references, and thus prevent memory leaks. The functions to be used are described in the following table:
Function | Description |
emalloc() | Serves as replacement for malloc(). |
efree() | Serves as replacement for free(). |
estrdup() | Serves as replacement for strdup(). |
estrndup() | Serves as replacement for strndup(). Faster than estrdup() and binary-safe. This is the recommended function to use if you know the string length prior to duplicating it. |
ecalloc() | Serves as replacement for calloc(). |
erealloc() | Serves as replacement for realloc(). |
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. |
The following directory and file functions should be used in Zend modules. They behave exactly like their C counterparts, but provide virtual working directory support on the thread level.
Strings are handled a bit differently by the Zend engine than other values such as integers, Booleans, etc., which don't require additional memory allocation for storing their values. If you want to return a string from a function, introduce a new string variable to the symbol table, or do something similar, you have to make sure that the memory the string will be occupying has previously been allocated, using the aforementioned e*() functions for allocation. (This might not make much sense to you yet; just keep it somewhere in your head for now - we'll get back to it shortly.)
Complex types such as arrays and objects require different treatment. Zend features a single API for these types - they're stored using hash tables.
Nota: To reduce complexity in the following source examples, we're only working with simple types such as integers at first. A discussion about creating more advanced types follows later in this chapter.
PHP 4 features an automatic build system that's very flexible. All modules reside in a subdirectory of the ext directory. In addition to its own sources, each module consists of a config.m4 file, for extension configuration. (for example, see http://www.gnu.org/manual/m4/html_mono/m4.html)
All these stub files are generated automatically, along with .cvsignore, by a little shell script named ext_skel that resides in the ext directory. As argument it takes the name of the module that you want to create. The shell script then creates a directory of the same name, along with the appropriate stub files.
Step by step, the process looks like this:
:~/cvs/php4/ext:> ./ext_skel --extname=my_module Creating directory my_module Creating basic files: config.m4 .cvsignore my_module.c php_my_module.h CREDITS EXPERIMENTAL tests/001.phpt my_module.php [done]. To use your new extension, you will have to execute the following steps: 1. $ cd .. 2. $ vi ext/my_module/config.m4 3. $ ./buildconf 4. $ ./configure --[with|enable]-my_module 5. $ make 6. $ ./php -f ext/my_module/my_module.php 7. $ vi ext/my_module/my_module.c 8. $ make Repeat steps 3-6 until you are satisfied with ext/my_module/config.m4 and step 6 confirms that your module is compiled into PHP. Then, start writing code and repeat the last two steps as often as necessary. |
The default config.m4 shown in Esempio 29-1 is a bit more complex:
Esempio 29-1. The default config.m4.
|
If you're unfamiliar with M4 files (now is certainly a good time to get familiar), this might be a bit confusing at first; but it's actually quite easy.
Note: Everything prefixed with dnl is treated as a comment and is not parsed.
The config.m4 file is responsible for parsing the command-line options passed to configure at configuration time. This means that it has to check for required external files and do similar configuration and setup tasks.
The default file creates two configuration directives in the configure script: --with-my_module and --enable-my_module. Use the first option when referring external files (such as the --with-apache directive that refers to the Apache directory). Use the second option when the user simply has to decide whether to enable your extension. Regardless of which option you use, you should uncomment the other, unnecessary one; that is, if you're using --enable-my_module, you should remove support for --with-my_module, and vice versa.
By default, the config.m4 file created by ext_skel accepts both directives and automatically enables your extension. Enabling the extension is done by using the PHP_EXTENSION macro. To change the default behavior to include your module into the PHP binary when desired by the user (by explicitly specifying --enable-my_module or --with-my_module), change the test for $PHP_MY_MODULE to == "yes":
if test "$PHP_MY_MODULE" == "yes"; then dnl Action.. PHP_EXTENSION(my_module, $ext_shared) fi |
Note: Be sure to run buildconf every time you change config.m4!
We'll go into more details on the M4 macros available to your configuration scripts later in this chapter. For now, we'll simply use the default files.
We'll start with the creation of a very simple extension at first, which basically does nothing more than implement a function that returns the integer it receives as parameter. Esempio 30-1 shows the source.
Esempio 30-1. A simple extension.
|
This code contains a complete PHP module. We'll explain the source code in detail shortly, but first we'd like to discuss the build process. (This will allow the impatient to experiment before we dive into API discussions.)
Nota: The example source makes use of some features introduced with the Zend version used in PHP 4.1.0 and above, it won't compile with older PHP 4.0.x versions.
There are basically two ways to compile modules:
Use the provided "make" mechanism in the ext directory, which also allows building of dynamic loadable modules.
Compile the sources manually.
The second method is good for those who (for some reason) don't have the full PHP source tree available, don't have access to all files, or just like to juggle with their keyboard. These cases should be extremely rare, but for the sake of completeness we'll also describe this method.
Compiling Using Make. To compile the sample sources using the standard mechanism, copy all their subdirectories to the ext directory of your PHP source tree. Then run buildconf, which will create an updated configure script containing appropriate options for the new extension. By default, all the sample sources are disabled, so you don't have to fear breaking your build process.
After you run buildconf, configure --help shows the following additional modules:
--enable-array_experiments BOOK: Enables array experiments --enable-call_userland BOOK: Enables userland module --enable-cross_conversion BOOK: Enables cross-conversion module --enable-first_module BOOK: Enables first module --enable-infoprint BOOK: Enables infoprint module --enable-reference_test BOOK: Enables reference test module --enable-resource_test BOOK: Enables resource test module --enable-variable_creation BOOK: Enables variable-creation module |
The module shown earlier in 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:
The command to compile the module simply instructs the compiler to generate position-independent code (-fpic shouldn't be omitted) and additionally defines the constant COMPILE_DL to tell the module code that it's compiled as a dynamically loadable module (the test module above checks for this; we'll discuss it shortly). After these options, it specifies a number of standard include paths that should be used as the minimal set to compile the source files.Note: All include paths in the example are relative to the directory ext. If you're compiling from another directory, change the pathnames accordingly. Required items are the PHP directory, the Zend directory, and (if necessary), the directory in which your module resides.
The link command is also a plain vanilla command instructing linkage as a dynamic module.
You can include optimization options in the compilation command, although these have been omitted in this example (but some are included in the makefile template described in an earlier section).
Note: Compiling and linking manually as a static module into the PHP binary involves very long instructions and thus is not discussed here. (It's not very efficient to type all those commands.)
Depending on the build process you selected, you should either end up with a new PHP binary to be linked into your Web server (or run as CGI), or with an .so (shared object) file. If you compiled the example file first_module.c as a shared object, your result file should be first_module.so. To use it, you first have to copy it to a place from which it's accessible to PHP. For a simple test procedure, you can copy it to your htdocs directory and try it with the source in 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. |
Calling this PHP file in your Web browser should give you the output shown in Figura 31-1.
If required, the dynamic loadable module is loaded by calling the dl() function. This function looks for the specified shared object, loads it, and makes its functions available to PHP. The module exports the function first_module(), which accepts a single parameter, converts it to an integer, and returns the result of the conversion.
If you've gotten this far, congratulations! You just built your first extension to PHP.
Actually, not much troubleshooting can be done when compiling static or dynamic modules. The only problem that could arise is that the compiler will complain about missing definitions or something similar. In this case, make sure that all header files are available and that you specified their path correctly in the compilation command. To be sure that everything is located correctly, extract a clean PHP source tree and use the automatic build in the ext directory with the fresh files; this will guarantee a safe compilation environment. If this fails, try manual compilation.
PHP might also complain about missing functions in your module. (This shouldn't happen with the sample sources if you didn't modify them.) If the names of external functions you're trying to access from your module are misspelled, they'll remain as "unlinked symbols" in the symbol table. During dynamic loading and linkage by PHP, they won't resolve because of the typing errors - there are no corresponding symbols in the main binary. Look for incorrect declarations in your module file or incorrectly written external references. Note that this problem is specific to dynamic loadable modules; it doesn't occur with static modules. Errors in static modules show up at compile time.
Now that you've got a safe build environment and you're able to include the modules into PHP files, it's time to discuss how everything works.
All PHP modules follow a common structure:
Header file inclusions (to include all required macros, API definitions, etc.)
C declaration of exported functions (required to declare the Zend function block)
Declaration of the Zend function block
Declaration of the Zend module block
Implementation of get_module()
Implementation of all exported functions
The only header file you really have to include for your modules is php.h, located in the PHP directory. This file makes all macros and API definitions required to build new modules available to your code.
Tip: It's good practice to create a separate header file for your module that contains module-specific definitions. This header file should contain all the forward definitions for exported functions and include php.h. If you created your module using ext_skel you already have such a header file prepared.
To declare functions that are to be exported (i.e., made available to PHP as new native functions), Zend provides a set of macros. A sample declaration looks like this:
ZEND_FUNCTION ( my_function ); |
ZEND_FUNCTION declares a new C function that complies with Zend's internal API. This means that the function is of type void and accepts INTERNAL_FUNCTION_PARAMETERS (another macro) as parameters. Additionally, it prefixes the function name with zif. The immediately expanded version of the above definitions would look like this:
void zif_my_function ( INTERNAL_FUNCTION_PARAMETERS ); |
void zif_my_function( int ht , zval * return_value , zval * this_ptr , int return_value_used , zend_executor_globals * executor_globals ); |
Since the interpreter and executor core have been separated from the main PHP package, a second API defining macros and function sets has evolved: the Zend API. As the Zend API now handles quite a few of the responsibilities that previously belonged to PHP, a lot of PHP functions have been reduced to macros aliasing to calls into the Zend API. The recommended practice is to use the Zend API wherever possible, as the old API is only preserved for compatibility reasons. For example, the types zval and pval are identical. zval is Zend's definition; pval is PHP's definition (actually, pval is an alias for zval now). As the macro INTERNAL_FUNCTION_PARAMETERS is a Zend macro, the above declaration contains zval. When writing code, you should always use zval to conform to the new Zend API.
The parameter list of this declaration is very important; you should keep these parameters in mind (see Tabella 33-1 for descriptions).
Tabella 33-1. Zend's Parameters to Functions Called from PHP
Parameter | Description |
ht | The number of arguments passed to the Zend function. You should not touch this directly, but instead use ZEND_NUM_ARGS() to obtain the value. |
return_value | This variable is used to pass any return values of your function back to PHP. Access to this variable is best done using the predefined macros. For a description of these see below. |
this_ptr | Using this variable, you can gain access to the object in which your function is contained, if it's used within an object. Use the function getThis() to obtain this pointer. |
return_value_used | This flag indicates whether an eventual return value from this function will actually be used by the calling script. 0 indicates that the return value is not used; 1 indicates that the caller expects a return value. Evaluation of this flag can be done to verify correct usage of the function as well as speed optimizations in case returning a value requires expensive operations (for an example, see how array.c makes use of this). |
executor_globals | This variable points to global settings of the Zend engine. You'll find this useful when creating new variables, for example (more about this later). The executor globals can also be introduced to your function by using the macro TSRMLS_FETCH(). |
Now that you have declared the functions to be exported, you also have to introduce them to Zend. Introducing the list of functions is done by using an array of zend_function_entry. This array consecutively contains all functions that are to be made available externally, with the function's name as it should appear in PHP and its name as defined in the C source. Internally, zend_function_entry is defined as shown in Esempio 33-1.
Esempio 33-1. Internal declaration of zend_function_entry.
|
zend_function_entry firstmod_functions[] = { ZEND_FE(first_module, NULL) {NULL, NULL, NULL} }; |
Nota: You cannot use the predefined macros for the end marker, as these would try to refer to a function named "NULL"!
The macro ZEND_FE (short for 'Zend Function Entry') simply expands to a structure entry in zend_function_entry. Note that these macros introduce a special naming scheme to your functions - your C functions will be prefixed with zif_, meaning that ZEND_FE(first_module) will refer to a C function zif_first_module(). If you want to mix macro usage with hand-coded entries (not a good practice), keep this in mind.
Tip: Compilation errors that refer to functions named zif_*() relate to functions defined with ZEND_FE.
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 Name | Description |
ZEND_FE(name, arg_types) | Defines a function entry of the name name in zend_function_entry. Requires a corresponding C function. arg_types needs to be set to NULL. This function uses automatic C function name generation by prefixing the PHP function name with zif_. For example, ZEND_FE("first_module", NULL) introduces a function first_module() to PHP and links it to the C function zif_first_module(). Use in conjunction with ZEND_FUNCTION. |
ZEND_NAMED_FE(php_name, name, arg_types) | Defines a function that will be available to PHP by the name php_name and links it to the corresponding C function name. arg_types needs to be set to NULL. Use this function if you don't want the automatic name prefixing introduced by ZEND_FE. Use in conjunction with ZEND_NAMED_FUNCTION. |
ZEND_FALIAS(name, alias, arg_types) | Defines an alias named alias for name. arg_types needs to be set to NULL. Doesn't require a corresponding C function; refers to the alias target instead. |
PHP_FE(name, arg_types) | Old PHP API equivalent of ZEND_FE. |
PHP_NAMED_FE(runtime_name, name, arg_types) | Old PHP API equivalent of ZEND_NAMED_FE. |
Note: You can't use ZEND_FE in conjunction with PHP_FUNCTION, or PHP_FE in conjunction with ZEND_FUNCTION. However, it's perfectly legal to mix ZEND_FE and ZEND_FUNCTION with PHP_FE and PHP_FUNCTION when staying with the same macro set for each function to be declared. But mixing is not recommended; instead, you're advised to use the ZEND_* macros only.
This block is stored in the structure zend_module_entry and contains all necessary information to describe the contents of this module to Zend. You can see the internal definition of this module in Esempio 33-2.
Esempio 33-2. Internal declaration of zend_module_entry.
|
In our example, this structure is implemented as follows:
zend_module_entry firstmod_module_entry = { STANDARD_MODULE_HEADER, "First Module", firstmod_functions, NULL, NULL, NULL, NULL, NULL, NO_VERSION_YET, STANDARD_MODULE_PROPERTIES, }; |
For reference purposes, you can find a list of the macros involved in declared startup and shutdown functions in 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
Macro | Description |
ZEND_MINIT(module) | Declares a function for module startup. The generated name will be zend_minit_<module> (for example, zend_minit_first_module). Use in conjunction with ZEND_MINIT_FUNCTION. |
ZEND_MSHUTDOWN(module) | Declares a function for module shutdown. The generated name will be zend_mshutdown_<module> (for example, zend_mshutdown_first_module). Use in conjunction with ZEND_MSHUTDOWN_FUNCTION. |
ZEND_RINIT(module) | Declares a function for request startup. The generated name will be zend_rinit_<module> (for example, zend_rinit_first_module). Use in conjunction with ZEND_RINIT_FUNCTION. |
ZEND_RSHUTDOWN(module) | Declares a function for request shutdown. The generated name will be zend_rshutdown_<module> (for example, zend_rshutdown_first_module). Use in conjunction with ZEND_RSHUTDOWN_FUNCTION. |
ZEND_MINFO(module) | Declares a function for printing module information, used when phpinfo() is called. The generated name will be zend_info_<module> (for example, zend_info_first_module). Use in conjunction with ZEND_MINFO_FUNCTION. |
This function is special to all dynamic loadable modules. Take a look at the creation via the ZEND_GET_MODULE macro first:
#if COMPILE_DL_FIRSTMOD ZEND_GET_MODULE(firstmod) #endif |
The function implementation is surrounded by a conditional compilation statement. This is needed since the function get_module() is only required if your module is built as a dynamic extension. By specifying a definition of COMPILE_DL_FIRSTMOD in the compiler command (see above for a discussion of the compilation instructions required to build a dynamic extension), you can instruct your module whether you intend to build it as a dynamic extension or as a built-in module. If you want a built-in module, the implementation of get_module() is simply left out.
get_module() is called by Zend at load time of the module. You can think of it as being invoked by the dl() call in your script. Its purpose is to pass the module information block back to Zend in order to inform the engine about the module contents.
If you don't implement a get_module() function in your dynamic loadable module, Zend will compliment you with an error message when trying to access it.
Implementing the exported functions is the final step. The example function in first_module looks like this:
ZEND_FUNCTION(first_module) { long parameter; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", ¶meter) == FAILURE) { return; } RETURN_LONG(parameter); } |
After the declaration, code for checking and retrieving the function's arguments, argument conversion, and return value generation follows (more on this later).
That's it, basically - there's nothing more to implementing PHP modules. Built-in modules are structured similarly to dynamic modules, so, equipped with the information presented in the previous sections, you'll be able to fight the odds when encountering PHP module source files.
Now, in the following sections, read on about how to make use of PHP's internals to build powerful extensions.
One of the most important issues for language extensions is accepting and dealing with data passed via arguments. Most extensions are built to deal with specific input data (or require parameters to perform their specific actions), and function arguments are the only real way to exchange data between the PHP level and the C level. Of course, there's also the possibility of exchanging data using predefined global values (which is also discussed later), but this should be avoided by all means, as it's extremely bad practice.
PHP doesn't make use of any formal function declarations; this is why call syntax is always completely dynamic and never checked for errors. Checking for correct call syntax is left to the user code. For example, it's possible to call a function using only one argument at one time and four arguments the next time - both invocations are syntactically absolutely correct.
Since PHP doesn't have formal function definitions with support for call syntax checking, and since PHP features variable arguments, sometimes you need to find out with how many arguments your function has been called. You can use the ZEND_NUM_ARGS macro in this case. In previous versions of PHP, this macro retrieved the number of arguments with which the function has been called based on the function's hash table entry, ht, which is passed in the INTERNAL_FUNCTION_PARAMETERS list. As ht itself now contains the number of arguments that have been passed to the function, ZEND_NUM_ARGS has been stripped down to a dummy macro (see its definition in zend_API.h). But it's still good practice to use it, to remain compatible with future changes in the call interface. Note: The old PHP equivalent of this macro is ARG_COUNT.
The following code checks for the correct number of arguments:
if(ZEND_NUM_ARGS() != 2) WRONG_PARAM_COUNT; |
This macro prints a default error message and then returns to the caller. Its definition can also be found in zend_API.h and looks like this:
ZEND_API void wrong_param_count(void); #define WRONG_PARAM_COUNT { wrong_param_count(); return; } |
New parameter parsing API: This chapter documents the new Zend parameter parsing API introduced by Andrei Zmievski. It was introduced in the development stage between PHP 4.0.6 and 4.1.0 .
Parsing parameters is a very common operation and it may get a bit tedious. It would also be nice to have standardized error checking and error messages. Since PHP 4.1.0, there is a way to do just that by using the new parameter parsing API. It greatly simplifies the process of receiving parameteres, but it has a drawback in that it can't be used for functions that expect variable number of parameters. But since the vast majority of functions do not fall into those categories, this parsing API is recommended as the new standard way.
The prototype for parameter parsing function looks like this:
int zend_parse_parameters(int num_args TSRMLS_DC, char *type_spec, ...); |
zend_parse_parameters() also performs type conversions whenever possible, so that you always receive the data in the format you asked for. Any type of scalar can be converted to another one, but conversions between complex types (arrays, objects, and resources) and scalar types are not allowed.
If the parameters could be obtained successfully and there were no errors during type conversion, the function will return SUCCESS, otherwise it will return FAILURE. The function will output informative error messages, if the number of received parameters does not match the requested number, or if type conversion could not be performed.
Here are some sample error messages:
Warning - ini_get_all() requires at most 1 parameter, 2 given Warning - wddx_deserialize() expects parameter 1 to be string, array given |
Here is the full list of type specifiers:
l - long
d - double
s - string (with possible null bytes) and its length
b - boolean
r - resource, stored in zval*
a - array, stored in zval*
o - object (of any class), stored in zval*
O - object (of class specified by class entry), stored in zval*
z - the actual zval*
| - indicates that the remaining parameters are optional. The storage variables corresponding to these parameters should be initialized to default values by the extension, since they will not be touched by the parsing function if the parameters are not passed.
/ - the parsing function will call SEPARATE_ZVAL_IF_NOT_REF() on the parameter it follows, to provide a copy of the parameter, unless it's a reference.
! - the parameter it follows can be of specified type or NULL (only applies to a, o, O, r, and z). If NULL value is passed by the user, the storage pointer will be set to NULL.
The best way to illustrate the usage of this function is through examples:
/* Gets a long, a string and its length, and a zval. */ long l; char *s; int s_len; zval *param; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lsz", &l, &s, &s_len, ¶m) == FAILURE) { return; } /* Gets an object of class specified by my_ce, and an optional double. */ zval *obj; double d = 0.5; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|d", &obj, my_ce, &d) == FAILURE) { return; } /* Gets an object or null, and an array. If null is passed for object, obj will be set to NULL. */ zval *obj; zval *arr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O!a", &obj, &arr) == FAILURE) { return; } /* Gets a separated array. */ zval *arr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a/", &arr) == FAILURE) { return; } /* Get only the first three parameters (useful for varargs functions). */ zval *z; zend_bool b; zval *r; if (zend_parse_parameters(3, "zbr!", &z, &b, &r) == FAILURE) { return; } |
Note that in the last example we pass 3 for the number of received parameters, instead of ZEND_NUM_ARGS(). What this lets us do is receive the least number of parameters if our function expects a variable number of them. Of course, if you want to operate on the rest of the parameters, you will have to use zend_get_parameters_array_ex() to obtain them.
The parsing function has an extended version that allows for an additional flags argument that controls its actions.
int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, char *type_spec, ...); |
The only flag you can pass currently is ZEND_PARSE_PARAMS_QUIET, which instructs the function to not output any error messages during its operation. This is useful for functions that expect several sets of completely different arguments, but you will have to output your own error messages.
For example, here is how you would get either a set of three longs or a string:
long l1, l2, l3; char *s; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "lll", &l1, &l2, &l3) == SUCCESS) { /* manipulate longs */ } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "s", &s, &s_len) == SUCCESS) { /* manipulate string */ } else { php_error(E_WARNING, "%s() takes either three long values or a string as argument", get_active_function_name(TSRMLS_C)); return; } |
With all the abovementioned ways of receiving function parameters you should have a good handle on this process. For even more example, look through the source code for extensions that are shipped with PHP - they illustrate every conceivable situation.
Deprecated parameter parsing API: This API is deprecated and superseded by the new ZEND parameter parsing API.
After having checked the number of arguments, you need to get access to the arguments themselves. This is done with the help of zend_get_parameters_ex():
zval **parameter; if(zend_get_parameters_ex(1, ¶meter) != SUCCESS) WRONG_PARAM_COUNT; |
zend_get_parameters_ex() accepts at least two arguments. The first argument is the number of arguments to retrieve (which should match the number of arguments with which the function has been called; this is why it's important to check for correct call syntax). The second argument (and all following arguments) are pointers to pointers to pointers to zvals. (Confusing, isn't it?) All these pointers are required because Zend works internally with **zval; to adjust a local **zval in our function,zend_get_parameters_ex() requires a pointer to it.
The return value of zend_get_parameters_ex() can either be SUCCESS or FAILURE, indicating (unsurprisingly) success or failure of the argument processing. A failure is most likely related to an incorrect number of arguments being specified, in which case you should exit with WRONG_PARAM_COUNT.
To retrieve more than one argument, you can use a similar snippet:
zval **param1, **param2, **param3, **param4; if(zend_get_parameters_ex(4, ¶m1, ¶m2, ¶m3, ¶m4) != SUCCESS) WRONG_PARAM_COUNT; |
zend_get_parameters_ex() only checks whether you're trying to retrieve too many parameters. If the function is called with five arguments, but you're only retrieving three of them with zend_get_parameters_ex(), you won't get an error but will get the first three parameters instead. Subsequent calls of zend_get_parameters_ex() won't retrieve the remaining arguments, but will get the same arguments again.
If your function is meant to accept a variable number of arguments, the snippets just described are sometimes suboptimal solutions. You have to create a line calling zend_get_parameters_ex() for every possible number of arguments, which is often unsatisfying.
For this case, you can use the function zend_get_parameters_array_ex(), which accepts the number of parameters to retrieve and an array in which to store them:
zval **parameter_array[4]; /* get the number of arguments */ argument_count = ZEND_NUM_ARGS(); /* see if it satisfies our minimal request (2 arguments) */ /* and our maximal acceptance (4 arguments) */ if(argument_count < 2 || argument_count > 5) WRONG_PARAM_COUNT; /* argument count is correct, now retrieve arguments */ if(zend_get_parameters_array_ex(argument_count, parameter_array) != SUCCESS) WRONG_PARAM_COUNT; |
A very clever implementation of this can be found in the code handling PHP's fsockopen() located in ext/standard/fsock.c, as shown in 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().
|
fsockopen() accepts two, three, four, or five parameters. After the obligatory variable declarations, the function checks for the correct range of arguments. Then it uses a fall-through mechanism in a switch() statement to deal with all arguments. The switch() statement starts with the maximum number of arguments being passed (five). After that, it automatically processes the case of four arguments being passed, then three, by omitting the otherwise obligatory break keyword in all stages. After having processed the last case, it exits the switch() statement and does the minimal argument processing needed if the function is invoked with only two arguments.
This multiple-stage type of processing, similar to a stairway, allows convenient processing of a variable number of arguments.
To access arguments, it's necessary for each argument to have a clearly defined type. Again, PHP's extremely dynamic nature introduces some quirks. Because PHP never does any kind of type checking, it's possible for a caller to pass any kind of data to your functions, whether you want it or not. If you expect an integer, for example, the caller might pass an array, and vice versa - PHP simply won't notice.
To work around this, you have to use a set of API functions to force a type conversion on every argument that's being passed (see Tabella 34-1).
Note: All conversion functions expect a **zval as parameter.
Tabella 34-1. Argument Conversion Functions
Function | Description |
convert_to_boolean_ex() | Forces conversion to a Boolean type. Boolean values remain untouched. Longs, doubles, and strings containing 0 as well as NULL values will result in Boolean 0 (FALSE). Arrays and objects are converted based on the number of entries or properties, respectively, that they have. Empty arrays and objects are converted to FALSE; otherwise, to TRUE. All other values result in a Boolean 1 (TRUE). |
convert_to_long_ex() | Forces conversion to a long, the default integer type. NULL values, Booleans, resources, and of course longs remain untouched. Doubles are truncated. Strings containing an integer are converted to their corresponding numeric representation, otherwise resulting in 0. Arrays and objects are converted to 0 if empty, 1 otherwise. |
convert_to_double_ex() | Forces conversion to a double, the default floating-point type. NULL values, Booleans, resources, longs, and of course doubles remain untouched. Strings containing a number are converted to their corresponding numeric representation, otherwise resulting in 0.0. Arrays and objects are converted to 0.0 if empty, 1.0 otherwise. |
convert_to_string_ex() | Forces conversion to a string. Strings remain untouched. NULL values are converted to an empty string. Booleans containing TRUE are converted to "1", otherwise resulting in an empty string. Longs and doubles are converted to their corresponding string representation. Arrays are converted to the string "Array" and objects to the string "Object". |
convert_to_array_ex(value) | Forces conversion to an array. Arrays remain untouched. Objects are converted to an array by assigning all their properties to the array table. All property names are used as keys, property contents as values. NULL values are converted to an empty array. All other values are converted to an array that contains the specific source value in the element with the key 0. |
convert_to_object_ex(value) | Forces conversion to an object. Objects remain untouched. NULL values are converted to an empty object. Arrays are converted to objects by introducing their keys as properties into the objects and their values as corresponding property contents in the object. All other types result in an object with the property scalar , having the corresponding source value as content. |
convert_to_null_ex(value) | Forces the type to become a NULL value, meaning empty. |
Nota: You can find a demonstration of the behavior in cross_conversion.php on the accompanying CD-ROM. Figura 34-2 shows the output.
Using these functions on your arguments will ensure type safety for all data that's passed to you. If the supplied type doesn't match the required type, PHP forces dummy contents on the resulting value (empty strings, arrays, or objects, 0 for numeric values, FALSE for Booleans) to ensure a defined state.
Following is a quote from the sample module discussed previously, which makes use of the conversion functions:
zval **parameter; if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, ¶meter) != SUCCESS)) { WRONG_PARAM_COUNT; } convert_to_long_ex(parameter); RETURN_LONG(Z_LVAL_P(parameter)); |
Esempio 34-2. PHP/Zend zval type definition.
|
Actually, pval (defined in php.h) is only an alias of zval (defined in zend.h), which in turn refers to _zval_struct. This is a most interesting structure. _zval_struct is the "master" structure, containing the value structure, type, and reference information. The substructure zvalue_value is a union that contains the variable's contents. Depending on the variable's type, you'll have to access different members of this union. For a description of both structures, see Tabella 34-2, Tabella 34-3 and Tabella 34-4.
Tabella 34-2. Zend zval Structure
Entry | Description |
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
Entry | Description |
lval | Use this property if the variable is of the type IS_LONG, IS_BOOLEAN, or IS_RESOURCE. |
dval | Use this property if the variable is of the type IS_DOUBLE. |
str | This structure can be used to access variables of the type IS_STRING. The member len contains the string length; the member val points to the string itself. Zend uses C strings; thus, the string length contains a trailing 0x00. |
ht | This entry points to the variable's hash table entry if the variable is an array. |
obj | Use this property if the variable is of the type IS_OBJECT. |
Tabella 34-4. Zend Variable Type Constants
Constant | Description |
IS_NULL | Denotes a NULL (empty) value. |
IS_LONG | A long (integer) value. |
IS_DOUBLE | A double (floating point) value. |
IS_STRING | A string. |
IS_ARRAY | Denotes an array. |
IS_OBJECT | An object. |
IS_BOOL | A Boolean value. |
IS_RESOURCE | A resource (for a discussion of resources, see the appropriate section below). |
IS_CONSTANT | A constant (defined) value. |
To access a long you access zval.value.lval, to access a double you use zval.value.dval, and so on. Because all values are stored in a union, trying to access data with incorrect union members results in meaningless output.
Accessing arrays and objects is a bit more complicated and is discussed later.
If your function accepts arguments passed by reference that you intend to modify, you need to take some precautions.
What we didn't say yet is that under the circumstances presented so far, you don't have write access to any zval containers designating function parameters that have been passed to you. Of course, you can change any zval containers that you created within your function, but you mustn't change any zvals that refer to Zend-internal data!
We've only discussed the so-called *_ex() API so far. You may have noticed that the API functions we've used are called zend_get_parameters_ex() instead of zend_get_parameters(), convert_to_long_ex() instead of convert_to_long(), etc. The *_ex() functions form the so-called new "extended" Zend API. They give a minor speed increase over the old API, but as a tradeoff are only meant for providing read-only access.
Because Zend works internally with references, different variables may reference the same value. Write access to a zval container requires this container to contain an isolated value, meaning a value that's not referenced by any other containers. If a zval container were referenced by other containers and you changed the referenced zval, you would automatically change the contents of the other containers referencing this zval (because they'd simply point to the changed value and thus change their own value as well).
zend_get_parameters_ex() doesn't care about this situation, but simply returns a pointer to the desired zval containers, whether they consist of references or not. Its corresponding function in the traditional API, zend_get_parameters(), immediately checks for referenced values. If it finds a reference, it creates a new, isolated zval container; copies the referenced data into this newly allocated space; and then returns a pointer to the new, isolated value.
This action is called zval separation (or pval separation). Because the *_ex() API doesn't perform zval separation, it's considerably faster, while at the same time disabling write access.
To change parameters, however, write access is required. Zend deals with this situation in a special way: Whenever a parameter to a function is passed by reference, it performs automatic zval separation. This means that whenever you're calling a function like this in PHP, Zend will automatically ensure that $parameter is being passed as an isolated value, rendering it to a write-safe state:
my_function(&$parameter); |
But this is not the case with regular parameters! All other parameters that are not passed by reference are in a read-only state.
This requires you to make sure that you're really working with a reference - otherwise you might produce unwanted results. To check for a parameter being passed by reference, you can use the macro PZVAL_IS_REF. This macro accepts a zval* to check if it is a reference or not. Examples are given in in Esempio 34-3.
Esempio 34-3. Testing for referenced parameter passing.
|
You might run into a situation in which you need write access to a parameter that's retrieved with zend_get_parameters_ex() but not passed by reference. For this case, you can use the macro SEPARATE_ZVAL, which does a zval separation on the provided container. The newly generated zval is detached from internal data and has only a local scope, meaning that it can be changed or destroyed without implying global changes in the script context:
zval **parameter; /* retrieve parameter */ zend_get_parameters_ex(1, ¶meter); /* at this stage, <parameter> still is connected */ /* to Zend's internal data buffers */ /* make <parameter> write-safe */ SEPARATE_ZVAL(parameter); /* now we can safely modify <parameter> */ /* without implying global changes */ |
Note: As you can easily work around the lack of write access in the "traditional" API (with zend_get_parameters() and so on), this API seems to be obsolete, and is not discussed further in this chapter.
When exchanging data from your own extensions with PHP scripts, one of the most important issues is the creation of variables. This section shows you how to deal with the variable types that PHP supports.
To create new variables that can be seen "from the outside" by the executing script, you need to allocate a new zval container, fill this container with meaningful values, and then introduce it to Zend's internal symbol table. This basic process is common to all variable creations:
zval *new_variable; /* allocate and initialize new container */ MAKE_STD_ZVAL(new_variable); /* set type and variable contents here, see the following sections */ /* introduce this variable by the name "new_variable_name" into the symbol table */ ZEND_SET_SYMBOL(EG(active_symbol_table), "new_variable_name", new_variable); /* the variable is now accessible to the script by using $new_variable_name */ |
The macro MAKE_STD_ZVAL allocates a new zval container using ALLOC_ZVAL and initializes it using INIT_ZVAL. As implemented in Zend at the time of this writing, initializing means setting the reference count to 1 and clearing the is_ref flag, but this process could be extended later - this is why it's a good idea to keep using MAKE_STD_ZVAL instead of only using ALLOC_ZVAL. If you want to optimize for speed (and you don't have to explicitly initialize the zval container here), you can use ALLOC_ZVAL, but this isn't recommended because it doesn't ensure data integrity.
ZEND_SET_SYMBOL takes care of introducing the new variable to Zend's symbol table. This macro checks whether the value already exists in the symbol table and converts the new symbol to a reference if so (with automatic deallocation of the old zval container). This is the preferred method if speed is not a crucial issue and you'd like to keep memory usage low.
Note that ZEND_SET_SYMBOL makes use of the Zend executor globals via the macro EG. By specifying EG(active_symbol_table), you get access to the currently active symbol table, dealing with the active, local scope. The local scope may differ depending on whether the function was invoked from within a function.
If you need to optimize for speed and don't care about optimal memory usage, you can omit the check for an existing variable with the same value and instead force insertion into the symbol table by using zend_hash_update():
zval *new_variable; /* allocate and initialize new container */ MAKE_STD_ZVAL(new_variable); /* set type and variable contents here, see the following sections */ /* introduce this variable by the name "new_variable_name" into the symbol table */ zend_hash_update( EG(active_symbol_table), "new_variable_name", strlen("new_variable_name") + 1, &new_variable, sizeof(zval *), NULL ); |
The variables generated with the snippet above will always be of local scope, so they reside in the context in which the function has been called. To create new variables in the global scope, use the same method but refer to another symbol table:
zval *new_variable; // allocate and initialize new container MAKE_STD_ZVAL(new_variable); // // set type and variable contents here // // introduce this variable by the name "new_variable_name" into the global symbol table ZEND_SET_SYMBOL(&EG(symbol_table), "new_variable_name", new_variable); |
Note: The active_symbol_table variable is a pointer, but symbol_table is not. This is why you have to use EG(active_symbol_table) and &EG(symbol_table) as parameters to ZEND_SET_SYMBOL - it requires a pointer.
Similarly, to get a more efficient version, you can hardcode the symbol table update:
zval *new_variable; // allocate and initialize new container MAKE_STD_ZVAL(new_variable); // // set type and variable contents here // // introduce this variable by the name "new_variable_name" into the global symbol table zend_hash_update( &EG(symbol_table), "new_variable_name", strlen("new_variable_name") + 1, &new_variable, sizeof(zval *), NULL ); |
Note: You can see that the global variable is actually not accessible from within the function. This is because it's not imported into the local scope using global $global_variable; in the PHP source.
Esempio 35-1. Creating variables with different scopes.
|
Now let's get to the assignment of data to variables, starting with longs. Longs are PHP's integers and are very simple to store. Looking at the zval.value container structure discussed earlier in this chapter, you can see that the long data type is directly contained in the union, namely in the lval field. The corresponding type value for longs is IS_LONG (see Esempio 35-2).
zval *new_long; MAKE_STD_ZVAL(new_long); ZVAL_LONG(new_long, 10); |
Doubles are PHP's floats and are as easy to assign as longs, because their value is also contained directly in the union. The member in the zval.value container is dval; the corresponding type is IS_DOUBLE.
zval *new_double; MAKE_STD_ZVAL(new_double); new_double->type = IS_DOUBLE; new_double->value.dval = 3.45; |
zval *new_double; MAKE_STD_ZVAL(new_double); ZVAL_DOUBLE(new_double, 3.45); |
Strings need slightly more effort. As mentioned earlier, all strings that will be associated with Zend's internal data structures need to be allocated using Zend's own memory-management functions. Referencing of static strings or strings allocated with standard routines is not allowed. To assign strings, you have to access the structure str in the zval.value container. The corresponding type is IS_STRING:
zval *new_string; char *string_contents = "This is a new string variable"; MAKE_STD_ZVAL(new_string); new_string->type = IS_STRING; new_string->value.str.len = strlen(string_contents); new_string->value.str.val = estrdup(string_contents); |
zval *new_string; char *string_contents = "This is a new string variable"; MAKE_STD_ZVAL(new_string); ZVAL_STRING(new_string, string_contents, 1); |
If you want to truncate the string at a certain position or you already know its length, you can use ZVAL_STRINGL(zval, string, length, duplicate), which accepts an explicit string length to be set for the new string. This macro is faster than ZVAL_STRING and also binary-safe.
To create empty strings, set the string length to 0 and use empty_string as contents:
new_string->type = IS_STRING; new_string->value.str.len = 0; new_string->value.str.val = empty_string; |
MAKE_STD_ZVAL(new_string); ZVAL_EMPTY_STRING(new_string); |
Booleans are created just like longs, but have the type IS_BOOL. Allowed values in lval are 0 and 1:
zval *new_bool; MAKE_STD_ZVAL(new_bool); new_bool->type = IS_BOOL; new_bool->value.lval = 1; |
Arrays are stored using Zend's internal hash tables, which can be accessed using the zend_hash_*() API. For every array that you want to create, you need a new hash table handle, which will be stored in the ht member of the zval.value container.
There's a whole API solely for the creation of arrays, which is extremely handy. To start a new array, you call array_init().
zval *new_array; MAKE_STD_ZVAL(new_array); array_init(new_array); |
To add new elements to the array, you can use numerous functions, depending on what you want to do. 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
Function | Description |
add_assoc_long(zval *array, char *key, long n);() | Adds an element of type long. |
add_assoc_unset(zval *array, char *key);() | Adds an unset element. |
add_assoc_bool(zval *array, char *key, int b);() | Adds a Boolean element. |
add_assoc_resource(zval *array, char *key, int r);() | Adds a resource to the array. |
add_assoc_double(zval *array, char *key, double d);() | Adds a floating-point value. |
add_assoc_string(zval *array, char *key, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory. |
add_assoc_stringl(zval *array, char *key, char *str, uint length, int duplicate); () | Adds a string with the desired length length to the array. Otherwise, behaves like add_assoc_string(). |
add_assoc_zval(zval *array, char *key, zval *value);() | Adds a zval to the array. Useful for adding other arrays, objects, streams, etc... |
Tabella 35-2. Zend's API for Indexed Arrays, Part 1
Function | Description |
add_index_long(zval *array, uint idx, long n);() | Adds an element of type long. |
add_index_unset(zval *array, uint idx);() | Adds an unset element. |
add_index_bool(zval *array, uint idx, int b);() | Adds a Boolean element. |
add_index_resource(zval *array, uint idx, int r);() | Adds a resource to the array. |
add_index_double(zval *array, uint idx, double d);() | Adds a floating-point value. |
add_index_string(zval *array, uint idx, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory. |
add_index_stringl(zval *array, uint idx, char *str, uint length, int duplicate);() | Adds a string with the desired length length to the array. This function is faster and binary-safe. Otherwise, behaves like add_index_string()(). |
add_index_zval(zval *array, uint idx, zval *value);() | Adds a zval to the array. Useful for adding other arrays, objects, streams, etc... |
Tabella 35-3. Zend's API for Indexed Arrays, Part 2
Function | Description |
add_next_index_long(zval *array, long n);() | Adds an element of type long. |
add_next_index_unset(zval *array);() | Adds an unset element. |
add_next_index_bool(zval *array, int b);() | Adds a Boolean element. |
add_next_index_resource(zval *array, int r);() | Adds a resource to the array. |
add_next_index_double(zval *array, double d);() | Adds a floating-point value. |
add_next_index_string(zval *array, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory. |
add_next_index_stringl(zval *array, char *str, uint length, int duplicate);() | Adds a string with the desired length length to the array. This function is faster and binary-safe. Otherwise, behaves like add_index_string()(). |
add_next_index_zval(zval *array, zval *value);() | Adds a zval to the array. Useful for adding other arrays, objects, streams, etc... |
All these functions provide a handy abstraction to Zend's internal hash API. Of course, you can also use the hash functions directly - for example, if you already have a zval container allocated that you want to insert into an array. This is done using zend_hash_update()() for associative arrays (see 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.
|
Esempio 35-4. Adding an element to an indexed array.
|
To emulate the functionality of add_next_index_*(), you can use this:
zend_hash_next_index_insert(ht, zval **new_element, sizeof(zval *), NULL) |
Note: To return arrays from a function, use array_init() and all following actions on the predefined variable return_value (given as argument to your exported function; see the earlier discussion of the call interface). You do not have to use MAKE_STD_ZVAL on this.
Tip: To avoid having to write new_array->value.ht every time, you can use HASH_OF(new_array), which is also recommended for compatibility and style reasons.
Since objects can be converted to arrays (and vice versa), you might have already guessed that they have a lot of similarities to arrays in PHP. Objects are maintained with the same hash functions, but there's a different API for creating them.
To initialize an object, you use the function object_init():
zval *new_object; MAKE_STD_ZVAL(new_object); if(object_init(new_object) != SUCCESS) { // do error handling here } |
Tabella 35-4. Zend's API for Object Creation
Function | Description |
add_property_long(zval *object, char *key, long l);() | Adds a long to the object. |
add_property_unset(zval *object, char *key);() | Adds an unset property to the object. |
add_property_bool(zval *object, char *key, int b);() | Adds a Boolean to the object. |
add_property_resource(zval *object, char *key, long r);() | Adds a resource to the object. |
add_property_double(zval *object, char *key, double d);() | Adds a double to the object. |
add_property_string(zval *object, char *key, char *str, int duplicate);() | Adds a string to the object. |
add_property_stringl(zval *object, char *key, char *str, uint length, int duplicate);() | Adds a string of the specified length to the object. This function is faster than add_property_string() and also binary-safe. |
add_property_zval(zval *obect, char *key, zval *container):() | Adds a zval container to the object. This is useful if you have to add properties which aren't simple types like integers or strings but arrays or other objects. |
Resources are a special kind of data type in PHP. The term resources doesn't really refer to any special kind of data, but to an abstraction method for maintaining any kind of information. Resources are kept in a special resource list within Zend. Each entry in the list has a correspondending type definition that denotes the kind of resource to which it refers. Zend then internally manages all references to this resource. Access to a resource is never possible directly - only via a provided API. As soon as all references to a specific resource are lost, a corresponding shutdown function is called.
For example, resources are used to store database links and file descriptors. The de facto standard implementation can be found in the MySQL module, but other modules such as the Oracle module also make use of resources.
Nota: In fact, a resource can be a pointer to anything you need to handle in your functions (e.g. pointer to a structure) and the user only has to pass a single resource variable to your function.
To create a new resource you need to register a resource destruction handler for it. Since you can store any kind of data as a resource, Zend needs to know how to free this resource if its not longer needed. This works by registering your own resource destruction handler to Zend which in turn gets called by Zend whenever your resource can be freed (whether manually or automatically). Registering your resource handler within Zend returns you the resource type handle for that resource. This handle is needed whenever you want to access a resource of this type later and is most of time stored in a global static variable within your extension. There is no need to worry about thread safety here because you only register your resource handler once during module initialization.
The Zend function to register your resource handler is defined as:
ZEND_API int zend_register_list_destructors_ex(rsrc_dtor_func_t ld, rsrc_dtor_func_t pld, char *type_name, int module_number); |
There are two different kinds of resource destruction handlers you can pass to this function: a handler for normal resources and a handler for persistent resources. Persistent resources are for example used for database connection. When registering a resource, either of these handlers must be given. For the other handler just pass NULL.
zend_register_list_destructors_ex() accepts the following parameters:
ld | Normal resource destruction handler callback |
pld | Pesistent resource destruction handler callback |
type_name | A string specifying the name of your resource. It's always a good thing to specify an unique name within PHP for the resource type so when the user for example calls var_dump($resource); he also gets the name of the resource. |
module_number | The module_number is automatically available in your PHP_MINIT_FUNCTION function and therefore you just pass it over. |
The resource destruction handler (either normal or persistent resources) has the following prototype:
void resource_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC); |
typedef struct _zend_rsrc_list_entry { void *ptr; int type; int refcount; } zend_rsrc_list_entry; |
Now we know how to start things, we define our own resource we want register within Zend. It is only a simple structure with two integer members:
typedef struct { int resource_link; int resource_type; } my_resource; |
void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) { // You most likely cast the void pointer to your structure type my_resource *my_rsrc = (my_resource *) rsrc->ptr; // Now do whatever needs to be done with you resource. Closing // Files, Sockets, freeing additional memory, etc. // Also, don't forget to actually free the memory for your resource too! do_whatever_needs_to_be_done_with_the_resource(my_rsrc); } |
Nota: One important thing to mention: If your resource is a rather complex structure which also contains pointers to memory you allocated during runtime you have to free them before freeing the resource itself!
Now that we have defined
what our resource is and
our resource destruction handler
create a global variable within the extension holding the resource ID so it can be accessed from every function which needs it
define the resource name
write the resource destruction handler
and finally register the handler
// Somewhere in your extension, define the variable for your registered resources. // If you wondered what 'le' stands for: it simply means 'list entry'. static int le_myresource; // It's nice to define your resource name somewhere #define le_myresource_name "My type of resource" [...] // Now actually define our resource destruction handler void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) { my_resource *my_rsrc = (my_resource *) rsrc->ptr; do_whatever_needs_to_be_done_with_the_resource(my_rsrc); } [...] PHP_MINIT_FUNCTION(my_extension) { // Note that 'module_number' is already provided through the // PHP_MINIT_FUNCTION() function definition. le_myresource = zend_register_resource_destructors_ex(my_destruction_handler, NULL, le_myresource_name, module_number); // You can register additional resources, initialize // your global vars, constants, whatever. } |
To actually register a new resource you use can either use the zend_register_resource() function or the ZEND_REGISTER_RESOURE() macro, both defined in zend_list.h . Although the arguments for both map 1:1 it's a good idea to always use macros to be upwards compatible:
int ZEND_REGISTER_RESOURCE(zval *rsrc_result, void *rsrc_pointer, int rsrc_type); |
rsrc_result | This is an already initialized zval * container. |
rsrc_pointer | Your resource pointer you want to store. |
rsrc_type | The type which you received when you registered the resource destruction handler. If you followed the naming scheme this would be le_myresource. |
What is really going on when you register a new resource is it gets inserted in an internal list in Zend and the result is just stored in the given zval * container:
rsrc_id = zend_list_insert(rsrc_pointer, rsrc_type); if (rsrc_result) { rsrc_result->value.lval = rsrc_id; rsrc_result->type = IS_RESOURCE; } return rsrc_id; |
RETURN_RESOURCE(rsrc_id) |
Nota: It is common practice that if you want to return the resource immidiately to the user you specify the return_value as the zval * container.
Zend now keeps track of all references to this resource. As soon as all references to the resource are lost, the destructor that you previously registered for this resource is called. The nice thing about this setup is that you don't have to worry about memory leakages introduced by allocations in your module - just register all memory allocations that your calling script will refer to as resources. As soon as the script decides it doesn't need them anymore, Zend will find out and tell you.
Now that the user got his resource, at some point he is passing it back to one of your functions. The value.lval inside the zval * container contains the key to your resource and thus can be used to fetch the resource with the following macro: ZEND_FETCH_RESOURCE:
ZEND_FETCH_RESOURCE(rsrc, rsrc_type, rsrc_id, default_rsrc_id, resource_type_name, resource_type) |
rsrc | This is your pointer which will point to your previously registered resource. |
rsrc_type | This is the typecast argument for your pointer, e.g. myresource *. |
rsrc_id | This is the address of the zval *container the user passed to your function, e.g. &z_resource if zval *z_resource is given. |
default_rsrc_id | This integer specifies the default resource ID if no resource could be fetched or -1. |
resource_type_name | This is the name of the requested resource. It's a string and is used when the resource can't be found or is invalid to form a meaningful error message. |
resource_type | The resource_type you got back when registering the resource destruction handler. In our example this was le_myresource. |
To force removal of a resource from the list, use the function zend_list_delete(). You can also force the reference count to increase if you know that you're creating another reference for a previously allocated value (for example, if you're automatically reusing a default database link). For this case, use the function zend_list_addref(). To search for previously allocated resource entries, use zend_list_find(). The complete API can be found in zend_list.h.
In addition to the macros discussed earlier, a few macros allow easy creation of simple global variables. These are nice to know in case you want to introduce global flags, for example. This is somewhat bad practice, but Table 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
Macro | Description |
SET_VAR_STRING(name, value) | Creates a new string. |
SET_VAR_STRINGL(name, value, length) | Creates a new string of the specified length. This macro is faster than SET_VAR_STRING and also binary-safe. |
SET_VAR_LONG(name, value) | Creates a new long. |
SET_VAR_DOUBLE(name, value) | Creates a new double. |
Zend supports the creation of true constants (as opposed to regular variables). Constants are accessed without the typical dollar sign ($) prefix and are available in all scopes. Examples include TRUE and FALSE, to name just two.
To create your own constants, you can use the macros in 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.
// register a new constant of type "long" REGISTER_LONG_CONSTANT("NEW_MEANINGFUL_CONSTANT", 324, CONST_CS | CONST_PERSISTENT); |
Tabella 35-6. Macros for Creating Constants
Macro | Description |
REGISTER_LONG_CONSTANT(name, value, flags) REGISTER_MAIN_LONG_CONSTANT(name, value, flags) | Registers a new constant of type long. |
REGISTER_DOUBLE_CONSTANT(name, value, flags) REGISTER_MAIN_DOUBLE_CONSTANT(name, value, flags) | Registers a new constant of type double. |
REGISTER_STRING_CONSTANT(name, value, flags) REGISTER_MAIN_STRING_CONSTANT(name, value, flags) | Registers a new constant of type string. The specified string must reside in Zend's internal memory. |
REGISTER_STRINGL_CONSTANT(name, value, length, flags) REGISTER_MAIN_STRINGL_CONSTANT(name, value, length, flags) | Registers a new constant of type string. The string length is explicitly set to length. The specified string must reside in Zend's internal memory. |
Sooner or later, you may need to assign the contents of one zval container to another. This is easier said than done, since the zval container doesn't contain only type information, but also references to places in Zend's internal data. For example, depending on their size, arrays and objects may be nested with lots of hash table entries. By assigning one zval to another, you avoid duplicating the hash table entries, using only a reference to them (at most).
To copy this complex kind of data, use the copy constructor. Copy constructors are typically defined in languages that support operator overloading, with the express purpose of copying complex types. If you define an object in such a language, you have the possibility of overloading the "=" operator, which is usually responsible for assigning the contents of the lvalue (result of the evaluation of the left side of the operator) to the rvalue (same for the right side).
Overloading means assigning a different meaning to this operator, and is usually used to assign a function call to an operator. Whenever this operator would be used on such an object in a program, this function would be called with the lvalue and rvalue as parameters. Equipped with that information, it can perform the operation it intends the "=" operator to have (usually an extended form of copying).
This same form of "extended copying" is also necessary for PHP's zval containers. Again, in the case of an array, this extended copying would imply re-creation of all hash table entries relating to this array. For strings, proper memory allocation would have to be assured, and so on.
Zend ships with such a function, called zend_copy_ctor() (the previous PHP equivalent was pval_copy_constructor()).
A most useful demonstration is a function that accepts a complex type as argument, modifies it, and then returns the argument:
zval *parameter; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", ¶meter) == FAILURE) return; } // do modifications to the parameter here // now we want to return the modified container: *return_value == *parameter; zval_copy_ctor(return_value); |
The first part of the function is plain-vanilla argument retrieval. After the (left out) modifications, however, it gets interesting: The container of parameter is assigned to the (predefined) return_value container. Now, in order to effectively duplicate its contents, the copy constructor is called. The copy constructor works directly with the supplied argument, and the standard return values are FAILURE on failure and SUCCESS on success.
If you omit the call to the copy constructor in this example, both parameter and return_value would point to the same internal data, meaning that return_value would be an illegal additional reference to the same data structures. Whenever changes occurred in the data that parameter points to, return_value might be affected. Thus, in order to create separate copies, the copy constructor must be used.
The copy constructor's counterpart in the Zend API, the destructor zval_dtor(), does the opposite of the constructor.
Returning values from your functions to PHP was described briefly in an earlier section; this section gives the details. Return values are passed via the return_value variable, which is passed to your functions as argument. The return_value argument consists of a zval container (see the earlier discussion of the call interface) that you can freely modify. The container itself is already allocated, so you don't have to run MAKE_STD_ZVAL on it. Instead, you can access its members directly.
To make returning values from functions easier and to prevent hassles with accessing the internal structures of the zval container, a set of predefined macros is available (as usual). These macros automatically set the correspondent type and value, as described in 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
Macro | Description |
RETURN_RESOURCE(resource) | Returns a resource. |
RETURN_BOOL(bool) | Returns a Boolean. |
RETURN_NULL() | Returns nothing (a NULL value). |
RETURN_LONG(long) | Returns a long. |
RETURN_DOUBLE(double) | Returns a double. |
RETURN_STRING(string, duplicate) | Returns a string. The duplicate flag indicates whether the string should be duplicated using estrdup(). |
RETURN_STRINGL(string, length, duplicate) | Returns a string of the specified length; otherwise, behaves like RETURN_STRING. This macro is faster and binary-safe, however. |
RETURN_EMPTY_STRING() | Returns an empty string. |
RETURN_FALSE | Returns Boolean false. |
RETURN_TRUE | Returns Boolean true. |
Tabella 37-2. Predefined Macros for Setting the Return Value of a Function
Macro | Description |
RETVAL_RESOURCE(resource) | Sets the return value to the specified resource. |
RETVAL_BOOL(bool) | Sets the return value to the specified Boolean value. |
RETVAL_NULL | Sets the return value to NULL. |
RETVAL_LONG(long) | Sets the return value to the specified long. |
RETVAL_DOUBLE(double) | Sets the return value to the specified double. |
RETVAL_STRING(string, duplicate) | Sets the return value to the specified string and duplicates it to Zend internal memory if desired (see also RETURN_STRING). |
RETVAL_STRINGL(string, length, duplicate) | Sets the return value to the specified string and forces the length to become length (see also RETVAL_STRING). This macro is faster and binary-safe, and should be used whenever the string length is known. |
RETVAL_EMPTY_STRING | Sets the return value to an empty string. |
RETVAL_FALSE | Sets the return value to Boolean false. |
RETVAL_TRUE | Sets the return value to Boolean true. |
Complex types such as arrays and objects can be returned by using array_init() and object_init(), as well as the corresponding hash functions on return_value. Since these types cannot be constructed of trivial information, there are no predefined macros for them.
Often it's necessary to print messages to the output stream from your module, just as print() would be used within a script. PHP offers functions for most generic tasks, such as printing warning messages, generating output for phpinfo(), and so on. The following sections provide more details. Examples of these functions can be found on the CD-ROM.
zend_printf() works like the standard printf(), except that it prints to Zend's output stream.
zend_error() can be used to generate error messages. This function accepts two arguments; the first is the error type (see zend_errors.h), and the second is the error message.
zend_error(E_WARNING, "This function has been called with empty arguments"); |
Tabella 38-1. Zend's Predefined Error Messages.
Error | Description |
E_ERROR | Signals an error and terminates execution of the script immediately . |
E_WARNING | Signals a generic warning. Execution continues. |
E_PARSE | Signals a parser error. Execution continues. |
E_NOTICE | Signals a notice. Execution continues. Note that by default the display of this type of error messages is turned off in php.ini. |
E_CORE_ERROR | Internal error by the core; shouldn't be used by user-written modules. |
E_COMPILE_ERROR | Internal error by the compiler; shouldn't be used by user-written modules. |
E_COMPILE_WARNING | Internal warning by the compiler; shouldn't be used by user-written modules. |
After creating a real module, you'll want to show information about the module in phpinfo() (in addition to the module name, which appears in the module list by default). PHP allows you to create your own section in the phpinfo() output with the ZEND_MINFO() function. This function should be placed in the module descriptor block (discussed earlier) and is always called whenever a script calls phpinfo().
PHP automatically prints a section in phpinfo() for you if you specify the ZEND_MINFO function, including the module name in the heading. Everything else must be formatted and printed by you.
Typically, you can print an HTML table header using php_info_print_table_start() and then use the standard functions php_info_print_table_header() and php_info_print_table_row(). As arguments, both take the number of columns (as integers) and the column contents (as strings). 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().
|
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.
|
Startup and shutdown functions can be used for one-time initialization and deinitialization of your modules. As discussed earlier in this chapter (see the description of the Zend module descriptor block), there are module, and request startup and shutdown events.
The module startup and shutdown functions are called whenever a module is loaded and needs initialization; the request startup and shutdown functions are called every time a request is processed (meaning that a file is being executed).
For dynamic extensions, module and request startup/shutdown events happen at the same time.
Declaration and implementation of these functions can be done with macros; see the earlier section "Declaration of the Zend Module Block" for details.
You can call user functions from your own modules, which is very handy when implementing callbacks; for example, for array walking, searching, or simply for event-based programs.
User functions can be called with the function call_user_function_ex(). It requires a hash value for the function table you want to access, a pointer to an object (if you want to call a method), the function name, return value, number of arguments, argument array, and a flag indicating whether you want to perform zval separation.
ZEND_API int call_user_function_ex(HashTable *function_table, zval *object, zval *function_name, zval **retval_ptr_ptr, int param_count, zval **params[], int no_separation); |
Note that you don't have to specify both function_table and object; either will do. If you want to call a method, you have to supply the object that contains this method, in which case call_user_function()automatically sets the function table to this object's function table. Otherwise, you only need to specify function_table and can set object to NULL.
Usually, the default function table is the "root" function table containing all function entries. This function table is part of the compiler globals and can be accessed using the macro CG. To introduce the compiler globals to your function, call the macro TSRMLS_FETCH once.
The function name is specified in a zval container. This might be a bit surprising at first, but is quite a logical step, since most of the time you'll accept function names as parameters from calling functions within your script, which in turn are contained in zval containers again. Thus, you only have to pass your arguments through to this function. This zval must be of type IS_STRING.
The next argument consists of a pointer to the return value. You don't have to allocate memory for this container; the function will do so by itself. However, you have to destroy this container (using zval_dtor()) afterward!
Next is the parameter count as integer and an array containing all necessary parameters. The last argument specifies whether the function should perform zval separation - this should always be set to 0. If set to 1, the function consumes less memory but fails if any of the parameters need separation.
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.
|
<?php dl("call_userland.so"); function test_function() { print("We are in the test function!<br>"); return("hello"); } $return_value = call_userland("test_function"); print("Return value: \"$return_value\"<br>"); ?> |
PHP 4 features a redesigned initialization file support. It's now possible to specify default initialization entries directly in your code, read and change these values at runtime, and create message handlers for change notifications.
To create an .ini section in your own module, use the macros PHP_INI_BEGIN() to mark the beginning of such a section and PHP_INI_END() to mark its end. In between you can use PHP_INI_ENTRY() to create entries.
PHP_INI_BEGIN() PHP_INI_ENTRY("first_ini_entry", "has_string_value", PHP_INI_ALL, NULL) PHP_INI_ENTRY("second_ini_entry", "2", PHP_INI_SYSTEM, OnChangeSecond) PHP_INI_ENTRY("third_ini_entry", "xyz", PHP_INI_USER, NULL) PHP_INI_END() |
The permissions are grouped into three sections:PHP_INI_SYSTEM allows a change only directly in the php.ini file; PHP_INI_USER allows a change to be overridden by a user at runtime using additional configuration files, such as .htaccess; and PHP_INI_ALL allows changes to be made without restrictions. There's also a fourth level, PHP_INI_PERDIR, for which we couldn't verify its behavior yet.
The fourth parameter consists of a pointer to a change-notification handler. Whenever one of these initialization entries is changed, this handler is called. Such a handler can be declared using the PHP_INI_MH macro:
PHP_INI_MH(OnChangeSecond); // handler for ini-entry "second_ini_entry" // specify ini-entries here PHP_INI_MH(OnChangeSecond) { zend_printf("Message caught, our ini entry has been changed to %s<br>", new_value); return(SUCCESS); } |
#define PHP_INI_MH(name) int name(php_ini_entry *entry, char *new_value, uint new_value_length, void *mh_arg1, void *mh_arg2, void *mh_arg3) |
The change-notification handlers should be used to cache initialization entries locally for faster access or to perform certain tasks that are required if a value changes. For example, if a constant connection to a certain host is required by a module and someone changes the hostname, automatically terminate the old connection and attempt a new one.
Access to initialization entries can also be handled with the macros shown in Tabella 41-1.
Tabella 41-1. Macros to Access Initialization Entries in PHP
Macro | Description |
INI_INT(name) | Returns the current value of entry name as integer (long). |
INI_FLT(name) | Returns the current value of entry name as float (double). |
INI_STR(name) | Returns the current value of entry name as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory. |
INI_BOOL(name) | Returns the current value of entry name as Boolean (defined as zend_bool, which currently means unsigned char). |
INI_ORIG_INT(name) | Returns the original value of entry name as integer (long). |
INI_ORIG_FLT(name) | Returns the original value of entry name as float (double). |
INI_ORIG_STR(name) | Returns the original value of entry name as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory. |
INI_ORIG_BOOL(name) | Returns the original value of entry name as Boolean (defined as zend_bool, which currently means unsigned char). |
Finally, you have to introduce your initialization entries to PHP. This can be done in the module startup and shutdown functions, using the macros REGISTER_INI_ENTRIES() and UNREGISTER_INI_ENTRIES():
ZEND_MINIT_FUNCTION(mymodule) { REGISTER_INI_ENTRIES(); } ZEND_MSHUTDOWN_FUNCTION(mymodule) { UNREGISTER_INI_ENTRIES(); } |
You've learned a lot about PHP. You now know how to create dynamic loadable modules and statically linked extensions. You've learned how PHP and Zend deal with internal storage of variables and how you can create and access these variables. You know quite a set of tool functions that do a lot of routine tasks such as printing informational texts, automatically introducing variables to the symbol table, and so on.
Even though this chapter often had a mostly "referential" character, we hope that it gave you insight on how to start writing your own extensions. For the sake of space, we had to leave out a lot; we suggest that you take the time to study the header files and some modules (especially the ones in the ext/standard directory and the MySQL module, as these implement commonly known functionality). This will give you an idea of how other people have used the API functions - particularly those that didn't make it into this chapter.
The file config.m4 is processed by buildconf and must contain all the instructions to be executed during configuration. For example, these can include tests for required external files, such as header files, libraries, and so on. PHP defines a set of macros that can be used in this process, the most useful of which are described in Tabella 43-1.
Tabella 43-1. M4 Macros for config.m4
Macro | Description |
AC_MSG_CHECKING(message) | Prints a "checking <message>" text during configure. |
AC_MSG_RESULT(value) | Gives the result to AC_MSG_CHECKING; should specify either yes or no as value. |
AC_MSG_ERROR(message) | Prints message as error message during configure and aborts the script. |
AC_DEFINE(name,value,description) | Adds #define to php_config.h with the value of value and a comment that says description (this is useful for conditional compilation of your module). |
AC_ADD_INCLUDE(path) | Adds a compiler include path; for example, used if the module needs to add search paths for header files. |
AC_ADD_LIBRARY_WITH_PATH(libraryname,librarypath) | Specifies an additional library to link. |
AC_ARG_WITH(modulename,description,unconditionaltest,conditionaltest) | Quite a powerful macro, adding the module with description to the configure --help output. PHP checks whether the option --with-<modulename> is given to the configure script. If so, it runs the script unconditionaltest (for example, --with-myext=yes), in which case the value of the option is contained in the variable $withval. Otherwise, it executes conditionaltest. |
PHP_EXTENSION(modulename, [shared]) | This macro is a must to call for PHP to configure your extension. You can supply a second argument in addition to your module name, indicating whether you intend compilation as a shared module. This will result in a definition at compile time for your source as COMPILE_DL_<modulename>. |
A set of macros was introduced into Zend's API that simplify access to zval containers (see Tabella 44-1).
Tabella 44-1. API Macros for Accessing zval Containers
Macro | Refers to |
Z_LVAL(zval) | (zval).value.lval |
Z_DVAL(zval) | (zval).value.dval |
Z_STRVAL(zval) | (zval).value.str.val |
Z_STRLEN(zval) | (zval).value.str.len |
Z_ARRVAL(zval) | (zval).value.ht |
Z_LVAL_P(zval) | (*zval).value.lval |
Z_DVAL_P(zval) | (*zval).value.dval |
Z_STRVAL_P(zval_p) | (*zval).value.str.val |
Z_STRLEN_P(zval_p) | (*zval).value.str.len |
Z_ARRVAL_P(zval_p) | (*zval).value.ht |
Z_LVAL_PP(zval_pp) | (**zval).value.lval |
Z_DVAL_PP(zval_pp) | (**zval).value.dval |
Z_STRVAL_PP(zval_pp) | (**zval).value.str.val |
Z_STRLEN_PP(zval_pp) | (**zval).value.str.len |
Z_ARRVAL_PP(zval_pp) | (**zval).value.ht |
The PHP Streams API introduces a unified approach to the handling of files and sockets in PHP extension. Using a single API with standard functions for common operations, the streams API allows your extension to access files, sockets, URLs, memory and script-defined objects. Streams is a run-time extensible API that allows dynamically loaded modules (and scripts!) to register new streams.
The aim of the Streams API is to make it comfortable for developers to open files, URLs and other streamable data sources with a unified API that is easy to understand. The API is more or less based on the ANSI C stdio family of functions (with identical semantics for most of the main functions), so C programmers will have a feeling of familiarity with streams.
The streams API operates on a couple of different levels: at the base level, the API defines php_stream objects to represent streamable data sources. On a slightly higher level, the API defines php_stream_wrapper objects which "wrap" around the lower level API to provide support for retrieving data and meta-data from URLs. 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.
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
|
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 Function | PHP Streams Function | Notes |
---|---|---|
fopen | php_stream_open_wrapper | Streams includes additional parameters |
fclose | php_stream_close | |
fgets | php_stream_gets | |
fread | php_stream_read | The nmemb parameter is assumed to have a value of 1, so the prototype looks more like read(2) |
fwrite | php_stream_write | The nmemb parameter is assumed to have a value of 1, so the prototype looks more like write(2) |
fseek | php_stream_seek | |
ftell | php_stream_tell | |
rewind | php_stream_rewind | |
feof | php_stream_eof | |
fgetc | php_stream_getc | |
fputc | php_stream_putc | |
fflush | php_stream_flush | |
puts | php_stream_puts | Same semantics as puts, NOT fputs |
fstat | php_stream_stat | Streams has a richer stat structure |
All streams are registered as resources when they are created. This ensures that they will be properly cleaned up even if there is some fatal error. All of the filesystem functions in PHP operate on streams resources - that means that your extensions can accept regular PHP file pointers as parameters to, and return streams from their functions. The streams API makes this process as painless as possible:
Esempio 45-2. How to accept a stream as a parameter
|
Esempio 45-3. How to return a stream from a function
|
Since streams are automatically cleaned up, it's tempting to think that we can get away with being sloppy programmers and not bother to close the streams when we are done with them. Although such an approach might work, it is not a good idea for a number of reasons: streams hold locks on system resources while they are open, so leaving a file open after you have finished with it could prevent other processes from accessing it. If a script deals with a large number of files, the accumulation of the resources used, both in terms of memory and the sheer number of open files, can cause web server requests to fail. Sounds bad, doesn't it? The streams API includes some magic that helps you to keep your code clean - if a stream is not closed by your code when it should be, you will find some helpful debugging information in you web server error log.
Nota: Always use a debug build of PHP when developing an extension (--enable-debug when running configure), as a lot of effort has been made to warn you about memory and stream leaks.
In some cases, it is useful to keep a stream open for the duration of a request, to act as a log or trace file for example. Writing the code to safely clean up such a stream is not difficult, but it's several lines of code that are not strictly needed. To save yourself the 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().
(no version information, might be only in CVS)
php_stream_stat_path -- Gets the status for a file or URLphp_stream_stat_path() examines the file or URL specified by path and returns information such as file size, access and creation times and so on. The return value is 0 on success, -1 on error. For more information about the information returned, see php_stream_statbuf.
(no version information, might be only in CVS)
php_stream_stat -- Gets the status for the underlying storage associated with a streamphp_stream_stat() examines the storage to which stream is bound, and returns information such as file size, access and creation times and so on. The return value is 0 on success, -1 on error. For more information about the information returned, see php_stream_statbuf.
(no version information, might be only in CVS)
php_stream_open_wrapper -- Opens a stream on a file or URLphp_stream_open_wrapper() opens a stream on the file, URL or other wrapped resource specified by path. Depending on the value of mode, the stream may be opened for reading, writing, appending or combinations of those. See the table below for the different modes that can be used; in addition to the characters listed below, you may include the character 'b' either as the second or last character in the mode string. The presence of the 'b' character informs the relevant stream implementation to open the stream in a binary safe mode.
The 'b' character is ignored on all POSIX conforming systems which treat binary and text files in the same way. It is a good idea to specify the 'b' character whenever your stream is accessing data where the full 8 bits are important, so that your code will work when compiled on a system where the 'b' flag is important.
Any local files created by the streams API will have their initial permissions set according to the operating system defaults - under Unix based systems this means that the umask of the process will be used. Under Windows, the file will be owned by the creating process. Any remote files will be created according to the URL wrapper that was used to open the file, and the credentials supplied to the remote server.
Open text file for reading. The stream is positioned at the beginning of the file.
Open text file for reading and writing. The stream is positioned at the beginning of the file.
Truncate the file to zero length or create text file for writing. The stream is positioned at the beginning of the file.
Open text file for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.
Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file.
Open text file for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file.
options affects how the path/URL of the stream is interpreted, safe mode checks and actions taken if there is an error during opening of the stream. See Stream open options for more information about options.
If opened is not NULL, it will be set to a string containing the name of the actual file/resource that was opened. This is important when the options include USE_PATH, which causes the include_path to be searched for the file. You, the caller, are responsible for calling efree() on the filename returned in this parameter.
Nota: If you specified STREAM_MUST_SEEK in options, the path returned in opened may not be the name of the actual stream that was returned to you. It will, however, be the name of the original resource from which the seekable stream was manufactured.
(no version information, might be only in CVS)
php_stream_read -- Read a number of bytes from a stream into a bufferphp_stream_read() reads up to count bytes of data from stream and copies them into the buffer buf.
php_stream_read() returns the number of bytes that were read successfully. There is no distinction between a failed read or an end-of-file condition - use php_stream_eof() to test for an EOF.
The internal position of the stream is advanced by the number of bytes that were read, so that subsequent reads will continue reading from that point.
If less than count bytes are available to be read, this call will block (or wait) until the required number are available, depending on the blocking status of the stream. By default, a stream is opened in blocking mode. When reading from regular files, the blocking mode will not usually make any difference: when the stream reaches the EOF php_stream_read() will return a value less than count, and 0 on subsequent reads.
(no version information, might be only in CVS)
php_stream_write -- Write a number of bytes from a buffer to a streamphp_stream_write() writes count bytes of data from buf into stream.
php_stream_write() returns the number of bytes that were 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.
(no version information, might be only in CVS)
php_stream_eof -- Check for an end-of-file condition on a streamphp_stream_eof() checks for an end-of-file condition on stream.
php_stream_eof() returns the 1 to indicate EOF, 0 if there is no EOF and -1 to indicate an error.
php_stream_getc() reads a single character from stream and returns it as an unsigned char cast as an int, or EOF if the end-of-file is reached, or an error occurred.
php_stream_getc() may block in the same way as php_stream_read() blocks.
The internal position of the stream is advanced by 1 if successful.
(no version information, might be only in CVS)
php_stream_gets -- Read a line of data from a stream into a bufferphp_stream_gets() reads up to count-1 bytes of data from stream and copies them into the buffer buf. Reading stops after an EOF or a newline. If a newline is read, it is stored in buf as part of the returned data. A NUL terminating character is stored as the last character in the buffer.
php_stream_read() returns buf when successful or NULL otherwise.
The internal position of the stream is advanced by the number of bytes that were read, so that subsequent reads will continue reading from that point.
This function may block in the same way as php_stream_read().
php_stream_close() safely closes stream and releases the resources associated with it. After stream has been closed, it's value is undefined and should not be used.
php_stream_close() returns 0 if the stream was closed or EOF to indicate an error. Regardless of the success of the call, stream is undefined and should not be used after a call to this function.
php_stream_flush() causes any data held in write buffers in stream to be committed to the underlying storage.
php_stream_flush() returns 0 if the buffers were flushed, or if the buffers did not need to be flushed, but returns EOF to indicate an error.
php_stream_seek() repositions the internal position of stream. The new position is determined by adding the offset to the position indicated by whence. If whence is set to SEEK_SET, SEEK_CUR or SEEK_END the offset is relative to the start of the stream, the current position or the end of the stream, respectively.
php_stream_seek() returns 0 on success, but -1 if there was an error.
Nota: Not all streams support seeking, although the streams API will emulate a seek if whence is set to SEEK_CUR and offset is positive, by calling php_stream_read() to read (and discard) offset bytes.
The emulation is only applied when the underlying stream implementation does not support seeking. If the stream is (for example) a file based stream that is wrapping a non-seekable pipe, the streams api will not apply emulation because the file based stream implements a seek operation; the seek will fail and an error result will be returned to the caller.
php_stream_tell() returns the internal position of stream, relative to the start of the stream. If there is an error, -1 is returned.
(no version information, might be only in CVS)
php_stream_copy_to_stream -- Copy data from one stream to anotherphp_stream_copy_to_stream() attempts to read up to maxlen bytes of data from src and write them to dest, and returns the number of bytes that were successfully copied.
If you want to copy all remaining data from the src stream, pass the constant PHP_STREAM_COPY_ALL as the value of maxlen.
Nota: This function will attempt to copy the data in the most efficient manner, using memory mapped files when possible.
(no version information, might be only in CVS)
php_stream_copy_to_mem -- Copy data from stream and into an allocated bufferphp_stream_copy_to_mem() allocates a buffer maxlen+1 bytes in length using pemalloc() (passing persistent). It then reads maxlen bytes from src and stores them in the allocated buffer.
The allocated buffer is returned in buf, and the number of bytes successfully read. You, the caller, are responsible for freeing the buffer by passing it and persistent to pefree().
If you want to copy all remaining data from the src stream, pass the constant PHP_STREAM_COPY_ALL as the value of maxlen.
Nota: This function will attempt to copy the data in the most efficient manner, using memory mapped files when possible.
(no version information, might be only in CVS)
php_stream_make_seekable -- Convert a stream into a stream is seekablephp_stream_make_seekable() checks if origstream is seekable. If it is not, it will copy the data into a new temporary stream. If successful, newstream is always set to the stream that is valid to use, even if the original stream was seekable.
flags allows you to specify your preference for the 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
Value | Meaning |
---|---|
PHP_STREAM_UNCHANGED | Original stream was seekable anyway. newstream is set to the value of origstream. |
PHP_STREAM_RELEASED | Original stream was not seekable and has been released. newstream is set to the new seekable stream. You should not access origstream anymore. |
PHP_STREAM_FAILED | An error occurred while attempting conversion. newstream is set to NULL; origstream is still valid. |
PHP_STREAM_CRITICAL | An error occurred while attempting conversion that has left origstream in an indeterminate state. newstream is set to NULL and it is highly recommended that you close origstream. |
Nota: If you need to seek and write to the stream, it does not make sense to use this function, because the stream it returns is not guaranteed to be bound to the same resource as the original stream.
Nota: If you only need to seek forwards, there is no need to call this function, as the streams API will emulate forward seeks when the whence parameter is SEEK_CUR.
Nota: If origstream is network based, this function will block until the whole contents have been downloaded.
Nota: NEVER call this function with an origstream that is reference by a file pointer in a PHP script! This function may cause the underlying stream to be closed which could cause a crash when the script next accesses the file pointer!
Nota: In many cases, this function can only succeed when origstream is a newly opened stream with no data buffered in the stream layer. For that reason, and because this function is complicated to use correctly, it is recommended that you use php_stream_open_wrapper() and pass in PHP_STREAM_MUST_SEEK in your options instead of calling this function directly.
(no version information, might be only in CVS)
php_stream_cast -- Convert a stream into another form, such as a FILE* or socketphp_stream_cast() attempts to convert stream into a resource indicated by castas. If ret is NULL, the stream is queried to find out if such a conversion is possible, without actually performing the conversion (however, some internal stream state *might* be changed in this case). If flags is set to REPORT_ERRORS, an error message will be displayed is there is an error during conversion.
Nota: This function returns SUCCESS for success or FAILURE for failure. Be warned that you must explicitly compare the return value with SUCCESS or FAILURE because of the underlying values of those constants. A simple boolean expression will not be interpreted as you intended.
Tabella 45-1. Resource types for castas
Value | Meaning |
---|---|
PHP_STREAM_AS_STDIO | Requests an ANSI FILE* that represents the stream |
PHP_STREAM_AS_FD | Requests a POSIX file descriptor that represents the stream |
PHP_STREAM_AS_SOCKETD | Requests a network socket descriptor that represents the stream |
In addition to the basic resource types above, the conversion process can be altered by using the following flags by using the OR operator to combine the resource type with one or more of the following values:
Tabella 45-2. Resource types for castas
Value | Meaning |
---|---|
PHP_STREAM_CAST_TRY_HARD | Tries as hard as possible, at the expense of additional resources, to ensure that the conversion succeeds |
PHP_STREAM_CAST_RELEASE | Informs the streams API that some other code (possibly a third party library) will be responsible for closing the underlying handle/resource. This causes the stream to be closed in such a way the underlying handle is preserved and returned in ret. If this function succeeds, stream should be considered closed and should no longer be used. |
Nota: If your system supports fopencookie() (systems using glibc 2 or later), the streams API will always be able to synthesize an ANSI FILE* pointer over any stream. While this is tremendously useful for passing any PHP stream to any third-party libraries, such behaviour is not portable. You are requested to consider the portability implications before distributing you extension. If the fopencookie synthesis is not 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().
(no version information, might be only in CVS)
php_stream_can_cast -- Determines if a stream can be converted into another form, such as a FILE* or socketThis function is equivalent to calling php_stream_cast() with ret set to NULL and flags set to 0. It returns SUCCESS if the stream can be converted into the form requested, or FAILURE if the conversion cannot be performed.
Nota: Although this function will not perform the conversion, some internal stream state *might* be changed by this call.
Nota: You must 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().
(no version information, might be only in CVS)
php_stream_is_persistent -- Determines if a stream is a persistent streamphp_stream_is_persistent() returns 1 if the stream is a persistent stream, 0 otherwise.
(no version information, might be only in CVS)
php_stream_is -- Determines if a stream is of a particular typephp_stream_is() returns 1 if stream is of the type specified by istype, or 0 otherwise.
Tabella 45-1. Values for istype
Value | Meaning |
---|---|
PHP_STREAM_IS_STDIO | The stream is implemented using the stdio implementation |
PHP_STREAM_IS_SOCKET | The stream is implemented using the network socket implementation |
PHP_STREAM_IS_USERSPACE | The stream is implemented using the userspace object implementation |
PHP_STREAM_IS_MEMORY | The stream is implemented using the grow-on-demand memory stream implementation |
Nota: The PHP_STREAM_IS_XXX "constants" are actually defined as pointers to the underlying stream operations structure. If your extension (or some other extension) defines additional streams, it should also declare a PHP_STREAM_IS_XXX constant in it's header file that you can use as the basis of this comparison.
Nota: This function is implemented as a simple (and fast) pointer comparison, and does not change the stream state in any way.
See also php_stream_cast() and php_stream_can_cast().
(no version information, might be only in CVS)
php_stream_passthru -- Outputs all remaining data from a streamphp_stream_passthru() outputs all remaining data from stream to the active output buffer and returns the number of bytes output. If buffering is disabled, the data is written straight to the output, which is the browser making the request in the case of PHP on a web server, or stdout for CLI based PHP. This function will use memory mapped files if possible to help improve performance.
(no version information, might be only in CVS)
php_register_url_stream_wrapper -- Registers a wrapper with the Streams APIphp_register_url_stream_wrapper() registers wrapper as the handler for the protocol specified by protocol.
Nota: If you call this function from a loadable module, you *MUST* call php_unregister_url_stream_wrapper() in your module shutdown function, otherwise PHP will crash.
(no version information, might be only in CVS)
php_unregister_url_stream_wrapper -- Unregisters a wrapper from the Streams APIphp_unregister_url_stream_wrapper() unregisters the wrapper associated with protocol.
(no version information, might be only in CVS)
php_stream_open_wrapper_ex -- Opens a stream on a file or URL, specifying contextphp_stream_open_wrapper_ex() is exactly like php_stream_open_wrapper(), but allows you to specify a php_stream_context object using context. To find out more about stream contexts, see XXX
(no version information, might be only in CVS)
php_stream_open_wrapper_as_file -- Opens a stream on a file or URL, and converts to a FILE*php_stream_open_wrapper_as_file() is exactly like php_stream_open_wrapper(), but converts the stream into an ANSI stdio FILE* and returns that instead of the stream. This is a convenient shortcut for extensions that pass FILE* to third-party libraries.
(no version information, might be only in CVS)
php_stream_filter_register_factory -- Registers a filter factory with the Streams APIUse 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.
(no version information, might be only in CVS)
php_stream_filter_unregister_factory -- Deregisters a filter factory with the Streams APIDeregisters 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.
The functions listed in this section work on local files, as well as remote files (provided that the wrapper supports this functionality!).
(no version information, might be only in CVS)
php_stream_opendir -- Open a directory for file enumerationphp_stream_opendir() returns a stream that can be used to list the files that are contained in the directory specified by path. This function is functionally equivalent to POSIX opendir(). Although this function returns a php_stream object, it is not recommended to try to use the functions from the common API on these streams.
(no version information, might be only in CVS)
php_stream_readdir -- Fetch the next directory entry from an opened dirphp_stream_readdir() reads the next directory entry from dirstream and stores it into ent. If the function succeeds, the return value is ent. If the function fails, the return value is NULL. See php_stream_dirent for more details about the information returned for each directory entry.
(no version information, might be only in CVS)
php_stream_rewinddir -- Rewind a directory stream to the first entryphp_stream_rewinddir() rewinds a directory stream to the first entry. Returns 0 on success, but -1 on failure.
(no version information, might be only in CVS)
php_stream_fopen_from_file -- Convert an ANSI FILE* into a streamphp_stream_fopen_from_file() returns a stream based on the file. mode must be the same as the mode used to open file, otherwise strange errors may occur when trying to write when the mode of the stream is different from the mode on the file.
(no version information, might be only in CVS)
php_stream_fopen_tmpfile -- Open a FILE* with tmpfile() and convert into a streamphp_stream_fopen_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.
(no version information, might be only in CVS)
php_stream_fopen_temporary_file -- Generate a temporary file name and open a stream on itphp_stream_fopen_temporary_file() generates a temporary file name in the directory specified by dir and with a prefix of pfx. The generated file name is returns in the opened parameter, which you are responsible for cleaning up using efree(). A stream is opened on that generated filename in "w+b" mode. The file is NOT automatically deleted; you are responsible for unlinking or moving the file when you have finished with it.
(no version information, might be only in CVS)
php_stream_sock_open_from_socket -- Convert a socket descriptor into a streamphp_stream_sock_open_from_socket() returns a stream based on the socket. persistent is a flag that controls whether the stream is opened as a persistent stream. Generally speaking, this parameter will usually be 0.
(no version information, might be only in CVS)
php_stream_sock_open_host -- Open a connection to a host and return a streamphp_stream_sock_open_host() establishes a connect to the specified host and port. socktype specifies the connection semantics that should apply to the connection. Values for socktype are system dependent, but will usually include (at a minimum) SOCK_STREAM for sequenced, reliable, two-way connection based streams (TCP), or SOCK_DGRAM for connectionless, unreliable messages of a fixed maximum length (UDP).
persistent is a flag the controls whether the stream is opened as a persistent stream. Generally speaking, this parameter will usually be 0.
If not NULL, timeout specifies a maximum time to allow for the connection to be made. If the connection attempt takes longer than the timeout value, the connection attempt is aborted and NULL is returned to indicate that the stream could not be opened.
Nota: The timeout value does not include the time taken to perform a DNS lookup. The reason for this is because there is no portable way to implement a non-blocking DNS lookup.
The timeout only applies to the connection phase; if you need to set timeouts for subsequent read or write operations, you should use php_stream_sock_set_timeout() to configure the timeout duration for your stream once it has been opened.
The streams API places no restrictions on the values you use for socktype, but encourages you to consider the portability of values you choose before you release your extension.
(no version information, might be only in CVS)
php_stream_sock_open_unix -- Open a Unix domain socket and convert into a streamphp_stream_sock_open_unix() attempts to open the Unix domain socket specified by path. pathlen specifies the length of path. If timeout is not NULL, it specifies a timeout period for the connection attempt. persistent indicates if the stream should be opened as a persistent stream. Generally speaking, this parameter will usually be 0.
Nota: This function will not work under Windows, which does not implement Unix domain sockets. A possible exception to this rule is if your PHP binary was built using cygwin. You are encouraged to consider this aspect of the portability of your extension before it's release.
Nota: This function treats path in a binary safe manner, suitable for use on systems with an abstract namespace (such as Linux), where the first character of path is a NUL character.
|
d_name
holds the name of the file, relative to the directory
being scanned.
typedef struct _php_stream_ops { /* all streams MUST implement these operations */ size_t (*write)(php_stream *stream, const char *buf, size_t count TSRMLS_DC); size_t (*read)(php_stream *stream, char *buf, size_t count TSRMLS_DC); int (*close)(php_stream *stream, int close_handle TSRMLS_DC); int (*flush)(php_stream *stream TSRMLS_DC); const char *label; /* name describing this class of stream */ /* these operations are optional, and may be set to NULL if the stream does not * support a particular operation */ int (*seek)(php_stream *stream, off_t offset, int whence TSRMLS_DC); char *(*gets)(php_stream *stream, char *buf, size_t size TSRMLS_DC); int (*cast)(php_stream *stream, int castas, void **ret TSRMLS_DC); int (*stat)(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC); } php_stream_ops; |
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; |
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 { 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; |
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; |
One or more of these values can be combined using the OR operator.
This is the default option for streams; it requests that the include_path is not to be searched for the requested file.
Requests that the include_path is to be searched for the requested file.
Requests that registered URL wrappers are to be ignored when opening the stream. Other non-URL wrappers will be taken into consideration when decoding the path. There is no opposite form for this flag; the streams API will use all registered wrappers by default.
On Windows systems, this is equivalent to IGNORE_URL. On all other systems, this flag has no effect.
Requests that the underlying stream implementation perform safe_mode checks on the file before opening the file. Omitting this flag will skip safe_mode checks and allow opening of any file that the PHP process has rights to access.
If this flag is set, and there was an error during the opening of the file or URL, the streams API will call the php_error function for you. This is useful because the path may contain username/password information that should not be displayed in the browser output (it would be a security risk to do so). When the streams API raises the error, it first strips username/password information from the path, making the error message safe to display in the browser.
This flag is useful when your extension really must be able to randomly seek around in a stream. Some streams may not be seekable in their native form, so this flag asks the streams API to check to see if the stream does support seeking. If it does not, it will copy the stream into temporary storage (which may be a temporary file or a memory stream) which does support seeking. Please note that this flag is not useful when you want to seek the stream and write to it, because the stream you are accessing might not be bound to the actual resource you requested.
Nota: If the requested resource is network based, this flag will cause the opener to block until the whole contents have been downloaded.
If your extension is using a third-party library that expects a FILE* or file descriptor, you can use this flag to request the streams API to open the resource but avoid buffering. You can then use php_stream_cast() to retrieve the FILE* or file descriptor that the library requires.
The is particularly useful when accessing HTTP URLs where the start of the actual stream data is found after an indeterminate offset into the stream.
Since this option disables buffering at the streams API level, you may experience lower performance when using streams functions on the stream; this is deemed acceptable because you have told streams that you will be using the functions to match the underlying stream implementation. Only use this option when you are sure you need it.
Questa sezione contiene le domande più generali riguardanti il PHP: cos'è e cosa fa.
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.
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.
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.
Sì. Fare riferimento al file INSTALL incluso nella distribuzione del codice sorgente di PHP 4. Fare inoltre riferimento alla relativa appendice.
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
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/.
Questa sezione contiene domande su come fare per entrare in contatto con la comunità PHP. Il modo migliore è tramite le mailing list.
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 .
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.
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.
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/
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.
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.
Questa sezione contiene dettagli riguardanti le modalità di download di PHP e argomenti relativi ai Sistemi Operativi.
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.
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.
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.
LDAP (Unix/Win) : Netscape Directory (LDAP) SDK 1.1.
Berkeley DB2 (Unix/Win) : http://www.sleepycat.com/.
Sybase-CT* (Linux, libc5) : Disponibile in locale.
È 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.
Un file browscap.ini può essere trovato qui http://www.garykeith.com/browsers/downloads.asp.
This section holds common questions about relation between PHP and databases. Yes, PHP can access virtually any database available today.
On Windows machines, you can simply use the included ODBC support and the correct ODBC driver.
On Unix machines, you can use the Sybase-CT driver to access Microsoft SQL Servers because they are (at least mostly) protocol-compatible. Sybase has made a free version of the necessary libraries for Linux systems. For other Unix operating systems, you need to contact Sybase for the correct libraries. Also see the answer to the next question.
Yes. You already have all the tools you need if you are running entirely under Windows 9x/Me, or NT/2000, where you can use ODBC and Microsoft's ODBC drivers for Microsoft Access databases.
If you are running PHP on a Unix box and want to talk to MS Access on a Windows box you will need Unix ODBC drivers. OpenLink Software has Unix-based ODBC drivers that can do this. There is a free pilot program where you can download an evaluation copy that doesn't expire and prices start at $675 for the commercial supported version.
Another alternative is to use an SQL server that has Windows ODBC drivers and use that to store the data, which you can then access from Microsoft Access (using ODBC) and PHP (using the built in drivers), or to use an intermediary file format that Access and PHP both understand, such as flat files or dBase databases. On this point Tim Hayes from OpenLink software writes:
Using another database as an intermediary is not a good idea, when you can use ODBC from PHP straight to your database - i.e. with OpenLink's drivers. If you do need to use an intermediary file format, OpenLink have now released Virtuoso (a virtual database engine) for NT, Linux and other Unix platforms. Please visit our website for a free download.
One option that has 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; } ?> |
<?php $result = mysql_query("SELECT * FROM tables_priv") or die("Bad query: " . mysql_error()); ?> |
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.
[mybox:user /src/php4] root# apachectl configtest apachectl: /usr/local/apache/bin/httpd Undefined symbols: _compress _uncompress |
cgi error: The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are: |
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 |
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 |
AddType application/x-httpd-php3 .php3 /* per PHP 3 */ AddType application/x-httpd-php .php /* per PHP 4 */ |
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 \ |
./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 |
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.
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.
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!
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 |
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.
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.
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.
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 = ' '; # substituted via Makefile.tmpl my $CFG_LD_SHLIB = ' '; # substituted via Makefile.tmpl my $CFG_LDFLAGS_SHLIB = ' '; # substituted via Makefile.tmpl |
my $CFG_CFLAGS_SHLIB = '-fpic -DSHARED_MODULE'; # substituted via Makefile.tmpl my $CFG_LD_SHLIB = 'gcc'; # substituted via Makefile.tmpl my $CFG_LDFLAGS_SHLIB = q(-shared); # substituted via Makefile.tmpl |
my $CFG_LIBEXECDIR = 'modules'; # substituted via APACI install |
my $CFG_LIBEXECDIR = '/usr/lib/apache'; # substituted via APACI install |
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 |
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(); ?> |
This section gathers many common errors that you may face while writing PHP scripts.
<?php function myfunc($argument) { echo $argument + 10; } $variable = 10; echo "myfunc($variable) = " . myfunc($variable); ?> |
<pre> <?php echo "This should be the first line."; ?> <?php echo "This should show up after the new line above."; ?> </pre> |
1. I would like to write a generic PHP script that can handle data coming from any form. How do I know which POST method variables are available?
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.
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.
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()
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.
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.
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
PHP and HTML interact a lot: PHP can generate HTML, and HTML can pass information to PHP. Before reading these faqs, it's important you learn how to retrieve variables from outside of PHP. The manual page on this topic includes many examples as well. Pay close attention to what register_globals means to you too.
There are several stages for which encoding is important. Assuming that you have a string $data, which contains the string you want to pass on in a non-encoded way, these are the relevant stages:
HTML interpretation. In order to specify a random string, you must include it in double quotes, and htmlspecialchars() the whole value.
URL: A URL consists of several parts. If you want your data to be interpreted as one item, you must encode it with urlencode().
Nota: It is wrong to urlencode() $data, because it's the browsers responsibility to urlencode() the data. All popular browsers do that correctly. Note that this will happen regardless of the method (i.e., GET or POST). You'll only notice this in case of GET request though, because POST requests are usually hidden.
Nota: The data is shown in the browser as intended, because the browser will interpret the HTML escaped symbols.
Upon submitting, either via GET or POST, the data will be urlencoded by the browser for transferring, and directly urldecoded by PHP. So in the end, you don't need to do any urlencoding/urldecoding yourself, everything is handled automagically.
Nota: In fact you are faking a HTML GET request, therefore it's necessary to manually urlencode() the data.
Nota: You need to htmlspecialchars() the whole URL, because the URL occurs as value of an HTML-attribute. In this case, the browser will first un-htmlspecialchars() the value, and then pass the URL on. PHP will understand the URL correctly, because you urlencoded() the data.
You'll notice that the & in the URL is replaced by &. Although most browsers will recover if you forget this, this isn't always possible. So even if your URL is not dynamic, you need to htmlspecialchars() the URL.
2. I'm trying to use an <input type="image"> tag, but the $foo.x and $foo.y variables aren't available. $_GET['foo.x'] isn't existing either. Where are they?
When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:
<input type="image" src="image.gif" name="foo" /> |
Because foo.x and foo.y would make invalid variable names in PHP, they are automagically converted to foo_x and foo_y. That is, the periods are replaced with underscores. So, you'd access these variables like any other described within the section on retrieving variables from outside of PHP. For example, $_GET['foo_x'].
To get your <form> result sent as an array to your PHP script you name the <input>, <select> or <textarea> elements like this:
<input name="MyArray[]" /> <input name="MyArray[]" /> <input name="MyArray[]" /> <input name="MyArray[]" /> |
<input name="MyArray[]" /> <input name="MyArray[]" /> <input name="MyOtherArray[]" /> <input name="MyOtherArray[]" /> |
<input name="AnotherArray[]" /> <input name="AnotherArray[]" /> <input name="AnotherArray[email]" /> <input name="AnotherArray[phone]" /> |
Nota: Specifying an arrays key is optional in HTML. If you do not specify the keys, the array gets filled in the order the elements appear in the form. Our first example will contain keys 0, 1, 2 and 3.
See also Array Functions and Variables from outside PHP.
The select multiple tag in an HTML construct allows users to select multiple items from a list. These items are then passed to the action handler for the form. The problem is that they are all passed with the same widget name. I.e.
<select name="var" multiple="yes"> |
var=option1 var=option2 var=option3 |
<select name="var[]" multiple="yes"> |
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[]']; |
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(); } ?> |
PHP può essere usato per accedere a oggetti COM o DCOM sotto piattaforme Win32.
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.
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.
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.
No, non puoi. Le istanze COM sono trattate come risorse e quindi sono disponibili solo nel contesto di un singolo script.
Attualmente non è possibile bloccare gli errori COM nei soliti modi disponibili in PHP (@, track_errors, ...), ma stiamo pensando di implementare questa funzione.
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
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.
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.
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.
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 :)
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.
PHP è il miglior linguaggio di programmazione per la programmazione web, ma cosa si può dire sugli altri linguaggi?
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.
Sì, uno dei più famosi e consigliati è asp2php.
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.
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.
PHP ha già una lunga storia dietro di se: Il leggendario PHP 1.0, PHP/FI, PHP 3.0 e PHP 4.0.
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.
PHP ha già una lunga storia dietro di se: Il leggendario PHP 1.0, PHP/FI, PHP 3.0 e PHP 4.0.
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.
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.
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.
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.
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.
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.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.
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.
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.
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.
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 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.
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.
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!
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.
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
|
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.
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.
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:
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_commit_ret() - Commit a transaction without closing it
ibase_db_info() - Request statistics about a database
ibase_drop_db() - Drops a database
ibase_errcode() - Return an error code
ibase_free_event_handler() - Cancels a registered event handler
ibase_gen_id() - Increments the named generator and returns its new value
ibase_maintain_db() - Execute a maintenance command on the database server
ibase_name_result() - Assigns a name to a 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_restore() - Initiates a restore task in the service manager and returns immediately
ibase_rollback_ret() - Rollback transaction and retain the transaction context
ibase_server_info() - Request statistics about a database
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_wait_event() - Wait for an event to be posted by the database
iconv:
iconv_mime_decode() - Decodes a MIME header field
iconv_mime_decode_headers() - Decodes multiple MIME header fields at once
iconv_mime_encode() - Composes a MIME header field
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
Streams:
stream_copy_to_stream() - Copies data from one stream to another
stream_get_line() - Gets line from stream resource up to a given delimiter
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
Other:
convert_uudecode() - decode a uuencoded string
convert_uuencode() - uuencode a string
curl_copy_handle() - Copy a cURL handle along with all of it's preferences
dba_key_split() - Splits a key in string representation into array representation
dbase_get_header_info() - Get the header info of a dBase database
dbx_fetch_row() - Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set
fbsql_set_password() - Change the password for a given user
file_put_contents() - Write a string to a file
ftp_alloc() - Allocates space for a file to be uploaded
get_declared_interfaces() - Returns an array of all declared interfaces
get_headers() - Fetches all the headers sent by the server in response to a HTTP request
headers_list() - Returns a list of response headers sent (or ready to send)
http_build_query() - Generate URL-encoded query string
idate() - Format a local time/date as integer
image_type_to_extension() - Get file extension for image-type returned by getimagesize(), exif_read_data(), exif_thumbnail(), exif_imagetype()
imagefilter() - Applies Filter an image using a custom angle
imap_getacl() - Gets the ACL for a given mailbox
ldap_sasl_bind() - Bind to LDAP directory using SASL
mb_list_encodings() - Returns an array of all supported encodings
pcntl_getpriority() - Get the priority of any process
pcntl_wait() - Waits on or returns the status of a forked child as defined by the waitpid() system call
pg_version() - Returns an array with client, protocol and server version (when available)
php_check_syntax() - Check the syntax of the specified file
php_strip_whitespace() - Return source with stripped comments and whitespace
proc_nice() - Change the priority of the current process
pspell_config_data_dir() - Change location of language data files
pspell_config_dict_dir() - Change location of the main word list
setrawcookie() - Send a cookie with no url encoding of the value
snmp_read_mib() - Reads and parses a MIB file into the active MIB tree
sqlite_fetch_column_types() - Return an array of column types from a particular table
str_split() - Convert a string to an array
strpbrk() - Search a string for any of a set of characters
substr_compare() - Binary safe optionally case insensitive comparison of two strings from an offset, up to length characters
time_nanosleep() - Delay for a number of seconds and nano seconds
Nota: The Tidy extension has also changed its API completely.
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)
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.
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.
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.
|
With PHP 5, private and protected methods are also introduced.
Esempio B-5. Protected methods example
|
Old code that has no user-defined classes or functions named "public", "protected" or "private" should run without modifications.
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.
Abstract classes cannot be instantiated. Old code that has no user-defined classes or functions named 'abstract' should run without modifications.
PHP 5 introduces interfaces. A class may implement an arbitrary list of interfaces.
Old code that has no user-defined classes or functions named 'interface' or 'implements' should run without modifications.
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.
These class type hints are not checked upon compilation, as would be the case in a typed language, but during runtime. This means that:
is equivalent to:
PHP 5 introduces the "final" keyword to declare final members and methods. Methods and members declared final cannot be overridden by sub-classes.
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.
Properties can not be final.
Old code that has no user-defined classes or functions named 'final' should run without modifications.
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 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
|
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.
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.
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.
PHP 5 introduces per-class constants:
Old code that has no user-defined classes or functions named 'const' will run without modifications.
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.
Old code that has no user-defined classes or functions 'catch', 'throw' and 'try' will run without modifications.
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
|
Static member variables of static classes can now be initialized.
PHP 5 introduces the 'static' keyword to declare a method static, thus callable from outside the object context.
The pseudo variable $this is not available inside a method that has been declared static.
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.
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 that are passed by reference to a function may now have default values
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.
Both method calls and property accesses can be overloaded via the __call(), __get() and __set() methods.
Esempio B-22. __get() and __set()
|
Objects may be iterated in an overloaded way when used with foreach. The default behavior is to iterate over all properties.
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
|
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
|
The new __toString() magic method allows you to overload the object to string conversion.
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
|
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
PHP 4 and the integrated Zend engine have greatly improved PHP's performance and capabilities, but great care has been taken to break as little existing code as possible. So migrating your code from PHP 3 to 4 should be much easier than migrating from PHP/FI 2 to PHP 3. A lot of existing PHP 3 code should be ready to run without changes, but you should still know about the few differences and take care to test your code before switching versions in production environments. The following should give you some hints about what to look for.
Recent operating systems provide the ability to perform versioning and scoping. This features make it possible to let PHP 3 and PHP 4 run as concurrent modules in one Apache server.
This feature is known to work on the following platforms:
Linux with recent binutils (binutils 2.9.1.0.25 tested)
Solaris 2.5 or better
FreeBSD (3.2, 4.0 tested)
To enable it, configure 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:
The global configuration file, php3.ini, has changed its name to php.ini.
For the Apache configuration file, there are slightly more changes. The MIME types recognized by the PHP module have changed.
application/x-httpd-php3 --> application/x-httpd-php application/x-httpd-php3-source --> application/x-httpd-php-source |
You can make your configuration files work with both versions of PHP (depending on which one is currently compiled into the server), using the following syntax:
AddType application/x-httpd-php3 .php3 AddType application/x-httpd-php3-source .php3s AddType application/x-httpd-php .php AddType application/x-httpd-php-source .phps |
In addition, the PHP directive names for Apache have changed.
Starting with PHP 4.0, there are only four Apache directives that relate to PHP:
php_value [PHP directive name] [value] php_flag [PHP directive name] [On|Off] php_admin_value [PHP directive name] [value] php_admin_flag [PHP directive name] [On|Off] |
There are two differences between the Admin values and the non admin values:
Admin values (or flags) can only appear in the server-wide Apache configuration files (e.g., httpd.conf).
Standard values (or flags) cannot control certain PHP directives, for example: safe mode (if you could override safe mode settings in .htaccess files, it would defeat safe mode's purpose). In contrast, Admin values can modify the value of any PHP directive.
To make the transition process easier, PHP 4 is bundled with scripts that automatically convert your Apache configuration and .htaccess files to work with both PHP 3 and PHP 4. These scripts do NOT convert the mime type lines! You have to convert these yourself.
To convert your Apache configuration files, run the apconf-conv.sh script (available in the scripts/apache/ directory). For example:
Your original configuration file will be saved in httpd.conf.orig.
To convert your .htaccess files, run the aphtaccess-conv.sh script (available in the scripts/apache/ directory as well):
Likewise, your old .htaccess files will be saved with an .orig prefix.
The conversion scripts require awk to be installed.
Parsing and execution are now two completely separated steps, no execution of a files code will happen until the complete file and everything it requires has completely and successfully been parsed.
One of the new requirements introduced with this split is that required and included files now have to be syntactically complete. You can no longer spread the different controlling parts of a control structure across file boundaries. That is you cannot start a for or while loop, an if statement or a switch block in one file and have the end of loop, else, endif, case or break statements in a different file.
It still perfectly legal to include additional code within loops or other control structures, only the controlling keywords and corresponding curly braces {...} have to be within the same compile unit (file or eval()ed string).
This should not harm 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.
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. |
A lot of existing PHP 3 code uses language constructs that should be considered as very bad style as this code, while doing the intended thing now, could easily be broken by changes in other places. PHP 4 will output a lot of notice messages in such situations where PHP 3 didn't. The easy fix is to just turn off E_NOTICE messages, but it is usually a good idea to fix the code instead.
The most common case that will now produce notice messages is the use of unquoted string constants as array indices. Both PHP 3 and 4 will fall back to interpret these as strings if no keyword or constant is known by that name, but whenever a constant by that name had been defined anywhere else in the code it might break your script. This can even become a security risk if some intruder manages to redefine string constants in a way that makes your script give him access rights he wasn't intended to have. So PHP 4 will now warn you whenever you use unquoted string constants as for example in $_SERVER[REQUEST_METHOD]. Changing it to $_SERVER['REQUEST_METHOD'] will make the parser happy and greatly improve the style and security of your code.
Another thing PHP 4 will now tell you about is the use of uninitialized variables or array elements.
Static variable and class member initializers only accept scalar values while in PHP 3 they accepted any valid expression. This is, once again, due to the split between parsing and execution as no code has yet been executed when the parser sees the initializer.
For classes you should use constructors to initialize member variables instead. For static variables anything but a simple static value rarely makes sense anyway.
The perhaps most controversial change in behavior has happened to the behavior of the empty(). A String containing only the character '0' (zero) is now considered empty while it wasn't in PHP 3.
This new behavior makes sense in web applications, with all input fields returning strings even if numeric input is requested, and with PHP's capabilities of automatic type conversion. But on the other hand it might break your code in a rather subtle way, leading to misbehavior that is hard to track down if you do not know about what to look for.
While PHP 4 comes with a lot of new features, functions and extensions, you may still find some functions from version 3 missing. A small number of core functions has vanished because they do not work with the new scheme of splitting parsing and execution as introduced into 4 with the Zend engine. Other functions and even complete extensions have become obsolete as newer functions and extensions serve the same task better and/or in a more general way. Some functions just simply haven't been ported yet and finally some functions or extensions may be missing due to license conflicts.
As PHP 4 now separates parsing from execution it is no longer possible to change the behavior of the parser (now embedded in the Zend engine) at runtime as parsing already happened by then. So the function short_tags() no longer exists. You can still change the parsers behavior by setting appropriate values in the php.ini file.
Another feature of PHP 3 that is not a part of PHP 4 is the bundled debugging interface. There are third-party add-ons for the Zend engine which add similar functionality.
The Adabas and Solid database extensions are no more. Long live the unified ODBC extension instead.
unset(), although still available, is implemented as a language construct rather than a function.
This does not have any consequences on the behavior of unset(), but testing for "unset" using function_exists() will return FALSE as it would with other language constructs that look like functions such as echo().
Another more practical change is that it is no longer possible to call unset() indirectly, that is $func="unset"; $func($somevar) won't work anymore.
Extensions written for PHP 3 will not work with PHP 4, neither as binaries nor at the source level. It is not difficult to port extensions to PHP 4 if you have access to the original source. A detailed description of the actual porting process is not part of this text.
PHP 4 adds a new mechanism to variable substitution in strings. You can now finally access object member variables and elements from multidimensional arrays within strings.
To do so you have to enclose your variables with curly braces with the dollar sign immediately following the opening brace: {$...}
To embed the value of an object member variable into a string you simply write "text {$obj->member} text" while in PHP 3 you had to use something like "text ".$obj->member." text".
This should lead to more readable code, while it may break existing scripts written for PHP 3. But you can easily check for this kind of problem by checking for the character combination {$ in your code and by replacing it with \{$ with your favorite search-and-replace tool.
PHP 3 had the bad habit of setting cookies in the reverse order of the setcookie() calls in your code. PHP 4 breaks with this habit and creates the cookie header lines in exactly the same order as you set the cookies in the code.
This might break some existing code, but the old behaviour was so strange to understand that it deserved a change to prevent further problems in the future.
While handling of global variables had the focus on to be easy in PHP 3 and early versions of PHP 4, the focus has changed to be more secure. While in PHP 3 the following example worked fine, in PHP 4 it has to be unset(unset($GLOBALS["id"]));. This is only one issue of global variable handling. You should always have used $GLOBALS, with newer versions of PHP 4 you are forced to do so in most cases. Read more on this subject in the global references section.
PHP 3.0 è 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.
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:
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:
Stesso come con if..endif, la sintassi di while..endwhile è anche cambiata:
Avvertimento |
Usando la vecchia sintassi di while..endwhile in PHP 3.0, otterreste un ciclo infinito. |
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:
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:
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.
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.
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.
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.
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).
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:
impostare una porta TCP per il debugger nel file di configurazione (debugger.port) e attivarla (debugger.enabled).
Impostare un TCP listener sulla porta scelta (per esempio socket -l -s 1400 su UNIX).
Nel codice, eseguire "debugger_on(host)", dove host è l'indirizzo IP o il nome dell'host su cui è in esecuzione il TCP listener.
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 in ISO 8601 format (yyyy-mm-dd)
Time including microseconds: hh:mm:uuuuuu
DNS name or IP address of the host where the script error was generated.
PID (process id) on host of the process with the PHP 3 script that generated this error.
Type of line. Tells the receiving program about what it should treat the following data as:
Tabella E-1. Debugger Line Types
Name | Meaning |
---|---|
start | Tells the receiving program that a debugger message starts here. The contents of data will be the type of error message, listed below. |
message | The 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. |
frames | Number 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. |
Line data.
Tabella E-2. Debugger Error Types
Debugger | PHP 3 Internal |
---|---|
warning | E_WARNING |
error | E_ERROR |
parse | E_PARSE |
notice | E_NOTICE |
core-error | E_CORE_ERROR |
core-warning | E_CORE_WARNING |
unknown | (any other) |
Esempio E-1. Example Debugger Message
|
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.
All functions look like this:
void php3_foo(INTERNAL_FUNCTION_PARAMETERS) { } |
Arguments are always of type pval. This type contains a union which has the actual type of the argument. So, if your function takes two arguments, you would do something like the following at the top of your function:
When you change any of the passed parameters, whether they are sent by reference or by value, you can either start over with the parameter by calling pval_destructor on it, or if it's an ARRAY you want to add to, you can use functions similar to the ones in internal_functions.h which manipulate return_value as an ARRAY.
Also if you change a parameter to IS_STRING make sure you first assign the new estrdup()'ed string and the string length, and only later change the type to IS_STRING. If you change the string of a parameter which already IS_STRING or IS_ARRAY you should run pval_destructor on it first.
A function can take a variable number of arguments. If your function can take either 2 or 3 arguments, use the following:
The type of each argument is stored in the pval type field. This type can be any of the following:
Tabella F-1. PHP Internal Types
IS_STRING | String |
IS_DOUBLE | Double-precision floating point |
IS_LONG | Long integer |
IS_ARRAY | Array |
IS_EMPTY | None |
IS_USER_FUNCTION | ?? |
IS_INTERNAL_FUNCTION | ?? (if some of these cannot be passed to a function - delete) |
IS_CLASS | ?? |
IS_OBJECT | ?? |
If you get an argument of one type and would like to use it as another, or if you just want to force the argument to be of a certain type, you can use one of the following conversion functions:
convert_to_long(arg1); convert_to_double(arg1); convert_to_string(arg1); convert_to_boolean_long(arg1); /* If the string is "" or "0" it becomes 0, 1 otherwise */ convert_string_to_number(arg1); /* Converts string to either LONG or DOUBLE depending on string */ |
These function all do in-place conversion. They do not return anything.
The actual argument is stored in a union; the members are:
IS_STRING: arg1->value.str.val
IS_LONG: arg1->value.lval
IS_DOUBLE: arg1->value.dval
Any memory needed by a function should be allocated with either emalloc() or estrdup(). These are memory handling abstraction functions that look and smell like the normal malloc() and strdup() functions. Memory should be freed with efree().
There are two kinds of memory in this program: memory which is returned to the parser in a variable, and memory which you need for temporary storage in your internal function. When you assign a string to a variable which is returned to the parser you need to make sure you first allocate the memory with either emalloc() or estrdup(). This memory should NEVER be freed by you, unless you later in the same function overwrite your original assignment (this kind of programming practice is not good though).
For any temporary/permanent memory you need in your functions/library you should use the three emalloc(), estrdup(), and efree() functions. They behave EXACTLY like their counterpart functions. Anything you emalloc() or estrdup() you have to efree() at some point or another, unless it's supposed to stick around until the end of the program; otherwise, there will be a memory leak. The meaning of "the functions behave exactly like their counterparts" is: if you efree() something which was not emalloc()'ed nor estrdup()'ed you might get a segmentation fault. So please take care and free all of your wasted memory.
If you compile with "-DDEBUG", PHP will print out a list of all memory that was allocated using emalloc() and estrdup() but never freed with efree() when it is done running the specified script.
A number of macros are available which make it easier to set a variable in the symbol table:
SET_VAR_STRING(name,value)
SET_VAR_DOUBLE(name,value)
SET_VAR_LONG(name,value)
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.
If you want to define a new array in a symbol table, you should do the following.
First, you may want to check whether it exists and abort appropriately, using hash_exists() or hash_find().
Next, initialize the array:
Here's how to add new entries to it:
Esempio F-6. Adding entries to a new array
|
hash_next_index_insert() uses more or less the same logic as $foo[] = bar; in PHP 2.0.
If you are building an array to return from a function, you can initialize the array just like above by doing:
if (array_init(return_value) == FAILURE) { failed...; } |
...and then adding values with the helper functions:
add_next_index_long(return_value,long_value); add_next_index_double(return_value,double_value); add_next_index_string(return_value,estrdup(string_value)); |
Of course, if the adding isn't done right after the array initialization, you'd probably have to look for the array first:
pval *arr; if (hash_find(active_symbol_table,"foo",sizeof("foo"),(void **)&arr)==FAILURE) { can't find... } else { use arr->value.ht... } |
Note that hash_find receives a pointer to a pval pointer, and not a pval pointer.
Just about any hash function returns SUCCESS or FAILURE (except for hash_exists(), which returns a boolean truth value).
A number of macros are available to make returning values from a function easier.
The RETURN_* macros all set the return value and return from the function:
RETURN
RETURN_FALSE
RETURN_TRUE
RETURN_LONG(l)
RETURN_STRING(s,dup) If dup is TRUE, duplicates the string
RETURN_STRINGL(s,l,dup) Return string (s) specifying length (l).
RETURN_DOUBLE(d)
The RETVAL_* macros set the return value, but do not return.
RETVAL_FALSE
RETVAL_TRUE
RETVAL_LONG(l)
RETVAL_STRING(s,dup) If dup is TRUE, duplicates the string
RETVAL_STRINGL(s,l,dup) Return string (s) specifying length (l).
RETVAL_DOUBLE(d)
The string macros above will all estrdup() the passed 's' argument, so you can safely free the argument after calling the macro, or alternatively use statically allocated memory.
If your function returns boolean success/error responses, always use RETURN_TRUE and RETURN_FALSE respectively.
Your function can also return a complex data type such as an object or an array.
Returning an object:
Call object_init(return_value).
Fill it up with values. The functions available for this purpose are listed below.
Possibly, register functions for this object. In order to obtain values from the object, the function would have to fetch "this" from the active_symbol_table. Its type should be IS_OBJECT, and it's basically a regular hash table (i.e., you can use regular hash functions on .value.ht). The actual registration of the function can be done using:
add_method( return_value, function_name, function_ptr ); |
The functions used to populate an object are:
add_property_long( return_value, property_name, l ) - Add a property named 'property_name', of type long, equal to 'l'
add_property_double( return_value, property_name, d ) - Same, only adds a double
add_property_string( return_value, property_name, str ) - Same, only adds a string
add_property_stringl( return_value, property_name, str, l ) - Same, only adds a string of length 'l'
Returning an array:
Call array_init(return_value).
Fill it up with values. The functions available for this purpose are listed below.
The functions used to populate an array are:
add_assoc_long(return_value,key,l) - add associative entry with key 'key' and long value 'l'
add_assoc_double(return_value,key,d)
add_assoc_string(return_value,key,str,duplicate)
add_assoc_stringl(return_value,key,str,length,duplicate) specify the string length
add_index_long(return_value,index,l) - add entry in index 'index' with long value 'l'
add_index_double(return_value,index,d)
add_index_string(return_value,index,str)
add_index_stringl(return_value,index,str,length) - specify the string length
add_next_index_long(return_value,l) - add an array entry in the next free offset with long value 'l'
add_next_index_double(return_value,d)
add_next_index_string(return_value,str)
add_next_index_stringl(return_value,str,length) - specify the string length
PHP has a standard way of dealing with various types of resources. This replaces all of the local linked lists in PHP 2.0.
Available functions:
php3_list_insert(ptr, type) - returns the 'id' of the newly inserted resource
php3_list_delete(id) - delete the resource with the specified id
php3_list_find(id,*type) - returns the pointer of the resource with the specified id, updates 'type' to the resource's type
Typical list code would look like this:
Esempio F-8. Using an existing resource
|
PHP has a standard way of storing persistent resources (i.e., resources that are kept in between hits). The first module to use this feature was the MySQL module, and mSQL followed it, so one can get the general impression of how a persistent resource should be used by reading mysql.c. The functions you should look at are:
php3_mysql_do_connect |
php3_mysql_connect() |
php3_mysql_pconnect() |
The general idea of persistence modules is this:
Code all of your module to work with the regular resource list mentioned in section (9).
Code extra connect functions that check if the resource already exists in the persistent resource list. If it does, register it as in the regular resource list as a pointer to the persistent resource list (because of 1., the rest of the code should work immediately). If it doesn't, then create it, add it to the persistent resource list AND add a pointer to it from the regular resource list, so all of the code would work since it's in the regular resource list, but on the next connect, the resource would be found in the persistent resource list and be used without having to recreate it. You should register these resources with a different type (e.g. LE_MYSQL_LINK for non-persistent link and LE_MYSQL_PLINK for a persistent link).
If you read mysql.c, you'll notice that except for the more complex connect function, nothing in the rest of the module has to be changed.
The very same interface exists for the regular resource list and the persistent resource list, only 'list' is replaced with 'plist':
php3_plist_insert(ptr, type) - returns the 'id' of the newly inserted resource
php3_plist_delete(id) - delete the resource with the specified id
php3_plist_find(id,*type) - returns the pointer of the resource with the specified id, updates 'type' to the resource's type
However, it's more than likely that these functions would prove to be useless for you when trying to implement a persistent module. Typically, one would want to use the fact that the persistent resource list is really a hash table. For instance, in the MySQL/mSQL modules, when there's a pconnect() call (persistent connect), the function builds a string out of the host/user/passwd that were passed to the function, and hashes the SQL link with this string as a key. The next time someone calls a pconnect() with the same host/user/passwd, the same key would be generated, and the function would find the SQL link in the persistent list.
Until further documented, you should look at mysql.c or msql.c to see how one should use the plist's hash table abilities.
One important thing to note: resources going into the persistent resource list must *NOT* be allocated with PHP's memory manager, i.e., they should NOT be created with emalloc(), estrdup(), etc. Rather, one should use the regular malloc(), strdup(), etc. The reason for this is simple - at the end of the request (end of the hit), every memory chunk that was allocated using PHP's memory manager is deleted. Since the persistent list isn't supposed to be erased at the end of a request, one mustn't use PHP's memory manager for allocating resources that go to it.
When you register a resource that's going to be in the persistent list, you should add destructors to it both in the non-persistent list and in the persistent list. The destructor in the non-persistent list destructor shouldn't do anything. The one in the persistent list destructor should properly free any resources obtained by that type (e.g. memory, SQL links, etc). Just like with the non-persistent resources, you *MUST* add destructors for every resource, even it requires no destruction and the destructor would be empty. Remember, since emalloc() and friends aren't to be used in conjunction with the persistent list, you mustn't use efree() here either.
Many of the features of PHP can be configured at runtime. These configuration directives can appear in either the designated php3.ini file, or in the case of the Apache module version in the Apache .conf files. The advantage of having them in the Apache .conf files is that they can be configured on a per-directory basis. This means that one directory may have a certain safemodeexecdir for example, while another directory may have another. This configuration granularity is especially handy when a server supports multiple virtual hosts.
The steps required to add a new directive:
Add directive to php3_ini_structure struct in mod_php3.h.
In main.c, edit the php3_module_startup function and add the appropriate cfg_get_string() or cfg_get_long() call.
Add the directive, restrictions and a comment to the php3_commands structure in mod_php3.c. Note the restrictions part. RSRC_CONF are directives that can only be present in the actual Apache .conf files. Any OR_OPTIONS directives can be present anywhere, include normal .htaccess files.
In either php3take1handler() or php3flaghandler() add the appropriate entry for your directive.
In the configuration section of the _php3_info() function in functions/info.c you need to add your new directive.
And last, you of course have to use your new directive somewhere. It will be addressable as php3_ini.directive.
To call user functions from an internal function, you should use the call_user_function() function.
call_user_function() returns SUCCESS on success, and FAILURE in case the function cannot be found. You should check that return value! If it returns SUCCESS, you are responsible for destroying the retval pval yourself (or return it as the return value of your function). If it returns FAILURE, the value of retval is undefined, and you mustn't touch it.
All internal functions that call user functions must be reentrant. Among other things, this means they must not use globals or static variables.
call_user_function() takes six arguments:
This is a pointer to an object on which the function is invoked. This should be NULL if a global function is called. If it's not NULL (i.e. it points to an object), the function_table argument is ignored, and instead taken from the object's hash. The object *may* be modified by the function that is invoked on it (that function will have access to it via $this). If for some reason you don't want that to happen, send a copy of the object instead.
The name of the function to call. Must be a pval of type IS_STRING with function_name.str.val and function_name.str.len set to the appropriate values. The function_name is modified by call_user_function() - it's converted to lowercase. If you need to preserve the case, send a copy of the function name instead.
A pointer to a pval structure, into which the return value of the invoked function is saved. The structure must be previously allocated - call_user_function() does NOT allocate it by itself.
An array of pointers to values that will be passed as arguments to the function, the first argument being in offset 0, the second in offset 1, etc. The array is an array of pointers to pval's; The pointers are sent as-is to the function, which means if the function modifies its arguments, the original values are changed (passing by reference). If you don't want that behavior, pass a copy instead.
To report errors from an internal function, you should call the php3_error() function. This takes at least two parameters -- the first is the level of the error, the second is the format string for the error message (as in a standard printf() call), and any following arguments are the parameters for the format string. The error levels are:
Notices are not printed by default, and indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. For example, trying to access the value of a variable which has not been set, or calling stat() on a file that doesn't exist.
Warnings are printed by default, but do not interrupt script execution. These indicate a problem that should have been trapped by the script before the call was made. For example, calling ereg() with an invalid regular expression.
Errors are also printed by default, and execution of the script is halted after the function returns. These indicate errors that can not be recovered from, such as a memory allocation problem.
Parse errors should only be generated by the parser. The code is listed here only for the sake of completeness.
This is like an E_ERROR, except it is generated by the core of PHP. Functions should not generate this type of error.
This is like an E_WARNING, except it is generated by the core of PHP. Functions should not generate this type of error.
This is like an E_ERROR, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error.
This is like an E_WARNING, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error.
This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). Functions should not generate this type of error.
This is like an E_WARNING, except it is generated by using the PHP function trigger_error(). Functions should not generate this type of error.
This is like an E_NOTICE, except it is generated by using the PHP function trigger_error(). Functions should not generate this type of error.
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.
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.
Compile with debugging symbols.
Sets how installed files will be laid out. Type is one of PHP (default) or GNU.
Install PEAR in DIR (default PREFIX/lib/php).
Do not install PEAR.
Enable PHP's own SIGCHLD handler.
Disable passing additional runtime library search paths.
Enable explicitly linking against libgcc.
Include experimental PHP streams. Do not use unless you are testing the code!
Define the location of zlib install directory.
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.
Use POSIX threads (default).
Build shared libraries [default=yes].
Build static libraries [default=yes].
Optimize for fast installation [default=yes].
Assume the C compiler uses GNU ld [default=no].
Avoid locking (might break parallel builds).
Try to use only PIC/non-PIC objects [default=use both].
Compile with memory limit support.
Disable the URL-aware fopen wrapper that allows accessing files via HTTP or FTP.
Export only required symbols. See INSTALL for more information.
Include IMSp support (DIR is IMSP's include dir and libimsp.a dir). PHP 3 only!
Include Cybercash MCK support. DIR is the cybercash mck build directory, defaults to /usr/src/mck-3.2.0.3-linux for help look in extra/cyberlib. PHP 3 only!
Include DAV support through Apache's mod_dav, DIR is mod_dav's installation directory (Apache module version only!) PHP 3 only!
Compile with remote debugging functions. PHP 3 only!
Take advantage of versioning and scoping provided by Solaris 2.x and Linux. PHP 3 only!
Enable make rules and dependencies not useful (and sometimes confusing) to the casual installer.
Sets the path in which to look for php.ini, defaults to PREFIX/lib.
Enable safe mode by default.
Only allow executables in DIR when in safe mode defaults to /usr/local/php/bin.
Enable magic quotes by default.
Disable the short-form <? start tag by default.
The following list contains the available SAPI&s (Server Application Programming Interface) for PHP.
Specify path to the installed AOLserver.
Build shared Apache module. FILE is the optional pathname to the Apache apxs tool; defaults to apxs. Make sure you specify the version of apxs that is actually installed on your system and NOT the one that is in the apache source tarball.
Build a static Apache module. DIR is the top-level Apache build directory, defaults to /usr/local/apache.
Enable transfer tables for mod_charset (Russian Apache).
Build shared Apache 2.0 module. FILE is the optional pathname to the Apache apxs tool; defaults to apxs.
Build PHP as a Pike module for use with Caudium. DIR is the Caudium server dir, with the default value /usr/local/caudium/server.
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 building of the embedded SAPI library. TYPE is either shared or static, which defaults to shared. Available with PHP 4.3.0.
Build fhttpd module. DIR is the fhttpd sources directory, defaults to /usr/local/src/fhttpd. No longer available as of PHP 4.3.0.
Build PHP as an ISAPI module for use with Zeus.
Specify path to the installed Netscape/iPlanet/SunONE Webserver.
No information yet.
Build PHP as a module for use with Pi3Web.
Build PHP as a Pike module. DIR is the base Roxen directory, normally /usr/local/roxen/server.
Build the Roxen module using Zend Thread Safety.
Include servlet support. DIR is the base install directory for the JSDK. This SAPI requires the java extension must be built as a shared dl.
Build PHP as thttpd module.
Build PHP as a TUX module (Linux only).
Build PHP as a WebJames module (RISC OS only)
Disable building CGI version of PHP. Available with PHP 4.3.0.
Enable the security check for internal server redirects. You should use this if you are running the CGI version with Apache.
If this is enabled, the PHP CGI binary can safely be placed outside of the web tree and people will not be able to circumvent .htaccess security.
Build PHP as FastCGI application. No longer available as of PHP 4.3.0, instead you should use --enable-fastcgi.
If this is enabled, the CGI module will be built with support for FastCGI also. Available since PHP 4.3.0
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.
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.
Tabella H-2. Language and Misc Configuration Options
Name | Default | Changeable |
---|---|---|
short_open_tag | On | PHP_INI_SYSTEM|PHP_INI_PERDIR |
asp_tags | Off | PHP_INI_SYSTEM|PHP_INI_PERDIR |
precision | "14" | PHP_INI_ALL |
y2k_compliance | Off | PHP_INI_ALL |
allow_call_time_pass_reference | On | PHP_INI_SYSTEM|PHP_INI_PERDIR |
expose_php | On | PHP_INI_SYSTEM |
Breve descrizione dei parametri di configurazione.
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.
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.
The number of significant digits displayed in floating point numbers.
Enforce year 2000 compliance (will cause problems with non-compliant browsers)
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.
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.
Breve descrizione dei parametri di configurazione.
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.
Tabella H-4. Data Handling Configuration Options
Name | Default | Changeable |
---|---|---|
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.
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.
The separator used in PHP generated URLs to separate arguments.
List of separator(s) used by PHP to parse input URLs into variables.
Nota: Every character in this directive is considered as separator!
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.
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.
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.
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.
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.
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.
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.
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.
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 the $HTTP_RAW_POST_DATA variable.
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.
Tabella H-5. Paths and Directories Configuration Options
Name | Default | Changeable |
---|---|---|
include_path | PHP_INCLUDE_PATH | PHP_INI_ALL |
doc_root | PHP_INCLUDE_PATH | PHP_INI_SYSTEM |
user_dir | NULL | PHP_INI_SYSTEM |
extension_dir | PHP_EXTENSION_DIR | PHP_INI_SYSTEM |
cgi.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.
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.
Using a . in the include path allows for relative includes as it means the current directory.
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.
The base name of the directory used on a user's home directory for PHP files, for example public_html .
In what directory PHP should look for dynamically loadable extensions. See also: enable_dl, and dl().
Which dynamically loadable extensions to load when PHP starts up.
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 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.
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 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.
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.
Tabella H-6. File Uploads Configuration Options
Name | Default | Changeable |
---|---|---|
file_uploads | "1" | PHP_INI_SYSTEM |
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
upload_max_filesize | "2M" | PHP_INI_SYSTEM|PHP_INI_PERDIR |
Breve descrizione dei parametri di configurazione.
Whether or not to allow HTTP file uploads. See also the upload_max_filesize, upload_tmp_dir, and post_max_size directives.
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.
The maximum size of an uploaded file.
Attenzione |
Only PHP 3 implements a default debugger, for more information see Appendice E. |
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 Master | Estensione utilizzata |
---|---|---|
add | swfmovie_add() | Ming (flash) |
add | swfsprite_add() | Ming (flash) |
add_root | domxml_add_root() | DOM XML |
addaction | swfbutton_addAction() | Ming (flash) |
addcolor | swfdisplayitem_addColor() | Ming (flash) |
addentry | swfgradient_addEntry() | Ming (flash) |
addfill | swfshape_addfill() | Ming (flash) |
addshape | swfbutton_addShape() | Ming (flash) |
addstring | swftext_addString() | Ming (flash) |
addstring | swftextfield_addString() | Ming (flash) |
align | swftextfield_align() | Ming (flash) |
attributes | domxml_attributes() | DOM XML |
children | domxml_children() | DOM XML |
chop | rtrim() | Base syntax |
close | closedir() | Base syntax |
com_get | com_propget() | COM |
com_propset | com_propput() | COM |
com_set | com_propput() | COM |
cv_add | ccvs_add() | CCVS |
cv_auth | ccvs_auth() | CCVS |
cv_command | ccvs_command() | CCVS |
cv_count | ccvs_count() | CCVS |
cv_delete | ccvs_delete() | CCVS |
cv_done | ccvs_done() | CCVS |
cv_init | ccvs_init() | CCVS |
cv_lookup | ccvs_lookup() | CCVS |
cv_new | ccvs_new() | CCVS |
cv_report | ccvs_report() | CCVS |
cv_return | ccvs_return() | CCVS |
cv_reverse | ccvs_reverse() | CCVS |
cv_sale | ccvs_sale() | CCVS |
cv_status | ccvs_status() | CCVS |
cv_textvalue | ccvs_textvalue() | CCVS |
cv_void | ccvs_void() | CCVS |
die | exit() | Miscellaneous functions |
dir | getdir() | Base syntax |
diskfreespace | disk_free_space() | Filesystem |
domxml_getattr | domxml_get_attribute() | DOM XML |
domxml_setattr | domxml_set_attribute() | DOM XML |
doubleval | floatval() | Base syntax |
drawarc | swfshape_drawarc() | Ming (flash) |
drawcircle | swfshape_drawcircle() | Ming (flash) |
drawcubic | swfshape_drawcubic() | Ming (flash) |
drawcubicto | swfshape_drawcubicto() | Ming (flash) |
drawcurve | swfshape_drawcurve() | Ming (flash) |
drawcurveto | swfshape_drawcurveto() | Ming (flash) |
drawglyph | swfshape_drawglyph() | Ming (flash) |
drawline | swfshape_drawline() | Ming (flash) |
drawlineto | swfshape_drawlineto() | Ming (flash) |
dtd | domxml_intdtd() | DOM XML |
dumpmem | domxml_dumpmem() | DOM XML |
fbsql | fbsql_db_query() | FrontBase |
fputs | fwrite() | Base syntax |
get_attribute | domxml_get_attribute() | DOM XML |
getascent | swffont_getAscent() | Ming (flash) |
getascent | swftext_getAscent() | Ming (flash) |
getattr | domxml_get_attribute() | DOM XML |
getdescent | swffont_getDescent() | Ming (flash) |
getdescent | swftext_getDescent() | Ming (flash) |
getheight | swfbitmap_getHeight() | Ming (flash) |
getleading | swffont_getLeading() | Ming (flash) |
getleading | swftext_getLeading() | Ming (flash) |
getshape1 | swfmorph_getShape1() | Ming (flash) |
getshape2 | swfmorph_getShape2() | Ming (flash) |
getwidth | swfbitmap_getWidth() | Ming (flash) |
getwidth | swffont_getWidth() | Ming (flash) |
getwidth | swftext_getWidth() | Ming (flash) |
gzputs | gzwrite() | Zlib |
i18n_convert | mb_convert_encoding() | Multi-bytes Strings |
i18n_discover_encoding | mb_detect_encoding() | Multi-bytes Strings |
i18n_http_input | mb_http_input() | Multi-bytes Strings |
i18n_http_output | mb_http_output() | Multi-bytes Strings |
i18n_internal_encoding | mb_internal_encoding() | Multi-bytes Strings |
i18n_ja_jp_hantozen | mb_convert_kana() | Multi-bytes Strings |
i18n_mime_header_decode | mb_decode_mimeheader() | Multi-bytes Strings |
i18n_mime_header_encode | mb_encode_mimeheader() | Multi-bytes Strings |
imap_create | imap_createmailbox() | IMAP |
imap_fetchtext | imap_body() | IMAP |
imap_getmailboxes | imap_list_full() | IMAP |
imap_getsubscribed | imap_lsub_full() | IMAP |
imap_header | imap_headerinfo() | IMAP |
imap_listmailbox | imap_list() | IMAP |
imap_listsubscribed | imap_lsub() | IMAP |
imap_rename | imap_renamemailbox() | IMAP |
imap_scan | imap_listscan() | IMAP |
imap_scanmailbox | imap_listscan() | IMAP |
ini_alter | ini_set() | Base syntax |
is_double | is_float() | Base syntax |
is_integer | is_int() | Base syntax |
is_long | is_int() | Base syntax |
is_real | is_float() | Base syntax |
is_writeable | is_writable() | Base syntax |
join | implode() | Base syntax |
labelframe | swfmovie_labelFrame() | Ming (flash) |
labelframe | swfsprite_labelFrame() | Ming (flash) |
last_child | domxml_last_child() | DOM XML |
lastchild | domxml_last_child() | DOM XML |
ldap_close | ldap_unbind() | LDAP |
magic_quotes_runtime | set_magic_quotes_runtime() | Base syntax |
mbstrcut | mb_strcut() | Multi-bytes Strings |
mbstrlen | mb_strlen() | Multi-bytes Strings |
mbstrpos | mb_strpos() | Multi-bytes Strings |
mbstrrpos | mb_strrpos() | Multi-bytes Strings |
mbsubstr | mb_substr() | Multi-bytes Strings |
ming_setcubicthreshold | ming_setCubicThreshold() | Ming (flash) |
ming_setscale | ming_setScale() | Ming (flash) |
move | swfdisplayitem_move() | Ming (flash) |
movepen | swfshape_movepen() | Ming (flash) |
movepento | swfshape_movepento() | Ming (flash) |
moveto | swfdisplayitem_moveTo() | Ming (flash) |
moveto | swffill_moveTo() | Ming (flash) |
moveto | swftext_moveTo() | Ming (flash) |
msql | msql_db_query() | mSQL |
msql_affected_rows | msql_affected_rows() | mSQL |
msql_createdb | msql_create_db() | mSQL |
msql_dbname | msql_result() | mSQL |
msql_dropdb | msql_drop_db() | mSQL |
msql_fieldflags | msql_field_flags() | mSQL |
msql_fieldlen | msql_field_len() | mSQL |
msql_fieldname | msql_field_name() | mSQL |
msql_fieldtable | msql_field_table() | mSQL |
msql_fieldtype | msql_field_type() | mSQL |
msql_freeresult | msql_free_result() | mSQL |
msql_listdbs | msql_list_dbs() | mSQL |
msql_listfields | msql_list_fields() | mSQL |
msql_listtables | msql_list_tables() | mSQL |
msql_numfields | msql_num_fields() | mSQL |
msql_numrows | msql_num_rows() | mSQL |
msql_regcase | sql_regcase() | mSQL |
msql_selectdb | msql_select_db() | mSQL |
msql_tablename | msql_result() | mSQL |
mssql_affected_rows | sybase_affected_rows() | Sybase |
mssql_affected_rows | sybase_affected_rows() | Sybase |
mssql_close | sybase_close() | Sybase |
mssql_close | sybase_close() | Sybase |
mssql_connect | sybase_connect() | Sybase |
mssql_connect | sybase_connect() | Sybase |
mssql_data_seek | sybase_data_seek() | Sybase |
mssql_data_seek | sybase_data_seek() | Sybase |
mssql_fetch_array | sybase_fetch_array() | Sybase |
mssql_fetch_array | sybase_fetch_array() | Sybase |
mssql_fetch_field | sybase_fetch_field() | Sybase |
mssql_fetch_field | sybase_fetch_field() | Sybase |
mssql_fetch_object | sybase_fetch_object() | Sybase |
mssql_fetch_object | sybase_fetch_object() | Sybase |
mssql_fetch_row | sybase_fetch_row() | Sybase |
mssql_fetch_row | sybase_fetch_row() | Sybase |
mssql_field_seek | sybase_field_seek() | Sybase |
mssql_field_seek | sybase_field_seek() | Sybase |
mssql_free_result | sybase_free_result() | Sybase |
mssql_free_result | sybase_free_result() | Sybase |
mssql_get_last_message | sybase_get_last_message() | Sybase |
mssql_get_last_message | sybase_get_last_message() | Sybase |
mssql_min_client_severity | sybase_min_client_severity() | Sybase |
mssql_min_error_severity | sybase_min_error_severity() | Sybase |
mssql_min_message_severity | sybase_min_message_severity() | Sybase |
mssql_min_server_severity | sybase_min_server_severity() | Sybase |
mssql_num_fields | sybase_num_fields() | Sybase |
mssql_num_fields | sybase_num_fields() | Sybase |
mssql_num_rows | sybase_num_rows() | Sybase |
mssql_num_rows | sybase_num_rows() | Sybase |
mssql_pconnect | sybase_pconnect() | Sybase |
mssql_pconnect | sybase_pconnect() | Sybase |
mssql_query | sybase_query() | Sybase |
mssql_query | sybase_query() | Sybase |
mssql_result | sybase_result() | Sybase |
mssql_result | sybase_result() | Sybase |
mssql_select_db | sybase_select_db() | Sybase |
mssql_select_db | sybase_select_db() | Sybase |
multcolor | swfdisplayitem_multColor() | Ming (flash) |
mysql | mysql_db_query() | MySQL |
mysql_createdb | mysql_create_db() | MySQL |
mysql_db_name | mysql_result() | MySQL |
mysql_dbname | mysql_result() | MySQL |
mysql_dropdb | mysql_drop_db() | MySQL |
mysql_fieldflags | mysql_field_flags() | MySQL |
mysql_fieldlen | mysql_field_len() | MySQL |
mysql_fieldname | mysql_field_name() | MySQL |
mysql_fieldtable | mysql_field_table() | MySQL |
mysql_fieldtype | mysql_field_type() | MySQL |
mysql_freeresult | mysql_free_result() | MySQL |
mysql_listdbs | mysql_list_dbs() | MySQL |
mysql_listfields | mysql_list_fields() | MySQL |
mysql_listtables | mysql_list_tables() | MySQL |
mysql_numfields | mysql_num_fields() | MySQL |
mysql_numrows | mysql_num_rows() | MySQL |
mysql_selectdb | mysql_select_db() | MySQL |
mysql_tablename | mysql_result() | MySQL |
name | domxml_attrname() | DOM XML |
new_child | domxml_new_child() | DOM XML |
new_xmldoc | domxml_new_xmldoc() | DOM XML |
nextframe | swfmovie_nextFrame() | Ming (flash) |
nextframe | swfsprite_nextFrame() | Ming (flash) |
node | domxml_node() | DOM XML |
oci8append | ocicollappend() | OCI8 |
oci8assign | ocicollassign() | OCI8 |
oci8assignelem | ocicollassignelem() | OCI8 |
oci8close | ocicloselob() | OCI8 |
oci8free | ocifreecoll() | OCI8 |
oci8free | ocifreedesc() | OCI8 |
oci8getelem | ocicollgetelem() | OCI8 |
oci8load | ociloadlob() | OCI8 |
oci8max | ocicollmax() | OCI8 |
oci8ocifreecursor | ocifreestatement() | OCI8 |
oci8save | ocisavelob() | OCI8 |
oci8savefile | ocisavelobfile() | OCI8 |
oci8size | ocicollsize() | OCI8 |
oci8trim | ocicolltrim() | OCI8 |
oci8writetemporary | ociwritetemporarylob() | OCI8 |
oci8writetofile | ociwritelobtofile() | OCI8 |
odbc_do | odbc_exec() | OCI8 |
odbc_field_precision | odbc_field_len() | OCI8 |
orbit_caught_exception | satellite_caught_exception() | Satellite |
orbit_exception_id | satellite_exception_id() | Satellite |
orbit_exception_value | satellite_exception_value() | Satellite |
orbit_get_repository_id | satellite_get_repository_id() | Satellite |
orbit_load_idl | satellite_load_idl() | Satellite |
output | swfmovie_output() | Ming (flash) |
parent | domxml_parent() | DOM XML |
pdf_add_outline | pdf_add_bookmark() | |
pg_clientencoding | pg_client_encoding() | PostgreSQL |
pg_setclientencoding | pg_set_client_encoding() | PostgreSQL |
pos | current() | Base syntax |
recode | recode_string() | Recode |
remove | swfmovie_remove() | Ming (flash) |
remove | swfsprite_remove() | Ming (flash) |
rewind | rewinddir() | Base syntax |
root | domxml_root() | DOM XML |
rotate | swfdisplayitem_rotate() | Ming (flash) |
rotateto | swfdisplayitem_rotateTo() | Ming (flash) |
rotateto | swffill_rotateTo() | Ming (flash) |
save | swfmovie_save() | Ming (flash) |
savetofile | swfmovie_saveToFile() | Ming (flash) |
scale | swfdisplayitem_scale() | Ming (flash) |
scaleto | swfdisplayitem_scaleTo() | Ming (flash) |
scaleto | swffill_scaleTo() | Ming (flash) |
set_attribute | domxml_set_attribute() | DOM XML |
set_content | domxml_set_content() | DOM XML |
setaction | swfbutton_setAction() | Ming (flash) |
setattr | domxml_set_attribute() | DOM XML |
setbackground | swfmovie_setBackground() | Ming (flash) |
setbounds | swftextfield_setBounds() | Ming (flash) |
setcolor | swftext_setColor() | Ming (flash) |
setcolor | swftextfield_setColor() | Ming (flash) |
setdepth | swfdisplayitem_setDepth() | Ming (flash) |
setdimension | swfmovie_setDimension() | Ming (flash) |
setdown | swfbutton_setDown() | Ming (flash) |
setfont | swftext_setFont() | Ming (flash) |
setfont | swftextfield_setFont() | Ming (flash) |
setframes | swfmovie_setFrames() | Ming (flash) |
setframes | swfsprite_setFrames() | Ming (flash) |
setheight | swftext_setHeight() | Ming (flash) |
setheight | swftextfield_setHeight() | Ming (flash) |
sethit | swfbutton_setHit() | Ming (flash) |
setindentation | swftextfield_setIndentation() | Ming (flash) |
setleftfill | swfshape_setleftfill() | Ming (flash) |
setleftmargin | swftextfield_setLeftMargin() | Ming (flash) |
setline | swfshape_setline() | Ming (flash) |
setlinespacing | swftextfield_setLineSpacing() | Ming (flash) |
setmargins | swftextfield_setMargins() | Ming (flash) |
setmatrix | swfdisplayitem_setMatrix() | Ming (flash) |
setname | swfdisplayitem_setName() | Ming (flash) |
setname | swftextfield_setName() | Ming (flash) |
setover | swfbutton_setOver() | Ming (flash) |
setrate | swfmovie_setRate() | Ming (flash) |
setratio | swfdisplayitem_setRatio() | Ming (flash) |
setrightfill | swfshape_setrightfill() | Ming (flash) |
setrightmargin | swftextfield_setRightMargin() | Ming (flash) |
setspacing | swftext_setSpacing() | Ming (flash) |
setup | swfbutton_setUp() | Ming (flash) |
show_source | highlight_file () | Base syntax |
sizeof | count() | Base syntax |
skewx | swfdisplayitem_skewX() | Ming (flash) |
skewxto | swfdisplayitem_skewXTo() | Ming (flash) |
skewxto | swffill_skewXTo() | Ming (flash) |
skewy | swfdisplayitem_skewY() | Ming (flash) |
skewyto | swfdisplayitem_skewYTo() | Ming (flash) |
skewyto | swffill_skewYTo() | Ming (flash) |
snmpwalkoid | snmprealwalk() | SNMP |
strchr | strstr() | Base syntax |
streammp3 | swfmovie_streamMp3() | Ming (flash) |
swfaction | swfaction_init() | Ming (flash) |
swfbitmap | swfbitmap_init() | Ming (flash) |
swfbutton | swfbutton_init() | Ming (flash) |
swfbutton_keypress | swfbutton_keypress() | Ming (flash) |
swffill | swffill_init() | Ming (flash) |
swffont | swffont_init() | Ming (flash) |
swfgradient | swfgradient_init() | Ming (flash) |
swfmorph | swfmorph_init() | Ming (flash) |
swfmovie | swfmovie_init() | Ming (flash) |
swfshape | swfshape_init() | Ming (flash) |
swfsprite | swfsprite_init() | Ming (flash) |
swftext | swftext_init() | Ming (flash) |
swftextfield | swftextfield_init() | Ming (flash) |
unlink | domxml_unlink_node() | DOM XML |
xpath_eval | xpath_eval() | DOM XML |
xpath_eval_expression | xpath_eval_expression() | DOM XML |
xpath_init | xpath_init() | DOM XML |
xpath_new_context | xpath_new_context() | DOM XML |
xptr_new_context | xpath_new_context() | DOM XML |
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 |
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 Name | Created By | Used By | Destroyed By | Definition |
---|---|---|---|---|
aspell | aspell_new() | aspell_check(), aspell_check_raw(), aspell_suggest() | None | Aspell dictionary |
bzip2 | bzopen() | bzerrno(), bzerror(), bzerrstr(), bzflush(), bzread(), bzwrite() | bzclose() | Bzip2 file |
COM | com_load() | com_invoke(), com_propget(), com_get(), com_propput(), com_set(), com_propput() | None | COM object reference |
VARIANT | ||||
cpdf | cpdf_open() | cpdf_page_init(), cpdf_finalize_page(), cpdf_finalize(), cpdf_output_buffer(), cpdf_save_to_file(), cpdf_set_current_page(), cpdf_begin_text(), cpdf_end_text(), cpdf_show(), cpdf_show_xy(), cpdf_text(), cpdf_set_font(), cpdf_set_leading(), cpdf_set_text_rendering(), cpdf_set_horiz_scaling(), cpdf_set_text_rise(), cpdf_set_text_matrix(), cpdf_set_text_pos(), cpdf_set_text_pos(), cpdf_set_word_spacing(), cpdf_continue_text(), cpdf_stringwidth(), cpdf_save(), cpdf_translate(), cpdf_restore(), cpdf_scale(), cpdf_rotate(), cpdf_setflat(), cpdf_setlinejoin(), cpdf_setlinecap(), cpdf_setmiterlimit(), cpdf_setlinewidth(), cpdf_setdash(), cpdf_moveto(), cpdf_rmoveto(), cpdf_curveto(), cpdf_lineto(), cpdf_rlineto(), cpdf_circle(), cpdf_arc(), cpdf_rect(), cpdf_closepath(), cpdf_stroke(), cpdf_closepath_fill_stroke(), cpdf_fill_stroke(), cpdf_clip(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray_stroke(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor(), cpdf_add_outline(), cpdf_set_page_animation(), cpdf_import_jpeg(), cpdf_place_inline_image(), cpdf_add_annotation() | cpdf_close() | PDF document with CPDF lib |
cpdf outline | ||||
curl | curl_init() | curl_init(), curl_exec() | curl_close() | Curl session |
dbm | dbmopen() | dbmexists(), dbmfetch(), dbminsert(), dbmreplace(), dbmdelete(), dbmfirstkey(), dbmnextkey() | dbmclose() | Link to DBM database |
dba | dba_open() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | dba_close() | Link to DBA database |
dba persistent | dba_popen() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | None | Persistent link to DBA database |
dbase | dbase_open() | dbase_pack(), dbase_add_record(), dbase_replace_record(), dbase_delete_record(), dbase_get_record(), dbase_get_record_with_names(), dbase_numfields(), dbase_numrecords() | dbase_close() | Link to Dbase database |
dbx_link_object | dbx_connect() | dbx_query() | dbx_close() | dbx connection |
dbx_result_object | dbx_query() | None | dbx result | |
domxml attribute | ||||
domxml document | ||||
domxml node | ||||
xpath context | ||||
xpath object | ||||
fbsql database | fbsql_select_db() | None | fbsql database | |
fbsql link | fbsql_change_user(), fbsql_connect() | fbsql_autocommit(), fbsql_change_user(), fbsql_create_db(), fbsql_data_seek(), fbsql_db_query(), fbsql_drop_db(), (), fbsql_select_db(), fbsql_errno(), fbsql_error(), fbsql_insert_id(), fbsql_list_dbs() | fbsql_close() | Link to fbsql database |
fbsql plink | fbsql_change_user(), fbsql_pconnect() | fbsql_autocommit(), fbsql_change_user(), fbsql_create_db(), fbsql_data_seek(), fbsql_db_query(), fbsql_drop_db(), (), fbsql_select_db(), fbsql_errno(), fbsql_error(), fbsql_insert_id(), fbsql_list_dbs() | None | Persistent link to fbsql database |
fbsql result | fbsql_db_query(), fbsql_list_dbs(), fbsql_query(), fbsql_list_fields(), fbsql_list_tables(), fbsql_tablename() | fbsql_affected_rows(), fbsql_fetch_array(), fbsql_fetch_assoc(), fbsql_fetch_field(), fbsql_fetch_lengths(), fbsql_fetch_object(), fbsql_fetch_row(), fbsql_field_flags(), fbsql_field_name(), fbsql_field_len(), fbsql_field_seek(), fbsql_field_table(), fbsql_field_type(), fbsql_next_result(), fbsql_num_fields(), fbsql_num_rows(), fbsql_result(), fbsql_num_rows() | fbsql_free_result() | fbsql result |
fdf | fdf_open() | fdf_create(), fdf_save(), fdf_get_value(), fdf_set_value(), fdf_next_field_name(), fdf_set_ap(), fdf_set_status(), fdf_get_status(), fdf_set_file(), fdf_get_file(), fdf_set_flags(), fdf_set_opt(), fdf_set_submit_form_action(), fdf_set_javascript_action() | fdf_close() | FDF File |
ftp | ftp_connect() | ftp_login(), ftp_pwd(), ftp_cdup(), ftp_chdir(), ftp_mkdir(), ftp_rmdir(), ftp_nlist(), ftp_rawlist(), ftp_systype(), ftp_pasv(), ftp_get(), ftp_fget(), ftp_put(), ftp_fput(), ftp_size(), ftp_mdtm(), ftp_rename(), ftp_delete(), ftp_site() | ftp_quit() | FTP stream |
gd | imagecreate(), imagecreatefromgif(), imagecreatefromjpeg(), imagecreatefrompng(), imagecreatefromwbmp(), imagecreatefromstring(), imagecreatetruecolor() | imagearc(), imagechar(), imagecharup(), imagecolorallocate(), imagecolorat(), imagecolorclosest(), imagecolorexact(), imagecolorresolve(), imagegammacorrect(), imagegammacorrect(), imagecolorset(), imagecolorsforindex(), imagecolorstotal(), imagecolortransparent(), imagecopy(), imagecopyresized(), imagedashedline(), imagefill(), imagefilledpolygon(), imagefilledrectangle(), imagefilltoborder(), imagegif(), imagepng(), imagejpeg(), imagewbmp(), imageinterlace(), imageline(), imagepolygon(), imagepstext(), imagerectangle(), imagesetpixel(), imagestring(), imagestringup(), imagesx(), imagesy(), imagettftext(), imagefilledarc(), imageellipse(), imagefilledellipse(), imagecolorclosestalpha(), imagecolorexactalpha(), imagecolorresolvealpha(), imagecopymerge(), imagecopymergegray(), imagecopyresampled(), imagetruecolortopalette(), imagesetbrush(), imagesettile(), imagesetthickness() | imagedestroy() | GD Image |
gd font | imageloadfont() | imagechar(), imagecharup(), imagefontheight() | None | Font for GD |
gd PS encoding | ||||
gd PS font | imagepsloadfont() | imagepstext(), imagepsslantfont(), imagepsextendfont(), imagepsencodefont(), imagepsbbox() | imagepsfreefont() | PS font for GD |
GMP integer | gmp_init() | gmp_intval(), gmp_strval(), gmp_add(), gmp_sub(), gmp_mul(), gmp_div_q(), gmp_div_r(), gmp_div_qr(), gmp_div(), gmp_mod(), gmp_divexact(), gmp_cmp(), gmp_neg(), gmp_abs(), gmp_sign(), gmp_fact(), gmp_sqrt(), gmp_sqrtrm(), gmp_perfect_square(), gmp_pow(), gmp_powm(), gmp_prob_prime(), gmp_gcd(), gmp_gcdext(), gmp_invert(), gmp_legendre(), gmp_jacobi(), gmp_random(), gmp_and(), gmp_or(), gmp_xor(), gmp_setbit(), gmp_clrbit(), gmp_scan0(), gmp_scan1(), gmp_popcount(), gmp_hamdist() | None | GMP Number |
hyperwave document | hw_cp(), hw_docbyanchor(), hw_getremote(), hw_getremotechildren() | hw_children(), hw_childrenobj(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getsrcbydestobj(), hw_getandlock(), hw_gettext(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_inscoll(), hw_pipedocument(), hw_unlock() | hw_deleteobject() | Hyperwave object |
hyperwave link | hw_connect() | hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() | hw_close(), hw_free_document() | Link to Hyperwave server |
hyperwave link persistent | hw_pconnect() | hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() | None | Persistent link to Hyperwave server |
icap | icap_open() | icap_fetch_event(), icap_list_events(), icap_store_event(), icap_snooze(), icap_list_alarms(), icap_delete_event() | icap_close() | Link to icap server |
imap | imap_open() | imap_append(), imap_body(), imap_check(), imap_createmailbox(), imap_delete(), imap_deletemailbox(), imap_expunge(), imap_fetchbody(), imap_fetchstructure(), imap_headerinfo(), imap_header(), imap_headers(), imap_listmailbox(), imap_getmailboxes(), imap_get_quota(), imap_status(), imap_listsubscribed(), imap_set_quota(), imap_set_quota(), imap_getsubscribed(), imap_mail_copy(), imap_mail_move(), imap_num_msg(), imap_num_recent(), imap_ping(), imap_renamemailbox(), imap_reopen(), imap_subscribe(), imap_undelete(), imap_unsubscribe(), imap_scanmailbox(), imap_mailboxmsginfo(), imap_fetchheader(), imap_uid(), imap_msgno(), imap_search(), imap_fetch_overview() | imap_close() | Link to IMAP, POP3 server |
imap chain persistent | ||||
imap persistent | ||||
ingres | ingres_connect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | ingres_close() | Link to ingresII base |
ingres persistent | ingres_pconnect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | None | Persistent link to ingresII base |
interbase blob | ||||
interbase link | ibase_connect() | ibase_query(), ibase_prepare(), ibase_trans() | ibase_close() | Link to Interbase database |
interbase link persistent | ibase_pconnect() | ibase_query(), ibase_prepare(), ibase_trans() | None | Persistent link to Interbase database |
interbase query | ibase_prepare() | ibase_execute() | ibase_free_query() | Interbase query |
interbase result | ibase_query() | ibase_fetch_row(), ibase_fetch_object(), ibase_field_info(), ibase_num_fields() | ibase_free_result() | Interbase Result |
interbase transaction | ibase_trans() | ibase_commit() | ibase_rollback() | Interbase transaction |
java | ||||
ldap link | ldap_connect(), ldap_search() | ldap_count_entries(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_next_attribute(), ldap_next_entry() | ldap_close() | ldap connection |
ldap result | ldap_read() | ldap_add(), ldap_compare(), ldap_bind(), ldap_count_entries(), ldap_delete(), ldap_errno(), ldap_error(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_get_option(), ldap_list(), ldap_modify(), ldap_mod_add(), ldap_mod_replace(), ldap_next_attribute(), ldap_next_entry(), ldap_mod_del(), ldap_set_option(), ldap_unbind() | ldap_free_result() | ldap search result |
ldap result entry | ||||
mcal | mcal_open(), mcal_popen() | mcal_create_calendar(), mcal_rename_calendar(), mcal_rename_calendar(), mcal_delete_calendar(), mcal_fetch_event(), mcal_list_events(), mcal_append_event(), mcal_store_event(), mcal_delete_event(), mcal_list_alarms(), mcal_event_init(), mcal_event_set_category(), mcal_event_set_title(), mcal_event_set_description(), mcal_event_set_start(), mcal_event_set_end(), mcal_event_set_alarm(), mcal_event_set_class(), mcal_next_recurrence(), mcal_event_set_recur_none(), mcal_event_set_recur_daily(), mcal_event_set_recur_weekly(), mcal_event_set_recur_monthly_mday(), mcal_event_set_recur_monthly_wday(), mcal_event_set_recur_yearly(), mcal_fetch_current_stream_event(), mcal_event_add_attribute(), mcal_expunge() | mcal_close() | Link to calendar server |
SWFAction | ||||
SWFBitmap | ||||
SWFButton | ||||
SWFDisplayItem | ||||
SWFFill | ||||
SWFFont | ||||
SWFGradient | ||||
SWFMorph | ||||
SWFMovie | ||||
SWFShape | ||||
SWFSprite | ||||
SWFText | ||||
SWFTextField | ||||
mnogosearch agent | ||||
mnogosearch result | ||||
msql link | msql_connect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | msql_close() | Link to mSQL database |
msql link persistent | msql_pconnect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | None | Persistent link to mSQL |
msql query | msql_query() | msql(), msql_affected_rows(), msql_data_seek(), msql_dbname(), msql_fetch_array(), msql_fetch_field(), msql_fetch_object(), msql_fetch_row(), msql_fieldname(), msql_field_seek(), msql_fieldtable(), msql_fieldtype(), msql_fieldflags(), msql_fieldlen(), msql_num_fields(), msql_num_rows(), msql_numfields(), msql_numrows(), msql_result() | msql_free_result(), msql_free_result() | mSQL result |
mssql link | mssql_connect() | mssql_query(), mssql_select_db() | mssql_close() | Link to Microsft SQL Server database |
mssql link persistent | mssql_pconnect() | mssql_query(), mssql_select_db() | None | Persistent link to Microsft SQL Server |
mssql result | mssql_query() | mssql_data_seek(), mssql_fetch_array(), mssql_fetch_field(), mssql_fetch_object(), mssql_fetch_row(), mssql_field_length(), mssql_field_name(), mssql_field_seek(), mssql_field_type(), mssql_num_fields(), mssql_num_rows(), mssql_result() | mssql_free_result() | Microsft SQL Server result |
mysql link | mysql_connect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | mysql_close() | Link to MySQL database |
mysql link persistent | mysql_pconnect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | None | Persistent link to MySQL database |
mysql result | mysql_db_query(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query() | mysql_data_seek(), mysql_db_name(), mysql_fetch_array(), mysql_fetch_assoc(), mysql_fetch_field(), mysql_fetch_lengths(), mysql_fetch_object(), mysql_fetch_row(), mysql_fetch_row(), mysql_field_flags(), mysql_field_name(), mysql_field_len(), mysql_field_seek(), mysql_field_table(), mysql_field_type(), mysql_num_fields(), mysql_num_rows(), mysql_result(), mysql_tablename() | mysql_free_result() | MySQL result |
oci8 collection | ||||
oci8 connection | ocilogon(), ociplogon(), ocinlogon() | ocicommit(), ociserverversion(), ocinewcursor(), ociparse(), ocierror() | ocilogoff() | Link to Oracle database |
oci8 descriptor | ||||
oci8 server | ||||
oci8 session | ||||
oci8 statement | ocinewdescriptor() | ocirollback(), ocinewdescriptor(), ocirowcount(), ocidefinebyname(), ocibindbyname(), ociexecute(), ocinumcols(), ociresult(), ocifetch(), ocifetchinto(), ocifetchstatement(), ocicolumnisnull(), ocicolumnname(), ocicolumnsize(), ocicolumntype(), ocistatementtype(), ocierror() | ocifreestatement() | Oracle Cursor |
odbc link | odbc_connect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | odbc_close() | Link to ODBC database |
odbc link persistent | odbc_connect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | None | Persistent link to ODBC database |
odbc result | odbc_prepare() | odbc_binmode(), odbc_cursor(), odbc_execute(), odbc_fetch_into(), odbc_fetch_row(), odbc_field_name(), odbc_field_num(), odbc_field_type(), odbc_field_len(), odbc_field_precision(), odbc_field_scale(), odbc_longreadlen(), odbc_num_fields(), odbc_num_rows(), odbc_result(), odbc_result_all(), odbc_setoption() | odbc_free_result() | ODBC result |
birdstep link | ||||
birdstep result | ||||
OpenSSL key | openssl_get_privatekey(), openssl_get_publickey() | openssl_sign(), openssl_seal(), openssl_open(), openssl_verify() | openssl_free_key() | OpenSSL key |
OpenSSL X.509 | openssl_x509_read() | openssl_x509_parse(), openssl_x509_checkpurpose() | openssl_x509_free() | Public Key |
oracle Cursor | ora_open() | ora_bind(), ora_columnname(), ora_columnsize(), ora_columntype(), ora_error(), ora_errorcode(), ora_exec(), ora_fetch(), ora_fetch_into(), ora_getcolumn(), ora_numcols(), ora_numrows(), ora_parse() | ora_close() | Oracle cursor |
oracle link | ora_logon() | ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() | ora_logoff() | Link to oracle database |
oracle link persistent | ora_plogon() | ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() | None | Persistent link to oracle database |
pdf document | pdf_new() | pdf_add_bookmark(), pdf_add_launchlink(), pdf_add_locallink(), pdf_add_note(), pdf_add_pdflink(), pdf_add_weblink(), pdf_arc(), pdf_attach_file(), pdf_begin_page(), pdf_circle(), pdf_clip(), pdf_closepath(), pdf_closepath_fill_stroke(), pdf_closepath_stroke(), pdf_concat(), pdf_continue_text(), pdf_curveto(), pdf_end_page(), pdf_endpath(), pdf_fill(), pdf_fill_stroke(), pdf_findfont(), pdf_get_buffer(), pdf_get_image_height(), pdf_get_image_width(), pdf_get_parameter(), pdf_get_value(), pdf_lineto(), pdf_moveto(), pdf_open_ccitt(), pdf_open_file(), pdf_open_image_file(), pdf_place_image(), pdf_rect(), pdf_restore(), pdf_rotate(), pdf_save(), pdf_scale(), pdf_setdash(), pdf_setflat(), pdf_setfont(), pdf_setgray(), pdf_setgray_fill(), pdf_setgray_stroke(), pdf_setlinecap(), pdf_setlinejoin(), pdf_setlinewidth(), pdf_setmiterlimit(), pdf_setpolydash(), pdf_setrgbcolor(), pdf_setrgbcolor_fill(), pdf_setrgbcolor_stroke(), pdf_set_border_color(), pdf_set_border_dash(), pdf_set_border_style(), pdf_set_char_spacing(), pdf_set_duration(), pdf_set_font(), pdf_set_horiz_scaling(), pdf_set_parameter(), pdf_set_text_pos(), pdf_set_text_rendering(), pdf_set_value(), pdf_set_word_spacing(), pdf_show(), pdf_show_boxed(), pdf_show_xy(), pdf_skew(), pdf_stringwidth(), pdf_stroke(), pdf_translate(), pdf_open_memory_image() | pdf_close(), pdf_delete() | PDF document |
pdf image | pdf_open_image(), pdf_open_image_file(), pdf_open_memory_image() | pdf_get_image_height(), pdf_get_image_width(), pdf_open_CCITT(), pdf_place_image() | pdf_close_image() | Image in PDF file |
pdf object | ||||
pdf outline | ||||
pgsql large object | pg_lo_open() | pg_lo_open(), pg_lo_create(), pg_lo_read(), pg_lo_read_all(), pg_lo_seek(), pg_lo_tell(), pg_lo_unlink(), pg_lo_write() | pg_lo_close() | PostgreSQL Large Object |
pgsql link | pg_connect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | pg_close() | Link to PostgreSQL database |
pgsql link persistent | pg_pconnect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | None | Persistent link to PostgreSQL database |
pgsql result | pg_query(), pg_get_result() | pg_fetch_array(), pg_fetch_object(), pg_fetch_result(), pg_fetch_row(), pg_field_is_null(), pg_field_name(), pg_field_num(), pg_field_prtlen(), pg_field_size(), pg_field_type(), pg_last_oid(), pg_num_fields(), pg_num_rows(), pg_result_error(), pg_result_status() | pg_free_result() | PostgreSQL result |
pgsql string | ||||
printer | ||||
printer brush | ||||
printer font | ||||
printer pen | ||||
pspell | pspell_new(), pspell_new_config(), pspell_new_personal() | pspell_add_to_personal(), pspell_add_to_session(), pspell_check(), pspell_clear_session(), pspell_config_ignore(), pspell_config_mode(), pspell_config_personal(), pspell_config_repl(), pspell_config_runtogether(), pspell_config_save_repl(), pspell_save_wordlist(), pspell_store_replacement(), pspell_suggest() | None | pspell dictionary |
pspell config | pspell_config_create() | pspell_new_config() | None | pspell configuration |
Sablotron XSLT | xslt_create() | xslt_closelog(), xslt_openlog(), xslt_run(), xslt_set_sax_handler(), xslt_errno(), xslt_error(), xslt_fetch_result(), xslt_free() | xslt_free() | XSLT parser |
shmop | shmop_open() | shmop_read(), shmop_write(), shmop_size(), shmop_delete() | shmop_close() | |
sockets file descriptor set | socket() | accept_connect(), bind(), connect(), listen(), read(), write() | close() | Socket |
sockets i/o vector | ||||
dir | dir() | readdir(), rewinddir() | closedir() | Dir handle |
file | fopen() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), flock(), fpassthru(), fputs(), fwrite(), fread(), fseek(), ftell(), fstat(), ftruncate(), set_file_buffer(), rewind() | fclose() | File handle |
pipe | popen() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | pclose() | Process handle |
socket | fsockopen() | fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | fclose() | Socket handle |
stream | ||||
sybase-db link | sybase_connect() | sybase_query(), sybase_select_db() | sybase_close() | Link to Sybase database using DB library |
sybase-db link persistent | sybase_pconnect() | sybase_query(), sybase_select_db() | None | Persistent link to Sybase database using DB library |
sybase-db result | sybase_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Sybase result using DB library |
sybase-ct link | sybase_connect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | sybase_close() | Link to Sybase database using CT library |
sybase-ct link persistent | sybase_pconnect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | None | Persistent link to Sybase database using CT library |
sybase-ct result | sybase_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Sybase result using CT library |
sysvsem | sem_get() | sem_acquire() | sem_release() | System V Semaphore |
sysvshm | shm_attach() | shm_remove(), shm_put_var(), shm_get_var(), shm_remove_var() | shm_detach() | System V Shared Memory |
wddx | wddx_packet_start() | wddx_add_vars() | wddx_packet_end() | WDDX packet |
xml | xml_parser_create() | xml_set_object(), xml_set_element_handler(), xml_set_character_data_handler(), xml_set_processing_instruction_handler(), xml_set_default_handler(), xml_set_unparsed_entity_decl_handler(), xml_set_notation_decl_handler(), xml_set_external_entity_ref_handler(), xml_parse(), xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number(), xml_get_current_byte_index(), xml_parse_into_struct(), xml_parser_set_option(), xml_parser_get_option() | xml_parser_free() | XML parser |
zlib | gzopen() | gzeof(), gzgetc(), gzgets(), gzgetss(), gzpassthru(), gzputs(), gzread(), gzrewind(), gzseek(), gztell(), gzwrite() | gzclose() | gz-compressed file |
The following is a list of the various URL style protocols that PHP has built-in for use with the filesystem functions such as fopen() and copy(). In addition to these wrappers, as of PHP 4.3.0, you can write your own wrappers using PHP script and stream_wrapper_register().
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.
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
Attribute | Supported |
---|---|
Restricted by allow_url_fopen. | Yes |
Allows Reading | Yes |
Allows Writing | No |
Allows Appending | No |
Allows Simultaneous Reading and Writing | N/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)
Name | Usage | Default |
---|---|---|
method | GET, POST, or any other HTTP method supported by the remote server. | GET |
header | Additional headers to be sent during request. Values in this option will override other values (such as User-agent:, Host:, and Authentication:). | |
user_agent | Value 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.
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
Attribute | PHP 4 | PHP 5 |
---|---|---|
Restricted by allow_url_fopen. | Yes | Yes |
Allows Reading | Yes | Yes |
Allows Writing | Yes (new files only) | Yes (new files/existing files with overwrite) |
Allows Appending | No | Yes |
Allows Simultaneous Reading and Writing | No | No |
Supports stat() | No | filesize(), filetype(), file_exists(), is_file(), and is_dir() elements only. |
Supports unlink() | No | Yes |
Supports rename() | No | Yes |
Supports mkdir() | No | Yes |
Supports rmdir() | No | Yes |
Tabella L-5. Context options (as of PHP 5.0.0)
Name | Usage | Default |
---|---|---|
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 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.
/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 |.
/<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.)
Attribute | Supported |
---|---|
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 Writing | No. These wrappers are unidirectional. |
Supports stat() | No |
Supports unlink() | No |
Supports rename() | No |
Supports mkdir() | No |
Supports rmdir() | No |
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
Attribute | Supported |
---|---|
Restricted by allow_url_fopen. | No |
Allows Reading | Yes |
Allows Writing | Yes |
Allows Appending | Yes |
Allows Simultaneous Reading and Writing | No |
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 |
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().
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.
string.toupper (since PHP 5.0.0) Use of this filter is equivalent to processing all stream data through the strtoupper() function.
string.tolower (since PHP 5.0.0) Use of this filter is equivalent to processing all stream data through the strtolower() function.
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
|
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
|
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.
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
|
Esempio M-8. zlib.deflate simple
|
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
|
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().
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)
Name | Usage | Default |
---|---|---|
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. |
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.
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
Expression | gettype() | empty() | is_null() | isset() | boolean : if($x) |
---|---|---|---|---|---|
$x = ""; | string | TRUE | FALSE | TRUE | FALSE |
$x = NULL | NULL | TRUE | TRUE | FALSE | FALSE |
var $x; | NULL | TRUE | TRUE | FALSE | FALSE |
$x is undefined | NULL | TRUE | TRUE | FALSE | FALSE |
$x = array(); | array | TRUE | FALSE | TRUE | FALSE |
$x = false; | boolean | TRUE | FALSE | TRUE | FALSE |
$x = true; | boolean | FALSE | FALSE | TRUE | TRUE |
$x = 1; | integer | FALSE | FALSE | TRUE | TRUE |
$x = 42; | integer | FALSE | FALSE | TRUE | TRUE |
$x = 0; | integer | TRUE | FALSE | TRUE | FALSE |
$x = -1; | integer | FALSE | FALSE | TRUE | TRUE |
$x = "1"; | string | FALSE | FALSE | TRUE | TRUE |
$x = "0"; | string | TRUE | FALSE | TRUE | FALSE |
$x = "-1"; | string | FALSE | FALSE | TRUE | TRUE |
$x = "php"; | string | FALSE | FALSE | TRUE | TRUE |
$x = "true"; | string | FALSE | FALSE | TRUE | TRUE |
$x = "false"; | string | FALSE | FALSE | TRUE | TRUE |
Tabella O-2. Loose comparisons with ==
TRUE | FALSE | 1 | 0 | -1 | "1" | "0" | "-1" | NULL | array() | "php" | |
---|---|---|---|---|---|---|---|---|---|---|---|
TRUE | TRUE | FALSE | TRUE | FALSE | TRUE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE |
FALSE | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | TRUE | TRUE | FALSE |
1 | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE |
0 | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | TRUE | FALSE | TRUE |
-1 | TRUE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE |
"1" | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE |
"0" | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE |
"-1" | TRUE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE |
NULL | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | TRUE | TRUE | FALSE |
array() | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | TRUE | FALSE |
"php" | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE |
Tabella O-3. Strict comparisons with ===
TRUE | FALSE | 1 | 0 | -1 | "1" | "0" | "-1" | NULL | array() | "php" | |
---|---|---|---|---|---|---|---|---|---|---|---|
TRUE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE |
FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE |
1 | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE |
0 | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE |
-1 | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE |
"1" | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE |
"0" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE |
"-1" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE |
NULL | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE |
array() | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE |
"php" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE |
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.
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
Token | Syntax | Reference |
---|---|---|
T_AND_EQUAL | &= | assignment operators |
T_ARRAY | array() | array(), array syntax |
T_ARRAY_CAST | (array) | type-casting |
T_AS | as | foreach |
T_BAD_CHARACTER | anything below ASCII 32 except \t (0x09), \n (0x0a) and \r (0x0d) | |
T_BOOLEAN_AND | && | logical operators |
T_BOOLEAN_OR | || | logical operators |
T_BOOL_CAST | (bool) or (boolean) | type-casting |
T_BREAK | break | break |
T_CASE | case | switch |
T_CHARACTER | ||
T_CLASS | class | classes and objects |
T_CLOSE_TAG | ?> or %> | |
T_COMMENT | // or # | comments |
T_CONCAT_EQUAL | .= | assignment operators |
T_CONST | const | |
T_CONSTANT_ENCAPSED_STRING | "foo" or 'bar' | string syntax |
T_CONTINUE | continue | |
T_CURLY_OPEN | ||
T_DEC | -- | incrementing/decrementing operators |
T_DECLARE | declare | declare |
T_DEFAULT | default | switch |
T_DIV_EQUAL | /= | assignment operators |
T_DNUMBER | 0.12, etc | floating point numbers |
T_DO | do | do..while |
T_DOLLAR_OPEN_CURLY_BRACES | ${ | complex variable parsed syntax |
T_DOUBLE_ARROW | => | array syntax |
T_DOUBLE_CAST | (real), (double) or (float) | type-casting |
T_ECHO | echo | echo() |
T_ELSE | else | else |
T_ELSEIF | elseif | elseif |
T_EMPTY | empty | empty() |
T_ENCAPSED_AND_WHITESPACE | ||
T_ENDDECLARE | enddeclare | declare, alternative syntax |
T_ENDFOR | endfor | for, alternative syntax |
T_ENDFOREACH | endforeach | foreach, alternative syntax |
T_ENDIF | endif | if, alternative syntax |
T_ENDSWITCH | endswitch | switch, alternative syntax |
T_ENDWHILE | endwhile | while, alternative syntax |
T_END_HEREDOC | heredoc syntax | |
T_EVAL | eval() | eval() |
T_EXIT | exit or die | exit(), die() |
T_EXTENDS | extends | extends, classes and objects |
T_FILE | __FILE__ | constants |
T_FOR | for | for |
T_FOREACH | foreach | foreach |
T_FUNCTION | function or cfunction | functions |
T_GLOBAL | global | variable scope |
T_IF | if | if |
T_INC | ++ | incrementing/decrementing operators |
T_INCLUDE | include() | include() |
T_INCLUDE_ONCE | include_once() | include_once() |
T_INLINE_HTML | ||
T_INT_CAST | (int) or (integer) | type-casting |
T_ISSET | isset() | isset() |
T_IS_EQUAL | == | comparison operators |
T_IS_GREATER_OR_EQUAL | >= | comparison operators |
T_IS_IDENTICAL | === | comparison operators |
T_IS_NOT_EQUAL | != or <> | comparison operators |
T_IS_NOT_IDENTICAL | !== | comparison operators |
T_SMALLER_OR_EQUAL | <= | comparison operators |
T_LINE | __LINE__ | constants |
T_LIST | list() | list() |
T_LNUMBER | 123, 012, 0x1ac, etc | integers |
T_LOGICAL_AND | and | logical operators |
T_LOGICAL_OR | or | logical operators |
T_LOGICAL_XOR | xor | logical operators |
T_MINUS_EQUAL | -= | assignment operators |
T_ML_COMMENT | /* and */ | comments |
T_MOD_EQUAL | %= | assignment operators |
T_MUL_EQUAL | *= | assignment operators |
T_NEW | new | classes and objects |
T_NUM_STRING | ||
T_OBJECT_CAST | (object) | type-casting |
T_OBJECT_OPERATOR | -> | classes and objects |
T_OLD_FUNCTION | old_function | old_function |
T_OPEN_TAG | <?php, <? or <% | escaping from HTML |
T_OPEN_TAG_WITH_ECHO | <?= or <%= | escaping from HTML |
T_OR_EQUAL | |= | assignment operators |
T_PAAMAYIM_NEKUDOTAYIM | :: | :: |
T_PLUS_EQUAL | += | assignment operators |
T_PRINT | print() | print() |
T_REQUIRE | require() | require() |
T_REQUIRE_ONCE | require_once() | require_once() |
T_RETURN | return | returning values |
T_SL | << | bitwise operators |
T_SL_EQUAL | <<= | assignment operators |
T_SR | >> | bitwise operators |
T_SR_EQUAL | >>= | assignment operators |
T_START_HEREDOC | <<< | heredoc syntax |
T_STATIC | static | variable scope |
T_STRING | ||
T_STRING_CAST | (string) | type-casting |
T_STRING_VARNAME | ||
T_SWITCH | switch | switch |
T_UNSET | unset() | unset() |
T_UNSET_CAST | (unset) | (not documented; casts to NULL) |
T_USE | use | (not implemented) |
T_VAR | var | classes and objects |
T_VARIABLE | $foo | variables |
T_WHILE | while | while, do..while |
T_WHITESPACE | ||
T_XOR_EQUAL | ^= | assignment operators |
T_FUNC_C | __FUNCTION__ | constants, since PHP 4.3.0 |
T_CLASS_C | __CLASS__ | constants, since PHP 4.3.0 |
See also token_name().
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.
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.)
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.
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.
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.
v1.0, 8 June 1999
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.
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.
All modified versions of documents covered by this license, including translations, anthologies, compilations and partial documents, must meet the following requirements:
The modified version must be labeled as such.
The person making the modifications must be identified and the modifications dated.
Acknowledgement of the original author and publisher if applicable must be retained according to normal academic citation practices.
The location of the original unmodified document must be identified.
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.
In addition to the requirements of this license, it is requested from and strongly recommended of redistributors that:
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.
All substantive modifications (including deletions) be either clearly marked up in the document or else described in an attachment to the document.
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).
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.