2005-10-26
Copyright © 1997-2005 Gruppo di Documentazione PHP
Copyright
Questo manuale è © Copyright 1997-2005 del Gruppo di Documentazione PHP. Questo manuale può essere redistribuito secondo i termini e le condizioni indicate dalla Open Publication License, v1.0 o successive (l'ultima versione è disponibile a http://www.opencontent.org/openpub/).
La distribuzione di versioni modificate di questo manuale è proibita senza l'esplicito consenso dei detentori del copyright.
La distribuzione di parte o di derivati da parti del manuale in qualsiasi forma di libro standard (cartaceo) è proibita senza un preventivo permesso ottenuto dai detentori del copyright.
In caso si desideri distribuire o pubblicare questo documento, totalmente od in parte, sia in versione integrale o modificata, oppure se si hanno dubbi, contattare i detentori del copyright a phpdoc@lists.php.net. Nota: questo indirizzo porta ad una mailing list pubblica.
La sezione 'Estendere PHP 4.0' di questo manuale è copyright © 2000 della Zend Technologies, Ltd. Questo materiale può essere distribuito solo secondo i termini e le condizioni della Open Publication License, v1.0 o successiva (la versione più recente è al momento disponibile qui http://www.opencontent.org/openpub/).
PHP, che significa "PHP: Hypertext Preprocessor", è un linguaggio di scripting general-purpose Open Source molto utilizzato, è specialmente indicato per lo sviluppo Web e può essere integrato nell'HTML. La sua sintassi è basata su quella di C, Java e Perl, ed è molto semplice da imparare. L'obiettivo principale del linguaggio è quello di permettere agli sviluppatori web di scrivere velocemente pagine web dinamiche, ma con PHP si possono fare molte altre cose.
Questo manuale consiste principalmente in un elenco commentato di funzioni, ma contiene anche una guida al linguaggio, la spiegazione di alcune delle principali caratteristiche e altre informazioni aggiuntive.
Il manuale è fornito in diversi formati qui: ???. Maggiori informazioni su come questo manuale viene sviluppato possono essere trovate nell'appendice 'Informazioni sul Manuale'. Se si è interessati alla storia del PHP, leggere l'appendice.
We highlight the currently most active people on the manual frontpage, but there are many more contributors who currently help in our work or provided a great amount of help to the project in the past. There are a lot of unnamed people who help out with their user notes on manual pages, which continually get included in the references, the work of whom we are also very thankful. All the lists provided below are in alphabetical order.
The following contributors should be recognized for the impact they have made and/or continue to make by adding content to the manual: Jouni Ahto, Alexander Aulbach, Daniel Beckham, Stig Bakken, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Stanislav Malyshev, Rafael Martinez, Yasuo Ohgaki, Derick Rethans, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Lars Torben Wilson, Jim Winstead, Jeroen van Wolffelaar e Andrei Zmievski.
The following contributors have done significant work editing the manual: Stig Bakken, Hartmut Holzgraefe e Egon Schmid.
The currently most active maintainers are: Mehdi Achour, Friedhelm Betz, Vincent Gevers, Aidan Lister, Nuno Lopes e Tom Sommer.
These people have also put a lot of effort into managing user notes: Daniel Beckham, Victor Boivie, Jesus M. Castagnetto, Nicolas Chaillan, Ron Chmara, James Cox, Sara Golemon, Zak Greant, Szabolcs Heilig, Oliver Hinckel, Hartmut Holzgraefe, Rasmus Lerdorf, Andrew Lindeman, Maxim Maletsky, James Moore, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Jani Taskinen, Yasuo Ohgaki, Philip Olson, Lars Torben Wilson, Jim Winstead, Jared Wyles e Jeroen van Wolffelaar.
PHP (acronimo ricorsivo per "PHP: Hypertext Preprocessor") è un linguaggio di scripting general-purpose Open Source molto utilizzato, è specialmente indicato per lo sviluppo Web e può essere integrato nell'HTML.
Risposta banale, ma che cosa significa? Un esempio:
Notate come questo esempio è differente da uno script scritto in altri linguaggi tipo Perl o C -- invece di scrivere un programma con parecchi comandi per produrre HTML, si scrive in HTML con qualche comando immerso per ottenere dei risultati (in questo semplice esempio, la visualizzazione di una frase). Il codice PHP è delimitato da speciali start ed end tag che ne indicano l'inizio e la fine e che consentono di passare dal modo HTML al modo PHP.
Ciò che distingue PHP da altri linguaggi di scripting del tipo client-side JavaScript è che il codice viene eseguito nel server. Per avere uno script simile a quello sopra nel vostro server, il client dovrebbe ricevere il risultato ottenuto con lo script, senza sapere mai quali sono le funzioni eseguite. Potete persino configurare il vostro web server per processare tutte i vostri file HTML con PHP ed allora non ci sarebbe realmente alcun modo per gli utenti di sapere cosa avete sul vostro server.
La cosa più interessante nell'uso di PHP è che si tratta di un linguaggio estremamente semplice per il neofita, ma che, tuttavia, offre molte prestazioni avanzate al programmatore di professione. Non lasciatevi impressionare dalla lunga lista delle potenzialità di PHP. In poco tempo potrete iniziare a creare velocemente semplici scripts.
Sebbene lo sviluppo di PHP abbia come obiettivo lo scripting server-side, si può fare molto di più con esso. Leggete, e consultate la sezione Che cosa può fare PHP? oppure andate su tutorial introduttivo se si è interessati solo alla programmazione web.
Qualsiasi cosa. PHP ha come obiettivo principale lo scripting server-side, per cui può fare tutto ciò che può fare un qualunque programma CGI, come raccogliere dati da un form, generare pagine dai contenuti dinamici, oppure mandare e ricevere cookies. Ma PHP può fare molto di più.
Esistono tre campi principali in cui vengono usati gli scripts PHP.
Lo scripting server-side. Questo è il campo più tradizionale ed il maggiore obiettivo del PHP. Per fare questo lavoro occorrono tre cose. Il parser PHP (CGI o server module), un webserver ed un browser web. Occorre avviare il server web con un'installazione di PHP attiva. Si può accedere all'output del programma PHP con un browser web e vedere la pagina PHP tramite il server. Tutto ciò può essere attivato sul pc di casa se si desidera semplicemenet provare la programmazione PHP. Consultate la sezione Istruzioni per l'installazione per ulteriori informazioni.
Lo scripting di righe di comando. Si può creare uno script PHP da usare senza alcun server o browser. Per usarlo in questo modo, l'unica cosa necessaria è un parser PHP. Questo tipo di utilizzo è ideale per gli scripts eseguiti con cron (sui sistemi *nix o Linux) oppure il Task Scheduler (su Windows). Questi script possono essere utilizzati per semplici task di proessamento testi. Vedere la sezione Uso di righe di comando in PHP per maggiori informazioni.
Scrittura di applicazioni desktop. Probabilmente PHP non è il linguaggio più adatto per scrivere applicazioni desktop, con interfaccia grafica, ma, se lo si conosce molto bene, e se se ne vogliono usare delle caratteristiche avanzate in applicazioni client-side, si può anche adoperare PHP-GTK per scrivere questo tipo di pogrammi. Allo stesso modo, c'è anche la possibilità di scrivere applicazioni cross-platform. PHP-GTK è un'estensione di PHP non reperibile nella grande distribuzione. Se vi interessa, visitate il sito web.
PHP può essere usato su tutti i principali sistemi operativi, inclusi Linux, molte varianti di Unix (compresi HP-UX, Solaris e OpenBSD), Microsoft Windows, MacOS X, MacOS Xserver, RISC OS, e probabilmente altri. Inoltre supporta anche la maggior parte dei server web esistenti. Ciò comprende Apache, Microsoft Internet Information Server, Personal Web Server, i servers Netscape ed iPlanet, Oreilly Website Pro Server, Caudium, Xitami, OmniHTTPd, e molti altri. Per la maggioranza dei servers PHP ha un modulo, per gli altri che supportano lo standard CGI, può funzionare come un processore CGI.
Pertanto, con PHP si ha la libertà di scegliere praticamente qualsiasi sistema operativo e qualsiasi server web. Inoltre, si può anche scegliere se fare uso di una programmazione procedurale oppure orientata agli oggetti, o una combinazione di entrambe. Sebbene non tutte le caratteristiche standard di OOP siano realizzate in PHP 4, molte librerie di codice e grandi applicazioni (compresa PEAR library) sono state scritte usando codice OOP. Con la version 5, il PHP supera le debolezze dell'OOP presenti in PHP 4, ed introduce in modo completo il modello a oggetti.
Con PHP non siete limitati soltanto ad un output in HTML. Le possibilità di PHP, infatti, includono l'abilità di generare immagini, files PDF e perfino filmati Flash al volo (utilizzando libswf e Ming). Sarete in grado di generare facilmente qualsiasi testo, come XHTML e qualsiasi altro file XML. PHP può autogenerare questi file, e salvarli nel file system, piuttosto che eseguire un printing esterno, o creare server-side cache per contenuti dinamici.
Una delle caratteristiche più importanti e significative di PHP è la possibilit` di supportare una completa gamma di databases. Scrivere una pagina web collegata ad un database è incredibilmente semplice. Attualmente sono supportati i seguenti database:
Esiste anche un'estensione DBX database abstraction extension, che vi permette di usare in modo trasparente qualsiasi database da essa supportato. Inoltre PHP supporta ODBC, lo standard di collegamento con i database, pertanto è possibile collegarsi con qualsiasi database che supporti questo standard mondiale.
Adabas D InterBase PostgreSQL dBase FrontBase SQLite Empress mSQL Solid FilePro (read-only) Direct MS-SQL Sybase Hyperwave MySQL Velocis IBM DB2 ODBC Unix dbm Informix Oracle (OCI7 and OCI8) Ingres Ovrimos
PHP fa anche da supporto per dialogare con altri servizi utilizzando i protocolli del tipo LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (in Windows) e innumerevoli altri. Potete anche aprire network sockets ed interagire usando qualsiasi altro protocollo. Inoltre supporta l'interscambio di dati complessi WDDX tra, virtualmente, tutti i linguaggi di programmazione web. A proposito di interconessioni, PHP supporta l'installazione dei JavaObjects e l'utilizzo di questi come oggetti PHP in modo trasparente. Si può anche usare la nostra estensione CORBA per accedere ad oggetti remoti.
PHP possiede alcune caratteristiche molto utili per la gestione del testo, da POSIX Extended o Perl regular expressions al parsing di documenti XML. Per fare il parsing ed accedere ai documenti XML, il PHP 4 supporta gli standard SAX e DOM, e si può utilizzare il modulo XSLT per le trasformazioni dei docuemtni XML. Il PHP 5 standardizza tutte le estensioni XML sulla base solida di libxml2 ed espande le caratteristiche aggiungendo SimpleXML ed XMLReader.
Se si usa PHP nel campo dell'E-commerce, si avranno a disposizione funzioni utili per i programmi di pagamento online, come: Cybercash, CyberMUT, Verysign Payflow Pro e MCVE.
L'ultimo, ma di non poca importanza, PHP ha molte altre estensioni interessanti, come funzioni per motori di ricerca mnoGoSearch, le funzioni IRC Gateway, molte utilità di compressione (gzip, bz2), conversione dei calendari, traduzione...
Come si può notare, questa pagina non è sufficiente per elencare tutte le funzioni che PHP offre. Per approfondire il discorso sulle suddette caratteristiche, consultate le sezioni Installazione di PHP, e function reference
Di seguito, in una breve e semplice introduzione, vorremmo mostrare alcuni esempi per l'utilizzo di PHP. Essi sono relativi soltanto alla creazione dinamica di pagine web, anche se PHP non ha funzionalità limitate esclusivamente alla creazione delle sole pagine web. Fare riferimento alla sezione intitolata Cosa può fare PHP per avere ulteriori informazioni.
Le pagine web create con PHP vengono trattate come normali pagine HTML e possono essere create e modificate nello stesso modo in cui si sviluppano normali pagine HTML.
In questo tutorial assumiamo che il vostro server abbia il suporto PHP attivato e che tutti i file con estensione .php vengano gestiti da questo. Quasi in tutti i server questa è l'estensione di default per i file PHP., ma consultatevi col vostro system administrator per sicurezza. Se il vostro server supporta PHP, allora, non è necessario fare nulla. Semplicemente create i vostri file .php e scaricateli nella vostra directory web, il server le analizzerà e le eseguirà magicamente. Non è necessario compilare nulla nè installare strumenti aggiuntivi. Si pensi ai file PHP come a dei semplici file HTML con una intera famiglia aggiuntiva di magici tags che consentono di fare ogni sorta di cose.
Creare un file con nome ciao.php nella directory del web server che abbia il seguente contenuto:
Si noti che questo file non è come uno script CGI. Il file non necessita in alcun modo di essere eseguibile o speciale in alcuna maniera. Si pensi ad esso come ad un normale file HTML nel quale sono contenuti uno speciale set di tags che permettono di eseguire una moltitudine di cose interessanti.
Questo programma è molto semplice e sicuramente non era necessario fare ricorso a PHP per creare una pagina come quella. Tutto ciò che essa fa è di visualizzare: Hello World! usando la funzione echo() di PHP.
Se si è provato questo esempio e non ha dato alcun output, o è apparso un pop-up che chiedeva se scaricare la pagina, o se è apparso il file come testo, probabilmente che il server su cui si stanno effettuando le prove non ha abilitato PHP. Provare a chiedere al proprio amministratore di sistema di abilitarlo per voi usando il capitolo del manuale dedicato all'Installazione. Se si vogliono sviluppare in locale script PHP, fare riferimento alla sezione download. Si può sviluppare senza problemi sul proprio Sistema Operativo in locale, è bene installare anche un web server.
L'obiettivo dell'esempio è quello di mostrare il formato speciale dei tag PHP. In questo esempio abbiamo usato <?php per indicare l'inizio di un tag PHP. Quindi abbiamo scritto la funzione PHP e abbiamo lasciato la modalità PHP usando il tag di chiusura, ?>. All'interno di un file HTML si può entrare ed uscire dalla modalità PHP quante volte si desidera.
Nota riguardo gli editor di testo: Esistomo molti editor di testo e Integrated Development Environment (IDE) che possono essere usati per creare, modificare e gestire file PHP. Una lista parziale di questi strumenti è disponibile qui: PHP Editor's List. Se si desidera suggerire un nuovo programma, visitare la pagina sopra e chiedere al curatore di aggiungerlo alla lista.
Nota riguardo i Word Processor: Word processor quali StarOffice Writer, Microsoft Word e Abiword non sono una buona scelta per modificare i file PHP.
Se si vogliono provare comunque per scrivere questo script di test, ci si deve assicurare di salvare il file come SOLO TESTO, altrimenti PHP non sarà in grado di leggerlo e quindi non riuscirà ad eseguire lo script.
Nota riguardo Blocco Note di Windows: Se si scrive codice usando l'applicazione di Windows Blocco Note, occorre assicurarsi che i file vengano salvati con estensione .php. (Blocco Note aggiunge automaticamente l'estensione .txt ai file, a meno che non si intraprenda uno dei passi descritti di seguito.)
Quando si salva il file e viene chiesto il nome da assegnargli, scrivere il nome fra virgolette (ad esempio: "ciao.php").
In alternativa, si può cliccare sul menu a tendina 'Documenti di Testo' nella finestra di salvataggio e cambiare l'impostazione in "Tutti i File". A quel punto si può inserire il nome del file, senza usare le virgolette.
Andiamo a fare qualcosa di leggermente più utile. Andremo a controllare che tipo di browser sta utilizzando la persona che visita le nostre pagine. Per fare questo si andrà a controllare la stringa dell'user agent che il browser invia come parte della richiesta HTTP. Quest'informazione viene inviata in una variabile. Le Variabili iniziano sempre con il simbolo di dollaro $ in PHP. La variabile alla quale ci riferiamo adesso è $_SERVER["HTTP_USER_AGENT"].
Note sulle variabili Autoglobali di PHP: $_SERVER è una variabile speciale riservata a PHP la quale contiene tutte le informazioni relative al Web Server. È conosciuta come Variabile autoglobale (o Superglobale). Per maggiori informazioni è possibile vedere la pagina del manuale relativa alle Variabili Autoglobali. Questo tipo di variabili sono state introdotte nella versione 4.1.0 di PHP. Nelle versioni precedenti abbiamo utilizzato le ormai vecchie $HTTP_SERVER_VARS, oggi in disuso, anche se queste continuano ad esistere. (Potete guardare nelle note del vecchio codice.)
Per visualizzare questa variabile, dobbiamo semplicemente:
Ci sono molti types (tipi) di variabili disponibili in PHP. Nell'esempio di sopra abbiamo stampato un elemento di un Array. Gli Array possono essere molto utili.
$_SERVER è soltanto una variabile che automaticamente viene resa diponibile da PHP. È possibile visualizzare una lunga lista nella sezione Variabili riservate del manuale oppure ottenere la lista completa creando un file php nella seguente forma:
Se caricate questo documento da un browser riceverete una pagina piena d'informazioni circa PHP, così come la lista di tutte le variabili disponibili.
Potete mettere dichiarazioni multipli di PHP all'interno di un tag di PHP e generare piccoli blocchi di codice che fanno di più di un singolo echo. Per esempio, se desiderassimo controllare per vedere se l'utente usa Internet Explorer potremmo fare qualcosa come questo:
Esempio 2-4. Esempi usando le strutture di controllo e le funzioni
L'output di esempio di questo script potrebbe essere:
|
Qui introduciamo una coppia di nuovi concetti. Abbiamo la dichiarazione if (se). Se avete una conoscenza con la sintassi di base usata dal linguaggio C questo dovrebbe sembrare logico per voi. Se non conoscete abbastanza C od un altro linguaggio che utilizza la sintassi qui sopra descritta, dovreste probabilmente prendere qualsiasi libro introduttivo di PHP e leggere i primi capitoli, o leggere la parte del manuale relativa ai Riferimenti del Linguaggio. Potete trovare una lista dei libri di PHP su http://www.php.net/books.php.
Il secondo concetto che abbiamo introdotto era la chiamata alla funzione strstr(). Questa è una funzione sviluppata in PHP che cerca una stringa all'interno di un'altra stringa. In questo caso abbiamo cercato "MSIE" all'interno della stringa $_SERVER["HTTP_USER_AGENT"]. Se la stringa viene trovata, la funzione restituisce TRUE altrimenti, FALSE. Se restituisce TRUE, la dichiarazione if viene valuta come TRUE ed il codice all'interno dei relativi {braces} (sostegni) sarà eseguito. Altrimenti, non esegue altro. Sentitevi liberi di generare esempi simili, con if, else (altrimenti) ed altre funzioni quali strtoupper() e strlen(). Ogni pagina del manuale, relativa a queste funzioni contiene anche degli esempi pratici.
Possiamo fare un passo avanti e mostrarvi come potete entrare ed uscite dal modo PHP anche dall' interno di un blocco PHP:
Invece di usare la dichiarazione echo per fare l'output di qualcosa, saltiamo fuori dal modo PHP inviando soltanto HTML puro. Il punto importante da notare qui è che il flusso logico dello script rimane intatto. Solo uno dei blocchi di di HTML finirà per essere inviato come risposta, dipendendo se strstr() ritorna TRUE o FALSE in altre parole, se la stringa MSIE viene trovata o meno.
Una delle caratteritiche più forti di PHP è il modo in cui gestisce i form. Il concetto da comprendere principalmente è che qualsiasi elemento di un form sarà automaticamente disponibile per i vostri script PHP. Per maggiori informazioni ed esempi relativi all'utilizzo dei form consultate la sezione del manuale che si riferisce a le Variabili al di fuori di PHP. A seguire un esempio di un form HTML:
Questo form non ha niente di speciale. È un semplice form in HTML che non presenta nessun tipo di tags particolari. Quando l'utente riempie questo form e preme il pulsante submit, viene richiamata la pagina action.php. In questo file il risultato sarà qualcosa di simile:
Ciò che avviene dovrebbe risultare ovvio. Non c' è altro da aggiungere. Le variabili $_POST["name"] e $_POST["age"] vengono impostate automaticamente dal PHP. Prima avevamo usato la variabile autoglobal $_SERVER, ora invece abbiamo introdotto la variabile autoglobal $_POST che contiene tutti i dati di tipo POST. Notate che il metodo del nostro form è il POST. Se usassimo il metodo GET le informazioni ricavate dal nostro form si troverebbero invece in $_GET. Si può anche usare la variabile $_REQUEST se la provenienza dei dati richiesti non ci interessa. Questa variabile contiene un misto di dati GET, POST, COOKIE e FILE. Vedere anche la funzione import_request_variables().
Da quando il PHP è divenuto un linguaggio di scripting popolare, esistono più fonti che producono listati di codice che si possono adoperare nei propri scripts. La maggioranza degli sviluppatori del PHP ha cercato di renderlo compatibile con le versioni precedenti, perciò uno script creato per una vecchia versione del PHP dovrebbe girare senza modifiche (in teoria) in una più recente, ma in pratica spesso possono servire delle correzioni.
Ecco due delle più importanti modifiche apportate al vecchio codice:
Il disuso dei vecchi arrays $HTTP_*_VARS (che devono essere dichiarati global quando vengano adoperati all' interno di una funzione o di un metodo). L' introduzione in PHP 4.1.0 dei seguenti autoglobal arrays: $_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, $_REQUEST, and $_SESSION. I vecchi arrays $HTTP_*_VARS quali $HTTP_POST_VARS, invece, continuano ad essere adoperati fin da PHP3.
Le variabili esterne non vengono più registrate nel global scope per default. In altre parole, da PHP 4.2.0 la direttiva PHP register_globals è off per default in php.ini. Il metodo consigliato per accedere a questi valori è quello che fa uso degli arrays autoglobali suddetti. Scripts, libri e tutorials più vecchi devono attenersi a queste direttive. Se, per esempio, qualcuno potesse usare $id dall'URL http://www.example.com/foo.php?id=42. La variabile, $_GET['id'] sarebbe disponibile indifferentemente del fatto che sia on od off.
Con quello che sapete ora dovreste essere in grado di comprendere la maggior parte del manuale ed anche i vari scripts di esempio reperibili nelle raccolte di esempi. Inoltre potete trovarne altri sui siti web di php.net nella sezione links: http://www.php.net/links.php.
Before starting the installation, first you need to know what do you want to use PHP for. There are three main fields you can use PHP, as described in the What can PHP do? section:
Server-side scripting
Command line scripting
Client-side GUI applications
For the first and most common form, you need three things: PHP itself, a web server and a web browser. You probably already have a web browser, and depending on your operating system setup, you may also have a web server (e.g. Apache on Linux and MacOS X; IIS on Windows). You may also rent webspace at a company. This way, you don't need to set up anything on your own, only write your PHP scripts, upload it to the server you rent, and see the results in your browser.
While setting up the server and PHP on your own, you have two choices for the method of connecting PHP to the server. For many servers PHP has a direct module interface (also called SAPI). These servers include Apache, Microsoft Internet Information Server, Netscape and iPlanet servers. Many other servers have support for ISAPI, the Microsoft module interface (OmniHTTPd for example). If PHP has no module support for your web server, you can always use it as a CGI or FastCGI processor. This means you set up your server to use the CGI executable of PHP to process all PHP file requests on the server.
If you are also interested to use PHP for command line scripting (e.g. write scripts autogenerating some images for you offline, or processing text files depending on some arguments you pass to them), you always need the command line executable. For more information, read the section about writing command line PHP applications. In this case, you need no server and no browser.
With PHP you can also write desktop GUI applications using the PHP-GTK extension. This is a completely different approach than writing web pages, as you do not output any HTML, but manage windows and objects within them. For more information about PHP-GTK, please visit the site dedicated to this extension. PHP-GTK is not included in the official PHP distribution.
From now on, this section deals with setting up PHP for web servers on Unix and Windows with server module interfaces and CGI executables. You will also find information on the command line executable in the following sections.
PHP source code and binary distributions for Windows can be found at http://www.php.net/downloads.php. We recommend you to choose a mirror nearest to you for downloading the distributions.
This section will guide you through the general configuration and installation of PHP on Unix systems. Be sure to investigate any sections specific to your platform or web server before you begin the process.
As our manual outlines in the General Installation Considerations section, we are mainly dealing with web centric setups of PHP in this section, although we will cover setting up PHP for command line usage as well.
There are several ways to install PHP for the Unix platform, either with a compile and configure process, or through various pre-packaged methods. This documentation is mainly focused around the process of compiling and configuring PHP. Many Unix like systems have some sort of package installation system. This can assist in setting up a standard configuration, but if you need to have a different set of features (such as a secure server, or a different database driver), you may need to build PHP and/or your webserver. If you are unfamiliar with building and compiling your own software, it is worth checking to see whether somebody has already built a packaged version of PHP with the features you need.
Prerequisite knowledge and software for compiling:
Basic Unix skills (being able to operate "make" and a C compiler)
An ANSI C compiler
flex: Version 2.5.4
bison: Version 1.28 (preferred), 1.35, or 1.75
A web server
Any module specific components (such as gd, pdf libs, etc.)
The initial PHP setup and configuration process is controlled by the use of the commandline options of the configure script. You could get a list of all available options along with short explanations running ./configure --help. Our manual documents the different options separately. You will find the core options in the appendix, while the different extension specific options are descibed on the reference pages.
When PHP is configured, you are ready to build the module and/or executables. The command make should take care of this. If it fails and you can't figure out why, see the Problems section.
This section contains notes and hints specific to Apache installs of PHP on Unix platforms. We also have instructions and notes for Apache 2 on a separate page.
You can select arguments to add to the configure on line 10 below from the list of core configure options and from extension specific options described at the respective places in the manual. The version numbers have been omitted here, to ensure the instructions are not incorrect. You will need to replace the 'xxx' here with the correct values from your files.
Esempio 4-1. Installation Instructions (Apache Shared Module Version) for PHP
|
Alternatively, to install PHP as a static object:
Esempio 4-2. Installation Instructions (Static Module Installation for Apache) for PHP
|
Nota: Replace php-4 by php-5 and php4 by php5 in PHP 5.
Depending on your Apache install and Unix variant, there are many possible ways to stop and restart the server. Below are some typical lines used in restarting the server, for different apache/unix installations. You should replace /path/to/ with the path to these applications on your systems.
Esempio 4-3. Example commands for restarting Apache
|
The locations of the apachectl and http(s)dctl binaries often vary. If your system has locate or whereis or which commands, these can assist you in finding your server control programs.
Different examples of compiling PHP for apache are as follows:
This will create a libphp4.so shared library that is loaded into Apache using a LoadModule line in Apache's httpd.conf file. The PostgreSQL support is embedded into this libphp4.so library.
This will create a libphp4.so shared library for Apache, but it will also create a pgsql.so shared library that is loaded into PHP either by using the extension directive in php.ini file or by loading it explicitly in a script using the dl() function.
This will create a libmodphp4.a library, a mod_php4.c and some accompanying files and copy this into the src/modules/php4 directory in the Apache source tree. Then you compile Apache using --activate-module=src/modules/php4/libphp4.a and the Apache build system will create libphp4.a and link it statically into the httpd binary (replace php4 by php5 in PHP 5). The PostgreSQL support is included directly into this httpd binary, so the final result here is a single httpd binary that includes all of Apache and all of PHP.
Same as before, except instead of including PostgreSQL support directly into the final httpd you will get a pgsql.so shared library that you can load into PHP from either the php.ini file or directly using dl().
When choosing to build PHP in different ways, you should consider the advantages and drawbacks of each method. Building as a shared object will mean that you can compile apache separately, and don't have to recompile everything as you add to, or change, PHP. Building PHP into apache (static method) means that PHP will load and run faster. For more information, see the Apache webpage on DSO support.
Nota: Apache's default httpd.conf currently ships with a section that looks like this:
Unless you change that to "Group nogroup" or something like that ("Group daemon" is also very common) PHP will not be able to open files.
Nota: Make sure you specify the installed version of apxs when using --with-apxs=/path/to/apxs. You must NOT use the apxs version that is in the apache sources but the one that is actually installed on your system.
This section contains notes and hints specific to Apache 2.0 installs of PHP on Unix systems.
Avvertimento |
We do not recommend using a threaded MPM in production with Apache2. Use the prefork MPM instead, or use Apache1. For information on why, read the following FAQ entry |
You are highly encouraged to take a look at the Apache Documentation to get a basic understanding of the Apache 2.0 Server.
PHP and Apache 2.0.x compatibility notes: The following versions of PHP are known to work with the most recent version of Apache 2.0.x:
These versions of PHP are compatible to Apache 2.0.40 and later.
- PHP 4.3.0 or later available at http://www.php.net/downloads.php.
- the latest stable development version. Get the source code http://snaps.php.net/php4-latest.tar.gz or download binaries for Windows http://snaps.php.net/win32/php4-win32-latest.zip.
- a prerelease version downloadable from http://qa.php.net/.
- you have always the option to obtain PHP through anonymous CVS.
Apache 2.0 SAPI-support started with PHP 4.2.0. PHP 4.2.3 works with Apache 2.0.39, don't use any other version of Apache with PHP 4.2.3. However, the recommended setup is to use PHP 4.3.0 or later with the most recent version of Apache2.
All mentioned versions of PHP will work still with Apache 1.3.x.
Download the most recent version of Apache 2.0 and a fitting PHP version from the above mentioned places. This quick guide covers only the basics to get started with Apache 2.0 and PHP. For more information read the Apache Documentation. The version numbers have been omitted here, to ensure the instructions are not incorrect. You will need to replace the 'NN' here with the correct values from your files.
Esempio 4-4. Installation Instructions (Apache 2 Shared Module Version)
|
Following the steps above you will have a running Apache 2.0 with support for PHP as SAPI module. Of course there are many more configuration options available for both, Apache and PHP. For more information use ./configure --help in the corresponding source tree. In case you wish to build a multithreaded version of Apache 2.0 you must overwrite the standard MPM-Module prefork either with worker or perchild. To do so append to your configure line in step 6 above either the option --with-mpm=worker or --with-mpm=perchild. Take care about the consequences and understand what you are doing. For more information read the Apache documentation about the MPM-Modules.
Nota: If you want to use content negotiation, read the Apache MultiViews FAQ.
Nota: To build a multithreaded version of Apache your system must support threads. This also implies to build PHP with experimental Zend Thread Safety (ZTS). Therefore not all extensions might be available. The recommended setup is to build Apache with the standard prefork MPM-Module.
PHP 4 can be built as a Pike module for the Caudium webserver. Note that this is not supported with PHP 3. Follow the simple instructions below to install PHP 4 for Caudium.
Esempio 4-5. Caudium Installation Instructions
|
You can of course compile your Caudium module with support for the various extensions available in PHP 4. See the reference pages for extension specific configure options.
Nota: When compiling PHP 4 with MySQL support you must make sure that the normal MySQL client code is used. Otherwise there might be conflicts if your Pike already has MySQL support. You do this by specifying a MySQL install directory the --with-mysql option.
To build PHP as an fhttpd module, answer "yes" to "Build as an fhttpd module?" (the --with-fhttpd=DIR option to configure) and specify the fhttpd source base directory. The default directory is /usr/local/src/fhttpd. If you are running fhttpd, building PHP as a module will give better performance, more control and remote execution capability.
Nota: Support for fhttpd is no longer available as of PHP 4.3.0.
This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Sun Solaris.
From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current webservers read the note about subrequests.
You can find more information about setting up PHP for the Netscape Enterprise Server (NES) here: http://benoit.noss.free.fr/php/install-php4.html
To build PHP with Sun JSWS/Sun ONE WS/iPlanet/Netscape webservers, enter the proper install directory for the --with-nsapi=[DIR] option. The default directory is usually /opt/netscape/suitespot/. Please also read /php-xxx-version/sapi/nsapi/nsapi-readme.txt.
Install the following packages from http://www.sunfreeware.com/ or another download site:
autoconf-2.13 |
automake-1.4 |
bison-1_25-sol26-sparc-local |
flex-2_5_4a-sol26-sparc-local |
gcc-2_95_2-sol26-sparc-local |
gzip-1.2.4-sol26-sparc-local |
m4-1_4-sol26-sparc-local |
make-3_76_1-sol26-sparc-local |
mysql-3.23.24-beta (if you want mysql support) |
perl-5_005_03-sol26-sparc-local |
tar-1.13 (GNU tar) |
Make sure your path includes the proper directories PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/bin and make it available to your system export PATH.
gunzip php-x.x.x.tar.gz (if you have a .gz dist, otherwise go to 4).
tar xvf php-x.x.x.tar
Change to your extracted PHP directory: cd ../php-x.x.x
For the following step, make sure /opt/netscape/suitespot/ is where your netscape server is installed. Otherwise, change to the correct path and run:
./configure --with-mysql=/usr/local/mysql \ --with-nsapi=/opt/netscape/suitespot/ \ --enable-libgcc |
Run make followed by make install.
After performing the base install and reading the appropriate readme file, you may need to perform some additional configuration steps.
Configuration Instructions for Sun/iPlanet/Netscape. Firstly you may need to add some paths to the LD_LIBRARY_PATH environment for the server to find all the shared libs. This can best done in the start script for your webserver. The start script is often located in: /path/to/server/https-servername/start. You may also need to edit the configuration files that are located in: /path/to/server/https-servername/config/.
Add the following line to mime.types (you can do that by the administration server):
type=magnus-internal/x-httpd-php exts=php |
Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following, shlib will vary depending on your system, it will be something like /opt/netscape/suitespot/bin/libphp4.so. You should place the following lines after mime types init.
Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="/opt/netscape/suitespot/bin/libphp4.so" Init fn="php4_init" LateInit="yes" errorString="Failed to initialize PHP!" [php_ini="/path/to/php.ini"] |
Configure the default object in obj.conf (for virtual server classes [version 6.0+] in their vserver.obj.conf):
<Object name="default"> . . . .#NOTE this next line should happen after all 'ObjectType' and before all 'AddLog' lines Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...] . . </Object> |
This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):
<Object name="x-httpd-php"> ObjectType fn="force-type" type="magnus-internal/x-httpd-php" Service fn=php4_execute [inikey=value inikey=value ...] </Object> |
Setup of authentication: PHP authentication cannot be used with any other authentication. ALL AUTHENTICATION IS PASSED TO YOUR PHP SCRIPT. To configure PHP Authentication for the entire server, add the following line to your default object:
<Object name="default"> AuthTrans fn=php4_auth_trans . . . </Object> |
To use PHP Authentication on a single directory, add the following:
<Object ppath="d:\path\to\authenticated\dir\*"> AuthTrans fn=php4_auth_trans </Object> |
Nota: The stacksize that PHP uses depends on the configuration of the webserver. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").
Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the webserver itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP 3.x way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running webserver without any valid CGI variables!
Nota: Why are there (invalid) CGI variables in the environment?
Answer: This is because you started the webserver process from the admin server which runs the startup script of the webserver, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started webserver has some CGI environment variables in it. You can test this by starting the webserver not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.
Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):
variables_order = "GPCS" register_globals = On |
You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:
Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...] |
Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:
Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...] |
The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the webserver and insert the result in the webpage. This function uses some undocumented features from the NSAPI library. On Unix the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.
Nota: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!
The default is to build PHP as a CGI program. This creates a commandline interpreter, which can be used for CGI processing, or for non-web-related PHP scripting. If you are running a web server PHP has module support for, you should generally go for that solution for performance reasons. However, the CGI version enables users to run different PHP-enabled pages under different user-ids.
Avvertimento |
By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks. |
As of PHP 4.3.0, some important additions have happened to PHP. A new SAPI named CLI also exists and it has the same name as the CGI binary. What is installed at {PREFIX}/bin/php depends on your configure line and this is described in detail in the manual section named Using PHP from the command line. For further details please read that section of the manual.
If you have built PHP as a CGI program, you may test your build by typing make test. It is always a good idea to test your build. This way you may catch a problem with PHP on your platform early instead of having to struggle with it later.
If you have built PHP 3 as a CGI program, you may benchmark your build by typing make bench. Note that if modalità sicura is on by default, the benchmark may not be able to finish if it takes longer then the 30 seconds allowed. This is because the set_time_limit() can not be used in modalità sicura. Use the max_execution_time configuration setting to control this time for your own scripts. make bench ignores the configuration file.
Nota: make bench is only available for PHP 3.
Some server supplied environment variables are not defined in the current CGI/1.1 specification. Only the following variables are defined there: AUTH_TYPE, CONTENT_LENGTH, CONTENT_TYPE, GATEWAY_INTERFACE, PATH_INFO, PATH_TRANSLATED, QUERY_STRING, REMOTE_ADDR, REMOTE_HOST, REMOTE_IDENT, REMOTE_USER, REQUEST_METHOD, SCRIPT_NAME, SERVER_NAME, SERVER_PORT, SERVER_PROTOCOL, and SERVER_SOFTWARE. Everything else should be treated as 'vendor extensions'.
This section contains notes and hints specific to installing PHP on HP-UX systems. (Contributed by paul_mckay at clearwater-it dot co dot uk).
Nota: These tips were written for PHP 4.0.4 and Apache 1.3.9.
You need gzip, download a binary distribution from http://hpux.connect.org.uk/ftp/hpux/Gnu/gzip-1.2.4a/gzip-1.2.4a-sd-10.20.depot.Z uncompress the file and install using swinstall.
You need gcc, download a binary distribution from http://gatekeep.cs.utah.edu/ftp/hpux/Gnu/gcc-2.95.2/gcc-2.95.2-sd-10.20.depot.gz. uncompress this file and install gcc using swinstall.
You need the GNU binutils, you can download a binary distribution from http://hpux.connect.org.uk/ftp/hpux/Gnu/binutils-2.9.1/binutils-2.9.1-sd-10.20.depot.gz. uncompress this file and install binutils using swinstall.
You now need bison, you can download a binary distribution from http://hpux.connect.org.uk/ftp/hpux/Gnu/bison-1.28/bison-1.28-sd-10.20.depot.gz, install as above.
You now need flex, you need to download the source from one of the http://www.gnu.org mirrors. It is in the non-gnu directory of the ftp site. Download the file, gunzip, then tar -xvf it. Go into the newly created flex directory and run ./configure, followed by make, and then make install.
If you have errors here, it's probably because gcc etc. are not in your PATH so add them to your PATH.
Download the PHP and apache sources.
gunzip and tar -xvf them. We need to hack a couple of files so that they can compile OK.
Firstly the configure file needs to be hacked because it seems to lose track of the fact that you are a hpux machine, there will be a better way of doing this but a cheap and cheerful hack is to put lt_target=hpux10.20 on line 47286 of the configure script.
Next, the Apache GuessOS file needs to be hacked. Under apache_1.3.9/src/helpers change line 89 from echo "hp${HPUXMACH}-hpux${HPUXVER}"; exit 0 to: echo "hp${HPUXMACH}-hp-hpux${HPUXVER}"; exit 0
You cannot install PHP as a shared object under HP-UX so you must compile it as a static, just follow the instructions at the Apache page.
PHP and Apache should have compiled OK, but Apache won't start. you need to create a new user for Apache, e.g. www, or apache. You then change lines 252 and 253 of the conf/httpd.conf in Apache so that instead of
User nobody Group nogroup |
you have something like
User www Group sys |
This is because you can't run Apache as nobody under hp-ux. Apache and PHP should then work.
This section contains notes and hints specific to installing PHP on OpenBSD 3.6.
Using binary packages to install PHP on OpenBSD is the recommended and simplest method. The core package has been separated from the various modules, and each can be installed and removed independently from the others. The files you need can be found on your OpenBSD CD or on the FTP site.
The main package you need to install is php4-core-4.3.8.tgz, which contains the basic engine (plus gettext and iconv). Next, take a look at the module packages, such as php4-mysql-4.3.8.tgz or php4-imap-4.3.8.tgz. You need to use the phpxs command to activate and deactivate these modules in your php.ini.
Esempio 4-6. OpenBSD Package Install Example
|
Read the packages(7) manual page for more information about binary packages on OpenBSD.
You can also compile up PHP from source using the ports tree. However, this is only recommended for users familiar with OpenBSD. The PHP 4 port is split into two sub-directories: core and extensions. The extensions directory generates sub-packages for all of the supported PHP modules. If you find you do not want to create some of these modules, use the no_* FLAVOR. For example, to skip building the imap module, set the FLAVOR to no_imap.
The default install of Apache runs inside a chroot(2) jail, which will restrict PHP scripts to accessing files under /var/www. You will therefore need to create a /var/www/tmp directory for PHP session files to be stored, or use an alternative session backend. In addition, database sockets need to be placed inside the jail or listen on the localhost interface. If you use network functions, some files from /etc such as /etc/resolv.conf and /etc/services will need to be moved into /var/www/etc. The OpenBSD PEAR package automatically installs into the correct chroot directories, so no special modification is needed there. More information on the OpenBSD Apache is available in the OpenBSD FAQ.
The OpenBSD 3.6 package for the gd extension requires XFree86 to be installed. If you do not wish to use some of the font features that require X11, install the php4-gd-4.3.8-no_x11.tgz package instead.
Older releases of OpenBSD used the FLAVORS system to compile up a statically linked PHP. Since it is hard to generate binary packages using this method, it is now deprecated. You can still use the old stable ports trees if you wish, but they are unsupported by the OpenBSD team. If you have any comments about this, the current maintainer for the port is Anil Madhavapeddy (avsm at openbsd dot org).
This section contains notes and hints specific to installing PHP on Solaris systems.
Solaris installs often lack C compilers and their related tools. Read this FAQ for information on why using GNU versions for some of these tools is necessary. The required software is as follows:
gcc (recommended, other C compilers may work)
make
flex
bison
m4
autoconf
automake
perl
gzip
tar
GNU sed
You can simplify the Solaris install process by using pkgadd to install most of your needed components.
This section contains notes and hints specific to installing PHP on Gentoo Linux.
While you can just download the PHP source and compile it yourself, using Gentoo's packaging system is the simplest and cleanest method of installing PHP. If you are not familiar with building software on Linux, this is the way to go.
If you have built your Gentoo system so far, you are probably used to Portage already. Installing Apache and PHP is no different than the other system tools.
The first decision you need to make is whether you want to install Apache 1.3.x or Apache 2.x. While both can be used with PHP, the steps given below will use Apache 1.3.x. Another thing to consider is whether your local Portage tree is up to date. If you have not updated it recently, you need to run emerge sync before anything else. This way, you will be using the most recent stable version of Apache and PHP.
Now that everything is in place, you can use the following example to install Apache and PHP:
Esempio 4-7. Gentoo Install Example with Apache 1.3
|
You can read more about emerge in the excellent Portage Manual provided on the Gentoo website.
If you need to use Apache 2, you can simply use emerge apache in the last example.
In the last section, PHP was emerged without any activated modules. As of this writing, the only module activated by default with Portage is XML which is needed by PEAR. This may not be what you want and you will soon discover that you need more activated modules, like MySQL, gettext, GD, etc.
When you compile PHP from source yourself, you need to activate modules via the configure command. With Gentoo, you can simply provide USE flags which will be passed to the configure script automatically. To see which USE flags to use with emerge, you can try:
Esempio 4-8. Getting the list of valid USE flags
|
As you can see from the last output, PHP considers a lot of USE flags. Look at them closely and choose what you need. If you choose a flag and you do not have the proper libraries, Portage will compile them for you. It is a good idea to use emerge -pv again to see what Portage will compile in accordance to your USE flags. As an example, if you do not have X installed and you choose to include X in the USE flags, Portage will compile X prior to PHP, which can take a couple of hours.
If you choose to compile PHP with MySQL, cURL and GD support, the command will look something like this:
As in the last example, do not forget to emerge php as well as mod_php. php is responsible for the command line version of PHP as mod_php is for the Apache module version of PHP.
If you see the PHP source instead of the result the script should produce, you have probably forgot to edit /etc/conf.d/apache. Apache needs to be started with the -D PHP4 flag. To see if the flag is present, you should be able to see it when using ps ax | grep apache while Apache is running.
Due to slotting problems, you might end up with more than one version of PHP installed on your system. If this is the case, you need to unmerge the old versions manually by using emerge unmerge mod_php-<old version>.
If you cannot emerge PHP because of Java, try putting -* in front of your USE flags like in the above examples.
If you are having problems configuring Apache and PHP, you can always search the Gentoo Forums. Try searching with the keywords "Apache PHP".
This section contains notes and hints specific to installing PHP on Debian GNU/Linux.
While you can just download the PHP source and compile it yourself, using Debian's packaging system is the simplest and cleanest method of installing PHP. If you are not familiar with building software on Linux, this is the way to go.
The first decision you need to make is whether you want to install Apache 1.3.x or Apache 2.x. The corresponding PHP packages are respectively named libapache-mod-php* and libapache2-mod-php*. The steps given below will use Apache 1.3.x. Please note that, as of this writing, there is no official Debian packages of PHP 5. Then the steps given below will install PHP 4.
PHP is available in Debian as CGI or CLI flavour too, named respectively php4-cgi and php4-cli. If you need them, you'll just have to reproduce the following steps with the good package names. Another special package you'd want to install is php4-pear. It contains a minimal PEAR installation and the pear commandline utility.
If you need more recent packages of PHP than the Debian's stable ones or if some PHP modules lacks the Debian official repository, perhaps you should take a look at http://www.apt-get.org/. One of the results found should be Dotdeb. This unofficial repository is maintained by Guillaume Plessis and contains Debian packages of the most recent versions of PHP 4 and PHP 5. To use it, just add the to following two lines to your /etc/apt/sources.lists and run apt-get update :
The last thing to consider is whether your list of packages is up to date. If you have not updated it recently, you need to run apt-get update before anything else. This way, you will be using the most recent stable version of the Apache and PHP packages.
Now that everything is in place, you can use the following example to install Apache and PHP:
APT will automatically install the PHP 4 module for Apache 1.3, and all its dependencies and then activate it. If you're not asked to restart Apache during the install process, you'll have to do it manually :
In the last section, PHP was installed with only core modules. This may not be what you want and you will soon discover that you need more activated modules, like MySQL, cURL, GD, etc.
When you compile PHP from source yourself, you need to activate modules via the configure command. With APT, you just have to install additional packages. They're all named 'php4-*' (or 'php5-*' if you installed PHP 5 from a third party repository).
As you can see from the last output, there's a lot of PHP modules that you can install (excluding the php4-cgi, php4-cli or php4-pear special packages). Look at them closely and choose what you need. If you choose a module and you do not have the proper libraries, APT will automatically install all the dependencies for you.
If you choose to add the MySQL, cURL and GD support to PHP the command will look something like this:
APT will automatically add the appropriate lines to your different php.ini (/etc/php4/apache/php.ini, /etc/php4/cgi/php.ini, etc).
You'll only have to stop/start Apache as previously to activate the modules.
If you see the PHP source instead of the result the script should produce, APT has probably not included /etc/apache/conf.d/php4 in your Apache 1.3 configuration. Please ensure that the following line is present in your /etc/apache/httpd.conf file then stop/start Apache:
If you installed an additional module and if its functions are not available in your scripts, please ensure that the appropriate line is present in your php.ini, as seen before. APT may fail during the installation of the additional module, due to a confusing debconf configuration.
This section contains notes and hints specific to installing PHP on Mac OS X. There are two slightly different versions of Mac OS X, Client and Server, our manual deals with installing PHP on both systems. Note that PHP is not available for MacOS 9 and earlier versions.
There are a few pre-packaged and pre-compiled versions of PHP for Mac OS X. This can help in setting up a standard configuration, but if you need to have a different set of features (such as a secure server, or a different database driver), you may need to build PHP and/or your web server yourself. If you are unfamiliar with building and compiling your own software, it's worth checking whether somebody has already built a packaged version of PHP with the features you need.
Get the latest distributions of Apache and PHP.
Untar them, and run the configure program on Apache like so.
./configure --exec-prefix=/usr \ --localstatedir=/var \ --mandir=/usr/share/man \ --libexecdir=/System/Library/Apache/Modules \ --iconsdir=/System/Library/Apache/Icons \ --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \ --enable-shared=max \ --enable-module=most \ --target=apache |
If you want the compiler to do some optimization, you may also want to add this line:
setenv OPTIM=-O2 |
Next, go to the PHP 4 source directory and configure it.
./configure --prefix=/usr \ --sysconfdir=/etc \ --localstatedir=/var \ --mandir=/usr/share/man \ --with-xml \ --with-apache=/src/apache_1.3.12 |
Type make and make install. This will add a directory to your Apache source directory under src/modules/php4.
Now, reconfigure Apache to build in PHP 4.
./configure --exec-prefix=/usr \ --localstatedir=/var \ --mandir=/usr/share/man \ --libexecdir=/System/Library/Apache/Modules \ --iconsdir=/System/Library/Apache/Icons \ --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \ --enable-shared=max \ --enable-module=most \ --target=apache \ --activate-module=src/modules/php4/libphp4.a |
Copy and rename the php.ini-dist file to your bin directory from your PHP 4 source directory: cp php.ini-dist /usr/local/bin/php.ini or (if your don't have a local directory) cp php.ini-dist /usr/bin/php.ini.
The following instructions will help you install a PHP module for the Apache web server included in MacOS X. This version includes support for the MySQL and PostgreSQL databases. These instructions are graciously provided by Marc Liyanage.
Avvertimento |
Be careful when you do this, you could screw up your Apache web server! |
Do this to install:
Open a terminal window.
Type wget http://www.diax.ch/users/liyanage/software/macosx/libphp4.so.gz, wait for the download to finish.
Type gunzip libphp4.so.gz.
Type sudo apxs -i -a -n php4 libphp4.so
Now type sudo open -a TextEdit /etc/httpd/httpd.conf. TextEdit will open with the web server configuration file. Locate these two lines towards the end of the file: (Use the Find command)
#AddType application/x-httpd-php .php #AddType application/x-httpd-php-source .phps |
Finally, type sudo apachectl graceful to restart the web server.
PHP should now be up and running. You can test it by dropping a file into your Sites folder which is called test.php. Into that file, write this line: <?php phpinfo() ?>.
Now open up 127.0.0.1/~your_username/test.php in your web browser. You should see a status table with information about the PHP module.
This section applies to Windows 98/Me and Windows NT/2000/XP/2003. PHP will not work on 16 bit platforms such as Windows 3.1 and sometimes we refer to the supported Windows platforms as Win32. Windows 95 is no longer supported as of PHP 4.3.0.
There are two main ways to install PHP for Windows: either manually or by using the installer.
If you have Microsoft Visual Studio, you can also build PHP from the original source code.
Once you have PHP installed on your Windows system, you may also want to load various extensions for added functionality.
Avvertimento |
There are several all-in-one installers over the Internet, but none of those are endorsed by PHP.net, as we believe that the manual installation is the best choice to have your system secure and optimised. |
The Windows PHP installer is available from the downloads page at http://www.php.net/downloads.php. This installs the CGI version of PHP and for IIS, PWS, and Xitami, it configures the web server as well. The installer does not include any extra external PHP extensions (php_*.dll) as you'll only find those in the Windows Zip Package and PECL downloads.
Nota: While the Windows installer is an easy way to make PHP work, it is restricted in many aspects as, for example, the automatic setup of extensions is not supported. Use of the installer isn't the preferred method for installing PHP.
First, install your selected HTTP (web) server on your system, and make sure that it works.
Run the executable installer and follow the instructions provided by the installation wizard. Two types of installation are supported - standard, which provides sensible defaults for all the settings it can, and advanced, which asks questions as it goes along.
The installation wizard gathers enough information to set up the php.ini file, and configure certain web servers to use PHP. One of the web servers the PHP installer does not configure for is Apache, so you'll need to configure it manually.
Once the installation has completed, the installer will inform you if you need to restart your system, restart the server, or just start using PHP.
Avvertimento |
Be aware, that this setup of PHP is not secure. If you would like to have a secure PHP setup, you'd better go on the manual way, and set every option carefully. This automatically working setup gives you an instantly working PHP installation, but it is not meant to be used on online servers. |
This install guide will help you manually install and configure PHP with a web server on Microsoft Windows. To get started you'll need to download the zip binary distribution from the downloads page at http://www.php.net/downloads.php.
Although there are many all-in-one installation kits, and we also distribute a PHP installer for Microsoft Windows, we recommend you take the time to setup PHP yourself as this will provide you with a better understanding of the system, and enables you to install PHP extensions easily when needed.
Upgrading from a previous PHP version: Previous editions of the manual suggest moving various ini and DLL files into your SYSTEM (i.e. C:\WINDOWS) folder and while this simplifies the installation procedure it makes upgrading difficult. We advise you remove all of these files (like php.ini and PHP related DLLs from the Windows SYSTEM folder) before moving on with a new PHP installation. Be sure to backup these files as you might break the entire system. The old php.ini might be useful in setting up the new PHP as well. And as you'll soon learn, the preferred method for installing PHP is to keep all PHP related files in one directory and have this directory available to your systems PATH.
MDAC requirements: If you use Microsoft Windows 98/NT4 download the latest version of the Microsoft Data Access Components (MDAC) for your platform. MDAC is available at http://msdn.microsoft.com/data/. This requirement exists because ODBC is built into the distributed Windows binaries.
The following steps should be completed on all installations before any server specific instructions are performed:
Extract the distribution file into a directory of your choice. If you are installing PHP 4, extract to C:\, as the zip file expands to a foldername like php-4.3.7-Win32. If you are installing PHP 5, extract to C:\php as the zip file doesn't expand as in PHP 4. You may choose a different location but do not have spaces in the path (like C:\Program Files\PHP) as some web servers will crash if you do.
The directory structure extracted from the zip is different for PHP versions 4 and 5 and look like as follows:
Esempio 6-1. PHP 4 package structure
|
Or:
Esempio 6-2. PHP 5 package structure
|
Notice the differences and similarities. Both PHP 4 and PHP 5 have a CGI executable, a CLI executable, and server modules, but they are located in different folders and/or have different names. While PHP 4 packages have the server modules in the sapi folder, PHP 5 distributions have no such directory and instead they're in the PHP folder root. The supporting DLLs for the PHP 5 extensions are also not in a seperate directory.
Nota: In PHP 4, you should move all files located in the dll and sapi folders to the main folder (e.g. C:\php).
Here is a list of server modules shipped with PHP 4 and PHP 5:
sapi/php4activescript.dll (php5activescript.dll) - ActiveScript engine, allowing you to embed PHP in your Windows applications.
sapi/php4apache.dll (php5apache.dll) - Apache 1.3.x module.
sapi/php4apache2.dll (php5apache2.dll) - Apache 2.0.x module.
sapi/php4isapi.dll (php5isapi.dll) - ISAPI Module for ISAPI compliant web servers like IIS 4.0/PWS 4.0 or newer.
sapi/php4nsapi.dll (php5nsapi.dll) - Sun/iPlanet/Netscape server module.
sapi/php4pi3web.dll (no equivalent in PHP 5) - Pi3Web server module.
Server modules provide significantly better performance and additional functionality compared to the CGI binary. The CLI version is designed to let you use PHP for command line scripting. More information about CLI is available in the chapter about using PHP from the command line.
Avvertimento |
The SAPI modules have been significantly improved as of the 4.1 release, however, in older systems you may encounter server errors or other server modules failing, such as ASP. |
The CGI and CLI binaries, and the web server modules all require the php4ts.dll (php5ts.dll) file to be available to them. You have to make sure that this file can be found by your PHP installation. The search order for this DLL is as follows:
The same directory from where php.exe is called, or in case you use a SAPI module, the web server's directory (e.g. C:\Program Files\Apache Group\Apache2\bin).
Any directory in your Windows PATH environment variable.
To make php4ts.dll / php5ts.dll available you have three options: copy the file to the Windows system directory, copy the file to the web server's directory, or add your PHP directory, C:\php to the PATH. For better maintenance, we advise you to follow the last option, add C:\php to the PATH, because it will be simpler to upgrade PHP in the future. Read more about how to add your PHP directory to PATH in the corresponding FAQ entry.
The next step is to set up a valid configuration file for PHP, php.ini. There are two ini files distributed in the zip file, php.ini-dist and php.ini-recommended. We advise you to use php.ini-recommended, because we optimized the default settings in this file for performance, and security. Read this well documented file carefully because it has changes from php.ini-dist that will drastically affect your setup. Some examples are display_errors being off and magic_quotes_gpc being off. In addition to reading these, study the ini settings and set every element manually yourself. If you would like to achieve the best security, then this is the way for you, although PHP works fine with these default ini files. Copy your chosen ini-file to a directory that PHP is able to find and rename it to php.ini. PHP searches for php.ini in the locations described in la Sezione The configuration file nel Capitolo 9 section.
If you are running Apache 2, the simpler option is to use the PHPIniDir directive (read the installation on Apache 2 page), otherwise your best option is to set the PHPRC environment variable. This process is explained in the following FAQ entry.
Nota: If you're using NTFS on Windows NT, 2000, XP or 2003, make sure that the user running the web server has read permissions to your php.ini (e.g. make it readable by Everyone).
The following steps are optional:
Edit your new php.ini file. If you plan to use OmniHTTPd, do not follow the next step. Set the doc_root to point to your web servers document_root. For example:
Choose the extensions you would like to load when PHP starts. See the section about Windows extensions, about how to set up one, and what is already built in. Note that on a new installation it is advisable to first get PHP working and tested without any extensions before enabling them in php.ini.
On PWS and IIS, you can set the browscap configuration setting to point to: c:\windows\system\inetsrv\browscap.ini on Windows 9x/Me, c:\winnt\system32\inetsrv\browscap.ini on NT/2000, and c:\windows\system32\inetsrv\browscap.ini on XP. For an up-to-date browscap.ini, read the following FAQ.
PHP is now setup on your system. The next step is to choose a web server, and enable it to run PHP. Choose a webserver from the table of contents.
This section contains notes specific to the ActiveScript installation.
ActiveScript is a windows only SAPI that enables you to use PHP script in any ActiveScript compliant host, like Windows Script Host, ASP/ASP.NET, Windows Script Components or Microsoft Scriptlet control.
As of PHP 5.0.1, ActiveScript has been moved to the PECL repository. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Nota: You should read the manual installation steps first!
After installing PHP, you should download the ActiveScript DLL (php5activescript.dll) and place it in the main PHP folder (e.g. C:\php).
After having all the files needed, you must register the DLL on your system. To achieve this, open a Command Prompt window (located in the Start Menu). Then go to your PHP directory by typing something like cd C:\php. To register the DLL just type regsvr32 php5activescript.dll.
To test if ActiveScript is working, create a new file, named test.wsf (the extension is very important) and type:
<job id="test"> <script language="PHPScript"> $WScript->Echo("Hello World!"); </script> </job> |
Nota: In PHP 4, the engine was named 'ActivePHP', so if you are using PHP 4, you should replace 'PHPScript' with 'ActivePHP' in the above example.
Nota: ActiveScript doesn't use the default php.ini file. Instead, it will look only in the same directory as the .exe that caused it to load. You should create php-activescript.ini and place it in that folder, if you wish to load extensions, etc.
This section contains notes and hints specific to IIS (Microsoft Internet Information Server).
Avvertimento |
By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks. |
First, read the Manual Installation Instructions. Do not skip this step as it provides crucial information for installing PHP on Windows.
CGI users must set the cgi.force_redirect PHP directive to 0 inside php.ini. Read the faq on cgi.force_redirect for important details. Also, CGI users may want to set the cgi.redirect_status_env directive. When using directives, be sure these directives aren't commented out inside php.ini.
The PHP 4 CGI is named php.exe while in PHP 5 it's php-cgi.exe. In PHP 5, php.exe is the CLI, and not the CGI.
Modify the Windows PATH environment variable to include the PHP directory. This way the PHP DLL files, PHP executables, and php.ini can all remain in the PHP directory without cluttering up the Windows system directory. For more details, see the FAQ on Setting the PATH.
The IIS user (usually IUSR_MACHINENAME) needs permission to read various files and directories, such as php.ini, docroot, and the session tmp directory.
Be sure the extension_dir and doc_root PHP directives are appropriately set in php.ini. These directives depend on the system that PHP is being installed on. In PHP 4, the extension_dir is extensions while with PHP 5 it's ext. So, an example PHP 5 extensions_dir value is "c:\php\ext" and an example IIS doc_root value is "c:\Inetpub\wwwroot".
PHP extension DLL files, such as php_mysql.dll and php_curl.dll, are found in the zip package of the PHP download (not the PHP installer). In PHP 5, many extensions are part of PECL and can be downloaded in the "Collection of PECL modules" package. Files such as php_zip.dll and php_ssh2.dll. Download PHP files here.
When defining the executable, the 'check that file exists' box may also be checked. For a small performance penalty, the IIS (or PWS) will check that the script file exists and sort out authentication before firing up PHP. This means that the web server will provide sensible 404 style error messages instead of CGI errors complaining that PHP did not output any data.
PHP may be installed as a CGI binary, or with the ISAPI module. In either case, you need to start the Microsoft Management Console (may appear as 'Internet Services Manager', either in your Windows NT 4.0 Option Pack branch or the Control Panel=>Administrative Tools under Windows 2000/XP). Then right click on your Web server node (this will most probably appear as 'Default Web Server'), and select 'Properties'.
If you want to use the CGI binary, do the following:
Under 'Home Directory', 'Virtual Directory', or 'Directory', do the following:
Change the Execute Permissions to 'Scripts only'
Click on the 'Configuration' button, and choose the Application Mappings tab. Click Add and set the Executable path to the appropriate CGI file. An example PHP 5 value is: C:\php\php-cgi.exe Supply .php as the extension. Leave 'Method exclusions' blank, and check the 'Script engine' checkbox. Now, click OK a few times.
Set up the appropriate security. (This is done in Internet Service Manager), and if your NT Server uses NTFS file system, add execute rights for I_USR_ to the directory that contains php.exe / php-cgi.exe.
To use the ISAPI module, do the following:
If you don't want to perform HTTP Authentication using PHP, you can (and should) skip this step. Under ISAPI Filters, add a new ISAPI filter. Use PHP as the filter name, and supply a path to the php4isapi.dll / php5isapi.dll.
Under 'Home Directory', 'Virtual Directory', or 'Directory', do the following:
Change the Execute Permissions to 'Scripts only'
Click on the 'Configuration' button, and choose the Application Mappings tab. Click Add and set the Executable path to the appropriate ISAPI DLL. An example PHP 5 value is: C:\php\php5isapi.dll Supply .php as the extension. Leave 'Method exclusions' blank, and check the 'Script engine' checkbox. Now, click OK a few times.
Stop IIS completely (NET STOP iisadmin)
Start IIS again (NET START w3svc)
With IIS 6 (2003 Server), open up the IIS Manager, go to Web Service Extensions, choose "Add a new Web service extension", enter in a name such as PHP, choose the Add button and for the value browse to either the ISAPI file (php4isapi.dll or php5isapi.dll) or CGI (php.exe or php-cgi.exe) then check "Set extension status to Allowed" and click OK.
In order to use index.php as a default content page, do the following: From within the Documents tab, choose Add. Type in index.php and click OK. Adjust the order by choosing Move Up or Move Down. This is similar to setting DirectoryIndex with Apache.
The steps above must be repeated for each extension that is to be associated with PHP scripts. .php is the most common although .php3 may be required for legacy applications.
If you experience 100% CPU usage after some time, turn off the IIS setting Cache ISAPI Application.
PWS 4 does not support ISAPI, only PHP CGI should be used.
Edit the enclosed pws-php4cgi.reg / pws-php5cgi.reg file (look into the SAPI folder for PHP 4, or in the main folder for PHP 5) to reflect the location of your php.exe / php-cgi.exe. Backslashes should be escaped, for example: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w3svc\parameters\Script Map] ".php"="C:\\php\\php.exe" (change to C:\\php\\php-cgi.exe if you are using PHP 5) Now merge this registery file into your system; you may do this by double-clicking it.
In the PWS Manager, right click on a given directory you want to add PHP support to, and select Properties. Check the 'Execute' checkbox, and confirm.
The recommended method for configuring these servers is to use the REG file included with the distribution (pws-php4cgi.reg in the SAPI folder for PHP 4, or pws-php5cgi.reg in the main folder for PHP 5). You may want to edit this file and make sure the extensions and PHP install directories match your configuration. Or you can follow the steps below to do it manually.
Avvertimento |
These steps involve working directly with the Windows registry. One error here can leave your system in an unstable state. We highly recommend that you back up your registry first. The PHP Development team will not be held responsible if you damage your registry. |
Run Regedit.
Navigate to: HKEY_LOCAL_MACHINE /System /CurrentControlSet /Services /W3Svc /Parameters /ScriptMap.
On the edit menu select: New->String Value.
Type in the extension you wish to use for your php scripts. For example .php
Double click on the new string value and enter the path to php.exe in the value data field. ex: C:\php\php.exe "%s" %s for PHP 4, or C:\php\php-cgi.exe "%s" %s for PHP 5.
Repeat these steps for each extension you wish to associate with PHP scripts.
The following steps do not affect the web server installation and only apply if you want your PHP scripts to be executed when they are run from the command line (ex. run C:\myscripts\test.php) or by double clicking on them in a directory viewer window. You may wish to skip these steps as you might prefer the PHP files to load into a text editor when you double click on them.
Navigate to: HKEY_CLASSES_ROOT
On the edit menu select: New->Key.
Name the key to the extension you setup in the previous section. ex: .php
Highlight the new key and in the right side pane, double click the "default value" and enter phpfile.
Repeat the last step for each extension you set up in the previous section.
Now create another New->Key under HKEY_CLASSES_ROOT and name it phpfile.
Highlight the new key phpfile and in the right side pane, double click the "default value" and enter PHP Script.
Right click on the phpfile key and select New->Key, name it Shell.
Right click on the Shell key and select New->Key, name it open.
Right click on the open key and select New->Key, name it command.
Highlight the new key command and in the right side pane, double click the "default value" and enter the path to php.exe. ex: c:\php\php.exe -q %1. (don't forget the %1).
Exit Regedit.
If using PWS on Windows, reboot to reload the registry.
PWS and IIS 3 users now have a fully operational system. IIS 3 users can use a nifty tool from Steven Genusa to configure their script maps.
This section contains notes and hints specific to Apache 1.3.x installs of PHP on Microsoft Windows systems. There are also instructions and notes for Apache 2 on a separate page.
Nota: Please read the manual installation steps first!
There are two ways to set up PHP to work with Apache 1.3.x on Windows. One is to use the CGI binary (php.exe for PHP 4 and php-cgi.exe for PHP 5), the other is to use the Apache Module DLL. In either case you need to edit your httpd.conf to configure Apache to work with PHP, and then restart the server.
It is worth noting here that now the SAPI module has been made more stable under Windows, we recommend it's use above the CGI binary, since it is more transparent and secure.
Although there can be a few variations of configuring PHP under Apache, these are simple enough to be used by the newcomer. Please consult the Apache Documentation for further configuration directives.
After changing the configuration file, remember to restart the server, for example, NET STOP APACHE followed by NET START APACHE, if you run Apache as a Windows Service, or use your regular shortcuts.
Nota: Remember that when adding path values in the Apache configuration files on Windows, all backslashes such as c:\directory\file.ext must be converted to forward slashes, as c:/directory/file.ext.
You should add the following lines to your Apache httpd.conf file:
Esempio 6-3. PHP as an Apache 1.3.x module This assumes PHP is installed to c:\php. Adjust the path if this is not the case. For PHP 4:
For PHP 5:
For both:
|
If you unzipped the PHP package to C:\php\ as described in the Manual Installation Steps section, you need to insert these lines to your Apache configuration file to set up the CGI binary:
Avvertimento |
By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks. |
If you would like to present PHP source files syntax highlighted, there is no such convenient option as with the module version of PHP. If you chose to configure Apache to use PHP as a CGI binary, you will need to use the highlight_file() function. To do this simply create a PHP script file and add this code: <?php highlight_file('some_php_script.php'); ?>.
This section contains notes and hints specific to Apache 2.0.x installs of PHP on Microsoft Windows systems. We also have instructions and notes for Apache 1.3.x users on a separate page.
Nota: You should read the manual installation steps first!
Avvertimento |
We do not recommend using a threaded MPM in production with Apache2. Use the prefork MPM instead, or use Apache1. For information on why, read the following FAQ entry |
You are highly encouraged to take a look at the Apache Documentation to get a basic understanding of the Apache 2.0.x Server. Also consider to read the Windows specific notes for Apache 2.0.x before reading on here.
PHP and Apache 2.0.x compatibility notes: The following versions of PHP are known to work with the most recent version of Apache 2.0.x:
These versions of PHP are compatible to Apache 2.0.40 and later.
- PHP 4.3.0 or later available at http://www.php.net/downloads.php.
- the latest stable development version. Get the source code http://snaps.php.net/php4-latest.tar.gz or download binaries for Windows http://snaps.php.net/win32/php4-win32-latest.zip.
- a prerelease version downloadable from http://qa.php.net/.
- you have always the option to obtain PHP through anonymous CVS.
Apache 2.0 SAPI-support started with PHP 4.2.0. PHP 4.2.3 works with Apache 2.0.39, don't use any other version of Apache with PHP 4.2.3. However, the recommended setup is to use PHP 4.3.0 or later with the most recent version of Apache2.
All mentioned versions of PHP will work still with Apache 1.3.x.
Avvertimento |
Apache 2.0.x is designed to run on Windows NT 4.0, Windows 2000 or Windows XP. At this time, support for Windows 9x is incomplete. Apache 2.0.x is not expected to work on those platforms at this time. |
Download the most recent version of Apache 2.0.x and a fitting PHP version. Follow the Manual Installation Steps and come back to go on with the integration of PHP and Apache.
There are two ways to set up PHP to work with Apache 2.0.x on Windows. One is to use the CGI binary the other is to use the Apache module DLL. In either case you need to edit your httpd.conf to configure Apache to work with PHP and then restart the server.
Nota: Remember that when adding path values in the Apache configuration files on Windows, all backslashes such as c:\directory\file.ext must be converted to forward slashes, as c:/directory/file.ext.
You need to insert these three lines to your Apache httpd.conf configuration file to set up the CGI binary:
Avvertimento |
By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks. |
You need to insert these two lines to your Apache httpd.conf configuration file to set up the PHP module for Apache 2.0:
Esempio 6-6. PHP and Apache 2.0 as Module
|
Nota: Remember to substitute your actual path to PHP for the c:/php/ in the above examples. Take care to use either php4apache2.dll or php5apache2.dll in your LoadModule directive and not php4apache.dll or php5apache.dll as the latter ones are designed to run with Apache 1.3.x.
Nota: If you want to use content negotiation, read related FAQ.
Avvertimento |
Don't mix up your installation with DLL files from different PHP versions. You have the only choice to use the DLL's and extensions that ship with your downloaded PHP version. |
This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Windows.
From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current webservers read the note about subrequests.
To install PHP as a CGI handler, do the following:
Copy php4ts.dll to your systemroot (the directory where you installed Windows)
Make a file association from the command line. Type the following two lines:
assoc .php=PHPScript ftype PHPScript=c:\php\php.exe %1 %* |
In the Netscape Enterprise Administration Server create a dummy shellcgi directory and remove it just after (this step creates 5 important lines in obj.conf and allow the web server to handle shellcgi scripts).
In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/shellcgi, File Suffix:php).
Do it for each web server instance you want PHP to run
More details about setting up PHP as a CGI executable can be found here: http://benoit.noss.free.fr/php/install-php.html
To install PHP with NSAPI, do the following:
Copy php4ts.dll to your systemroot (the directory where you installed Windows)
Make a file association from the command line. Type the following two lines:
assoc .php=PHPScript ftype PHPScript=c:\php\php.exe %1 %* |
In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/x-httpd-php, File Suffix: php).
Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following: You should place the lines after mime types init.
Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="c:/php/sapi/php4nsapi.dll" Init fn="php4_init" LateInit="yes" errorString="Failed to initialise PHP!" [php_ini="c:/path/to/php.ini"] |
Configure the default object in obj.conf (for virtual server classes [Sun Web Server 6.0+] in their vserver.obj.conf): In the <Object name="default"> section, place this line necessarily after all 'ObjectType' and before all 'AddLog' lines:
Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...] |
This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):
<Object name="x-httpd-php"> ObjectType fn="force-type" type="magnus-internal/x-httpd-php" Service fn=php4_execute [inikey=value inikey=value ...] </Object> |
Restart your web service and apply changes
Do it for each web server instance you want PHP to run
Nota: More details about setting up PHP as an NSAPI filter can be found here: http://benoit.noss.free.fr/php/install-php4.html
Nota: The stacksize that PHP uses depends on the configuration of the webserver. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").
Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the webserver itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP 3.x way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running webserver without any valid CGI variables!
Nota: Why are there (invalid) CGI variables in the environment?
Answer: This is because you started the webserver process from the admin server which runs the startup script of the webserver, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started webserver has some CGI environment variables in it. You can test this by starting the webserver not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.
Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):
variables_order = "GPCS" register_globals = On |
You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:
Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...] |
Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:
Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...] |
The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the webserver and insert the result in the webpage. The problem is, that this function uses some undocumented features from the NSAPI library.
Under Unix this is not a problem, because the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.
Under Windows limitations in the DLL handling need the use of a automatic detection of the most recent ns-httpdXX.dll file. This is tested for servers till version 6.1. If a newer version of the Sun server is used, the detection fails and nsapi_virtual() is disabled.
If this is the case, try the following: Add the following parameter to php4_init in magnus.conf/obj.conf:
Init fn=php4_init ... server_lib="ns-httpdXX.dll" |
You can check the status by using the phpinfo() function.
Nota: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!
This section contains notes and hints specific to OmniHTTPd on Windows.
Nota: You should read the manual installation steps first!
Avvertimento |
By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks. |
You need to complete the following steps to make PHP work with OmniHTTPd. This is a CGI executable setup. SAPI is supported by OmniHTTPd, but some tests have shown that it is not so stable to use PHP as an ISAPI module.
Important for CGI users: Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0.
Install OmniHTTPd server.
Right click on the blue OmniHTTPd icon in the system tray and select Properties
Click on Web Server Global Settings
On the 'External' tab, enter: virtual = .php | actual = c:\php\php.exe (use php-cgi.exe if installing PHP 5), and use the Add button.
On the Mime tab, enter: virtual = wwwserver/stdcgi | actual = .php, and use the Add button.
Click OK
Repeat steps 2 - 6 for each extension you want to associate with PHP.
Nota: Some OmniHTTPd packages come with built in PHP support. You can choose at setup time to do a custom setup, and uncheck the PHP component. We recommend you to use the latest PHP binaries. Some OmniHTTPd servers come with PHP 4 beta distributions, so you should choose not to set up the built in support, but install your own. If the server is already on your machine, use the Replace button in Step 4 and 5 to set the new, correct information.
This section contains notes and hints specific to the Sambar Server for Windows.
Nota: You should read the manual installation steps first!
This list describes how to set up the ISAPI module to work with the Sambar server on Windows.
Find the file called mappings.ini (in the config directory) in the Sambar install directory.
Open mappings.ini and add the following line under [ISAPI]:
Now restart the Sambar server for the changes to take effect.
This section contains notes and hints specific to Xitami on Windows.
Nota: You should read the manual installation steps first!
This list describes how to set up the PHP CGI binary to work with Xitami on Windows.
Important for CGI users: Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0. If you want to use $_SERVER['PHP_SELF'] you have to enable the cgi.fix_pathinfo directive.
Avvertimento |
By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks. |
Make sure the webserver is running, and point your browser to xitamis admin console (usually http://127.0.0.1/admin), and click on Configuration.
Navigate to the Filters, and put the extension which PHP should parse (i.e. .php) into the field File extensions (.xxx).
In Filter command or script put the path and name of your PHP CGI executable i.e. C:\php\php.exe for PHP 4, or C:\php\php-cgi.exe for PHP 5.
Press the 'Save' icon.
Restart the server to reflect changes.
This chapter teaches how to compile PHP from sources on windows, using Microsoft's tools. To compile PHP with cygwin, please refer to Capitolo 4.
To compile and build PHP you need a Microsoft Development Environment. Microsoft Visual C++ 6.0 is recommended, although .NET versions (either the free Microsoft Visual C++ Toolkit or the commercial Microsoft Visual C++ .NET) will also work. To extract the downloaded files you will also need a ZIP extraction utility. Windows XP and newer already include this functionality built-in.
Before you get started, you have to download:
the win32 buildtools from the PHP site at http://www.php.net/extra/win32build.zip.
the source code for the DNS name resolver used by PHP from http://www.php.net/extra/bindlib_w32.zip. This is a replacement for the resolv.lib library included in win32build.zip.
If you plan to compile PHP as a Apache module you will also need the Apache sources.
Finally, you are going to need the source to PHP itself. You can get the latest development version using anonymous CVS, a snapshot or the most recent released source tarball.
After downloading the required packages you have to extract them in a proper place:
Create a working directory where all files end up after extracting, e.g: C:\work.
Create the directory win32build under your working directory (C:\work) and unzip win32build.zip into it.
Create the directory bindlib_w32 under your working directory (C:\work) and unzip bindlib_w32.zip into it.
Extract the downloaded PHP source code into your working directory (C:\work).
Build the libraries you are going to need (or download the binaries if available) and place the headers and libs in the C:\work\win32build\include and C:\work\win32build\lib directories, respectively.
+--C:\work | | | +--bindlib_w32 | | | | | +--arpa | | | | | +--conf | | | | | +--... | | | +--php-5.x.x | | | | | +--build | | | | | +--... | | | | | +--win32 | | | | | +--... | | | +--win32build | | | | | +--bin | | | | | +--include | | | | | +--lib |
If you aren't using Cygwin, you must also create the directories C:\usr\local\lib and then copy bison.simple from C:\work\win32build\bin to C:\usr\local\lib.
Nota: If you want to use PEAR and the comfortable command line installer, the CLI-SAPI is mandatory. For more information about PEAR and the installer read the documentation at the PEAR website.
You must build the resolv.lib library. Decide whether you want to have debug symbols available (bindlib - Win32 Debug) or not (bindlib - Win32 Release), but please remember the choice you made, because you'll have to build PHP in the same way, or you may get linking errors. Build the appropriate configuration:
For GUI users, launch VC++, by double-clicking in C:\work\bindlib_w32\bindlib.dsw. Then select Build=>Rebuild All.
For command line users, make sure that you either have the C++ environment variables registered, or have run vcvars.bat, and then execute one of the following commands:
msdev bindlib.dsp /MAKE "bindlib - Win32 Debug"
msdev bindlib.dsp /MAKE "bindlib - Win32 Release"
This chapter explains how to compile PHP >=5 using the new build system, which is CLI-based and very similar with the main PHP's Unix build system.
Nota: This build system isn't available in PHP 4. Please refer to la Sezione Building PHP using DSW files [PHP 4] instead.
Before starting, be sure you have read la Sezione Putting it all together and you have built all needed libraries, like Libxml or ICU (needed for PHP >= 6).
First you should open a Visual Studio Command Prompt, which should be available under the Start menu. A regular Command Prompt window shouldn't work, as probably it doesn't have the necessary environment variables set. Then type something like cd C:\work\php-5.x.x to enter in the PHP source dir. Now you are ready to start configuring PHP.
The second step is running the buildconf batch file to make the configure script, by scanning the folder for config.w32 files. By default this command will also search in the following directories: pecl; ..\pecl; pecl\rpc; ..\pecl\rpc. Since PHP 5.1.0, you can change this behaviour by using the --add-modules-dir argument (e.g. cscript /nologo win32/build/buildconf.js --add-modules-dir=../php-gtk2 --add-modules-dir=../pecl).
The third step is configuring. To view the list of the available configuration options type cscript /nologo configure.js --help. After choosing the options that you will enable/disable, type something like: cscript /nologo configure.js --disable-foo --enable-fun-ext. Using --enable-foo=shared will attempt to build the 'foo' extension as a shared, dynamically loadable module.
The last step is compilling. To achieve this just issue the command nmake. The generated files (e.g. .exe and .dll) will be placed in either Release_TS or Debug_TS directories (if built with Thread safety), or in the Release or Debug directories otherwise.
Optionally you may also run PHP's test suite, by typing nmake test. If you want to run just a specific test, you may use the 'TESTS' variable (e.g. nmake /D TESTS=ext/sqlite/tests test - will only run sqlite's tests). To delete the files that were created during the compilation, you can use the nmake clean command.
A very usefull configure option to build snapshots is --enable-snapshot-build, which add a new compiling mode (nmake build-snap). This tries to build every extension available (as shared, by default), but it will ignore build errors in individual extensions or SAPI.
Compiling PHP using the DSW files isn't supported as of PHP 5, as a much more flexible system was made available. Anyway, you can still use them, but keep in mind that they are not maintained very often, so you can have compiling problems. To compile PHP 4 for windows, this is the only available way though.
The first step is to configure MVC++ to prepare for compiling. Launch Microsoft Visual C++, and from the menu select Tools => Options. In the dialog, select the directories tab. Sequentially change the dropdown to Executables, Includes, and Library files. Your entries should look like this:
Executable files: C:\work\win32build\bin, Cygwin users: C:\cygwin\bin
Include files: C:\work\win32build\include
Library files: C:\work\win32build\lib
The best way to get started is to build the CGI version:
For GUI users, launch VC++, and then select File => Open Workspace and select C:\work\php-4.x.x\win32\php4ts.dsw. Then select Build=>Set Active Configuration and select the desired configuration, either php4ts - Win32 Debug_TS or php4ts - Win32 Release_TS. Finally select Build=>Rebuild All.
For command line users, make sure that you either have the C++ environment variables registered, or have run vcvars.bat, and then execute one of the following commands from the C:\work\php-4.x.x\win32 directory:
msdev php4ts.dsp /MAKE "php4ts - Win32 Debug_TS"
msdev php4ts.dsp /MAKE "php4ts - Win32 Release_TS"
At this point, you should have a usable php.exe in either your C:\work\php-4.x.x\Debug_TS or Release_TS subdirectories.
It is possible to do minor customization to the build process by editing the main/config.win32.h file. For example you can change the default location of php.ini, the built-in extensions, and the default location for your extensions.
Next you may want to build the CLI version which is designed to use PHP from the command line. The steps are the same as for building the CGI version, except you have to select the php4ts_cli - Win32 Debug_TS or php4ts_cli - Win32 Release_TS project file. After a successful compiling run you will find the php.exe in either the directory Release_TS\cli\ or Debug_TS\cli\.
In order to build the SAPI module (php4isapi.dll) for integrating PHP with Microsoft IIS, set your active configuration to php4isapi-whatever-config and build the desired dll.
After installing PHP and a webserver on Windows, you will probably want to install some extensions for added functionality. You can choose which extensions you would like to load when PHP starts by modifying your php.ini. You can also load a module dynamically in your script using dl().
The DLLs for PHP extensions are prefixed with php_.
Many extensions are built into the Windows version of PHP. This means additional DLL files, and the extension directive, are not used to load these extensions. The Windows PHP Extensions table lists extensions that require, or used to require, additional PHP DLL files. Here's a list of built in extensions:
In PHP 4 (updated PHP 4.3.11): BCMath, Caledar, COM, Ctype, FTP, MySQL, ODBC, Overload, PCRE, Session, Tokenizer, WDDX, XML e Zlib
In PHP 5 (updated PHP 5.0.4), the following changes exist. Built in: DOM, LibXML, Iconv, SimpleXML, SPL e SQLite. And the following are no longer built in: MySQL and Overload.
The default location PHP searches for extensions is C:\php4\extensions in PHP 4 and C:\php5 in PHP 5. To change this setting to reflect your setup of PHP edit your php.ini file:
You will need to change the extension_dir setting to point to the directory where your extensions lives, or where you have placed your php_*.dll files. For example:
Enable the extension(s) in php.ini you want to use by uncommenting the extension=php_*.dll lines in php.ini. This is done by deleting the leading ; from the extension you want to load.
Esempio 6-8. Enable Bzip2 extension for PHP-Windows
|
Some of the extensions need extra DLLs to work. Couple of them can be found in the distribution package, in the C:\php\dlls\ folder in PHP 4 or in the main folder in PHP 5, but some, for example Oracle (php_oci8.dll) require DLLs which are not bundled with the distribution package. If you are installing PHP 4, copy the bundled DLLs from C:\php\dlls folder to the main C:\php folder. Don't forget to include C:\php in the system PATH (this process is explained in a separate FAQ entry).
Some of these DLLs are not bundled with the PHP distribution. See each extensions documentation page for details. Also, read the manual section titled Installation of PECL extensions for details on PECL. An increasingly large number of PHP extensions are found in PECL, and these extensions require a separate download.
Nota: If you are running a server module version of PHP remember to restart your webserver to reflect your changes to php.ini.
The following table describes some of the extensions available and required additional dlls.
Tabella 6-1. PHP Extensions
Extension | Description | Notes |
---|---|---|
php_bz2.dll | bzip2 compression functions | None |
php_calendar.dll | Calendar conversion functions | Built in since PHP 4.0.3 |
php_cpdf.dll | ClibPDF functions | None |
php_crack.dll | Crack functions | None |
php_ctype.dll | ctype family functions | Built in since PHP 4.3.0 |
php_curl.dll | CURL, Client URL library functions | Requires: libeay32.dll, ssleay32.dll (bundled) |
php_cybercash.dll | Cybercash payment functions | PHP <= 4.2.0 |
php_db.dll | DBM functions | Deprecated. Use DBA instead (php_dba.dll) |
php_dba.dll | DBA: DataBase (dbm-style) Abstraction layer functions | None |
php_dbase.dll | dBase functions | None |
php_dbx.dll | dbx functions | |
php_domxml.dll | DOM XML functions | PHP <= 4.2.0 requires: libxml2.dll (bundled) PHP >= 4.3.0 requires: iconv.dll (bundled) |
php_dotnet.dll | .NET functions | PHP <= 4.1.1 |
php_exif.dll | EXIF functions | php_mbstring.dll. And, php_exif.dll must be loaded after php_mbstring.dll in php.ini. |
php_fbsql.dll | FrontBase functions | PHP <= 4.2.0 |
php_fdf.dll | FDF: Forms Data Format functions. | Requires: fdftk.dll (bundled) |
php_filepro.dll | filePro functions | Read-only access |
php_ftp.dll | FTP functions | Built-in since PHP 4.0.3 |
php_gd.dll | GD library image functions | Removed in PHP 4.3.2. Also note that truecolor functions are not available in GD1, instead, use php_gd2.dll. |
php_gd2.dll | GD library image functions | GD2 |
php_gettext.dll | Gettext functions | PHP <= 4.2.0 requires gnu_gettext.dll (bundled), PHP >= 4.2.3 requires libintl-1.dll, iconv.dll (bundled). |
php_hyperwave.dll | HyperWave functions | None |
php_iconv.dll | ICONV characterset conversion | Requires: iconv-1.3.dll (bundled), PHP >=4.2.1 iconv.dll |
php_ifx.dll | Informix functions | Requires: Informix libraries |
php_iisfunc.dll | IIS management functions | None |
php_imap.dll | IMAP POP3 and NNTP functions | None |
php_ingres.dll | Ingres II functions | Requires: Ingres II libraries |
php_interbase.dll | InterBase functions | Requires: gds32.dll (bundled) |
php_java.dll | Java functions | PHP <= 4.0.6 requires: jvm.dll (bundled) |
php_ldap.dll | LDAP functions | PHP <= 4.2.0 requires libsasl.dll (bundled), PHP >= 4.3.0 requires libeay32.dll, ssleay32.dll (bundled) |
php_mbstring.dll | Multi-Byte String functions | None |
php_mcrypt.dll | Mcrypt Encryption functions | Requires: libmcrypt.dll |
php_mhash.dll | Mhash functions | PHP >= 4.3.0 requires: libmhash.dll (bundled) |
php_mime_magic.dll | Mimetype functions | Requires: magic.mime (bundled) |
php_ming.dll | Ming functions for Flash | None |
php_msql.dll | mSQL functions | Requires: msql.dll (bundled) |
php_mssql.dll | MSSQL functions | Requires: ntwdblib.dll (bundled) |
php_mysql.dll | MySQL functions | PHP >= 5.0.0, requires libmysql.dll (bundled) |
php_mysqli.dll | MySQLi functions | PHP >= 5.0.0, requires libmysql.dll (libmysqli.dll in PHP <= 5.0.2) (bundled) |
php_oci8.dll | Oracle 8 functions | Requires: Oracle 8.1+ client libraries |
php_openssl.dll | OpenSSL functions | Requires: libeay32.dll (bundled) |
php_oracle.dll | Oracle functions | Requires: Oracle 7 client libraries |
php_overload.dll | Object overloading functions | Built in since PHP 4.3.0 |
php_pdf.dll | PDF functions | None |
php_pgsql.dll | PostgreSQL functions | None |
php_printer.dll | Printer functions | None |
php_shmop.dll | Shared Memory functions | None |
php_snmp.dll | SNMP get and walk functions | NT only! |
php_soap.dll | SOAP functions | PHP >= 5.0.0 |
php_sockets.dll | Socket functions | None |
php_sybase_ct.dll | Sybase functions | Requires: Sybase client libraries |
php_tidy.dll | Tidy functions | PHP >= 5.0.0 |
php_tokenizer.dll | Tokenizer functions | Built in since PHP 4.3.0 |
php_w32api.dll | W32api functions | None |
php_xmlrpc.dll | XML-RPC functions | PHP >= 4.2.1 requires: iconv.dll (bundled) |
php_xslt.dll | XSLT functions | PHP <= 4.2.0 requires sablot.dll, expat.dll (bundled). PHP >= 4.2.1 requires sablot.dll, expat.dll, iconv.dll (bundled). |
php_yaz.dll | YAZ functions | Requires: yaz.dll (bundled) |
php_zip.dll | Zip File functions | Read only access |
php_zlib.dll | ZLib compression functions | Built in since PHP 4.3.0 |
PECL is a repository of PHP extensions that are made available to you via the PEAR packaging system. This section of the manual is intended to demonstrate how to obtain and install PECL extensions.
These instructions assume /your/phpsrcdir/ is the path to the PHP source distribution, and that extname is the name of the PECL extension. Adjust accordingly. These instructions also assume a familiarity with the pear command.
To be useful, a shared extension must be built, installed, and loaded. The methods described below provide you with various instructions on how to build and install the extensions, but they do not automatically load them. Extensions can be loaded by adding an extension directive. To this php.ini file, or through the use of the dl() function.
When building PHP modules, it's important to have known-good versions of the required tools (autoconf, automake, libtool, etc.) See the Anonymous CVS Instructions for details on the required tools, and required versions.
There are several options for downloading PECL extensions, such as:
The PECL web site contains information about the different extensions that are offered by the PHP Development Team. The information available here includes: ChangeLog, release notes, requirements and other similar details.
pear download extname
PECL extensions that have releases listed on the PECL web site are available for download and installation using the pear command. Specific revisions may also be specified.
CVS
Most PECL extensions also reside in CVS. A web-based view may be seen at http://cvs.php.net/pecl/. To download straight from CVS, the following sequence of commands may be used. Note that phpfi is the password for user cvsread:
$ cvs -d:pserver:cvsread@cvs.php.net:/repository login $ cvs -d:pserver:cvsread@cvs.php.net:/repository co pecl/extname |
Windows downloads
Windows users may find compiled PECL binaries by downloading the Collection of PECL modules from the PHP Downloads page, and by retrieving a PECL Snapshot. To compile PHP under Windows, read the Win32 Build README.
As with any other PHP extension DLL, installation is as simple as copying the PECL extension DLLs into the extension_dir folder and loading them from php.ini. For example, add the following line to your php.ini:
extension=php_extname.dll |
After doing this, restart the web server.
PEAR makes it easy to create shared PHP extensions. Using the pear command, do the following:
$ pear install extname |
This will download the source for extname, compile, and install extname.so into your extension_dir. extname.so may then be loaded via php.ini
By default, the pear command will not install packages that are marked with the alpha or beta state. If no stable packages are available, you may install a beta package using the following command:
$ pear install extname-beta |
You may also install a specific version using this variant:
$ pear install extname-0.1 |
Sometimes, using the pear installer is not an option. This could be because you're behind a firewall, or it could be because the extension you want to install is not available as a PEAR compatible package, such as unreleased extensions from CVS. If you need to build such an extension, you can use the lower-level build tools to perform the build manually.
The phpize command is used to prepare the build environment for a PHP extension. In the following sample, the sources for an extension are in a directory named extname:
$ cd extname $ phpize $ ./configure $ make # make install |
A successful install will have created extname.so and put it into the PHP extensions directory. You'll need to and adjust php.ini and add an extension=extname.so line before you can use the extension.
You might find that you need to build a PECL extension statically into your PHP binary. To do this, you'll need to place the extension source under the php-src/ext/ directory and tell the PHP build system to regenerate its configure script.
$ cd /your/phpsrcdir/ext $ pear download extname $ gzip -d < extname.tgz | tar -xvf - $ mv extname-x.x.x extname |
This will result in the following directory:
/your/phpsrcdir/ext/extname |
From here, force PHP to rebuild the configure script, and then build PHP as normal:
$ cd /your/phpsrcdir $ rm configure $ ./buildconf --force $ ./configure --help $ ./configure --with-extname --enable-someotherext --with-foobar $ make $ make install |
Nota: To run the 'buildconf' script you need autoconf 2.13 and automake 1.4+ (newer versions of autoconf may work, but are not supported).
Whether --enable-extname or --with-extname is used depends on the extension. Typically an extension that does not require external libraries uses --enable. To be sure, run the following after buildconf:
$ ./configure --help | grep extname |
Some problems are more common than others. The most common ones are listed in the PHP FAQ, part of this manual.
If you are still stuck, someone on the PHP installation mailing list may be able to help you. You should check out the archive first, in case someone already answered someone else who had the same problem as you. The archives are available from the support page on http://www.php.net/support.php. To subscribe to the PHP installation mailing list, send an empty mail to php-install-subscribe@lists.php.net. The mailing list address is php-install@lists.php.net.
If you want to get help on the mailing list, please try to be precise and give the necessary details about your environment (which operating system, what PHP version, what web server, if you are running PHP as CGI or a server module, modalità sicura, etc...), and preferably enough code to make others able to reproduce and test your problem.
If you think you have found a bug in PHP, please report it. The PHP developers probably don't know about it, and unless you report it, chances are it won't be fixed. You can report bugs using the bug-tracking system at http://bugs.php.net/. Please do not send bug reports in mailing list or personal letters. The bug system is also suitable to submit feature requests.
Read the How to report a bug document before submitting any bug reports!
The configuration file (called php3.ini in PHP 3, and simply php.ini as of PHP 4) is read when PHP starts up. For the server module versions of PHP, this happens only once when the web server is started. For the CGI and CLI version, it happens on every invocation.
php.ini is searched in these locations (in order):
SAPI module specific location (PHPIniDir directive in Apache 2, -c command line option in CGI and CLI, php_ini parameter in NSAPI, PHP_INI_PATH environment variable in THTTPD)
HKEY_LOCAL_MACHINE\SOFTWARE\PHP\IniFilePath (Windows Registry location)
The PHPRC environment variable
Current working directory (for CLI)
The web server's directory (for SAPI modules), or directory of PHP (otherwise in Windows)
Windows directory (C:\windows or C:\winnt) (for Windows), or --with-config-file-path compile time option
If php-SAPI.ini exists (where SAPI is used SAPI, so the filename is e.g. php-cli.ini or php-apache.ini), it's used instead of php.ini. SAPI name can be determined by php_sapi_name().
Nota: The Apache web server changes the directory to root at startup causing PHP to attempt to read php.ini from the root filesystem if it exists.
The php.ini directives handled by extensions are documented respectively on the pages of the extensions themselves. The list of the core directives is available in the appendix. Probably not all PHP directives are documented in the manual though. For a complete list of directives available in your PHP version, please read your well commented php.ini file. Alternatively, you may find the the latest php.ini from CVS helpful too.
Esempio 9-1. php.ini example
|
Since PHP 5.1.0, it is possible to refer to existing .ini variables from within .ini files. Example: open_basedir = ${open_basedir} ":/new/dir".
When using PHP as an Apache module, you can also change the configuration settings using directives in Apache configuration files (e.g. httpd.conf) and .htaccess files. You will need "AllowOverride Options" or "AllowOverride All" privileges to do so.
With PHP 4 and PHP 5, there are several Apache directives that allow you to change the PHP configuration from within the Apache configuration files. For a listing of which directives are PHP_INI_ALL, PHP_INI_PERDIR, or PHP_INI_SYSTEM, have a look at the List of php.ini directives appendix.
Nota: With PHP 3, there are Apache directives that correspond to each configuration setting in the php3.ini name, except the name is prefixed by "php3_".
Sets the value of the specified directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives. To clear a previously set value use none as the value.
Nota: Don't use php_value to set boolean values. php_flag (see below) should be used instead.
Used to set a boolean configuration directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives.
Sets the value of the specified directive. This can not be used in .htaccess files. Any directive type set with php_admin_value can not be overridden by .htaccess or virtualhost directives. To clear a previously set value use none as the value.
Used to set a boolean configuration directive. This can not be used in .htaccess files. Any directive type set with php_admin_flag can not be overridden by .htaccess or virtualhost directives.
Esempio 9-2. Apache configuration example
|
Attenzione |
PHP constants do not exist outside of PHP. For example, in httpd.conf you can not use PHP constants such as E_ALL or E_NOTICE to set the error_reporting directive as they will have no meaning and will evaluate to 0. Use the associated bitmask values instead. These constants can be used in php.ini |
When running PHP on Windows, the configuration values can be modified on a per-directory basis using the Windows registry. The configuration values are stored in the registry key HKLM\SOFTWARE\PHP\Per Directory Values, in the sub-keys corresponding to the path names. For example, configuration values for the directory c:\inetpub\wwwroot would be stored in the key HKLM\SOFTWARE\PHP\Per Directory Values\c\inetpub\wwwroot. The settings for the directory would be active for any script running from this directory or any subdirectory of it. The values under the key should have the name of the PHP configuration directive and the string value. PHP constants in the values are not parsed. However, only configuration values changeable in PHP_INI_USER can be set this way, PHP_INI_PERDIR values can not.
Regardless of how you run PHP, you can change certain values at runtime of your scripts through ini_set(). See the documentation on the ini_set() page for more information.
If you are interested in a complete list of configuration settings on your system with their current values, you can execute the phpinfo() function, and review the resulting page. You can also access the values of individual configuration directives at runtime using ini_get() or get_cfg_var().
Quando il PHP inizia a esaminare un file, cerca i tag di apertura e di chiusura, che indicano dove iniziare e terminare l'interpretazione del codice. Questa tecnica permette al PHP di essere incorporato in tutte le tipologie di documenti, poichè ogni cosa esterna ai tag di apertura e di chiusura viene ignoarat dal parser PHP. Il più delle volte si vedrà codice PHP racchiuso in documenti HTML, come nel seguente esempio.
<p>This is going to be ignored.</p> <?php echo 'While this is going to be parsed.'; ?> <p>This will also be ignored.</p> |
Si possono usare anche strutture più avanzate:
Esistono 4 set di tag che possono essere utilizzati per delimitare blocchi di codice PHP. Soltanto due di questi (<?php. . .?> e <script language="php">. . .</script>) sono sempre disponibili. Gli altri due sono i tag brevi e i tag stile ASP e possono essere attivati o disattivati tramite il file di configurazione php.ini. Sebbene i tag brevi o quelli in stile ASP possano essere pratici, questi sono meno portabili e, in generale, sconsigliati.
Nota: Occorre notare che se si intende inserire codice PHP all'interno di testi XMl o XHTML, occorre utilizzare <?php ?> per essere conformi allo standard XML.
Esempio 10-2. Tag di apertura e di chiusura
|
Sebbene i tag utilizzati negli esempi 1 e 2 siano sempre disponibili, l'esempio uno rappresenta la situazione più comunemente utilizzata, e la più raccomandata dei due.
I tag brevi (esempio tre) sono disponibili soltanto se sono stati abilitati tramite il parametro short_open_tag del php.ini, oppure se il PHP è stato configurato con --enable-short-tags.
Nota: Se si utilizza il PHP 3 si può anche avere disponibili i tag brevi tramite la funzione short_tags(). Questo vale solo per il PHP 3!
I tag in stile ASP (esempio quattro) sono disponibili soltanto quando sono abilitati tramite il parametro asp_tags del php.ini
Nota: Il supporto per i tag nello stile ASP è stato aggiunto nella versione 3.0.4.
Nota: L'utilizzo dei tag brevi dovrebbe essere evitato nello sviluppo di applicazioni o librerie destinate alla distribuzione o destinati a server di produzione PHP di cui non si ha il controllo poichè questi tag potrebbero non essere attivi sul server di destinazione. Per avere maggiore portabilità, codice redistribuibile, occorre essere certi di non utilizzare i tag brevi.
Come in C od in Perl, il PHP richiede che le istruzioni siano chiuse dal punto e virgola al termine di ogni istruzione. I tag di chiusura di un blocco di codice PHP implicano in automatico il punto e virgola; non occorre, pertanto, inserire il punto e virgola per chiudere l'ultima riga di un blocco PHP. Il tag di chiusura del blocco include il newline immediatamente seguente, se presente.
Il PHP supporta i commenti dei linguaggi 'C', 'C++' e stile shell (stile Perl) di Unix. Per esempio:
<?php echo 'Questo ` un test'; // Questo è un commento su una linea nella stile c++ /* Questo è un commento su più linee ancora un'altra linea di commento */ echo 'Questo è un altro test'; echo 'Un ultimo test'; # Questo è un commento stile shell Unix ?> |
Lo stile di commento su "una linea", attualmente commenta solo fino alla fine della linea o del blocco corrente di codice PHP. Questo significa che l'eventuale codice HTML posto dopo // ?> sarà stampato: ?> esce dalla modalità PHP e ritorna in modalità HTML, e quindi // non può influenzare quest'ultima. Se l'impostazione asp_tags è abilitata, il PHP si comporta allo stesso modo con // %>. Tuttavia il tag </script> non esce dalla modalità PHP nei commenti di una linea.
<h1>Questo è un <?# echo 'semplice';?> esempio.</h1> <p>L'intestazione qui sopra dirà 'Questo è un esempio'.</p> |
I commenti in stile C terminano alla prima occorrenza di */. Occorre fare attenzione nel non annidare i commenti di stile C, situazione che si presenta quando si commentano larghi blocchi di codice.
PHP supports eight primitive types.
Four scalar types:
Two compound types: And finally two special types: This manual also introduces some pseudo-types for readability reasons: You may also find some references to the type "double". Consider double the same as float, the two names exist only for historic reasons.The type of a variable is usually not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used.
Nota: If you want to check out the type and value of a certain expression, use var_dump().
Nota: If you simply want a human-readable representation of the type for debugging, use gettype(). To check for a certain type, do not use gettype(), but use the is_type functions. Some examples:
<?php $bool = TRUE; // a boolean $str = "foo"; // a string $int = 12; // an integer echo gettype($bool); // prints out "boolean" echo gettype($str); // prints out "string" // If this is an integer, increment it by four if (is_int($int)) { $int += 4; } // If $bool is a string, print it out // (does not print out anything) if (is_string($bool)) { echo "String: $bool"; } ?>
If you would like to force a variable to be converted to a certain type, you may either cast the variable or use the settype() function on it.
Note that a variable may be evaluated with different values in certain situations, depending on what type it is at the time. For more information, see the section on Type Juggling. Also, you may be interested in viewing the type comparison tables, as they show examples of various type related comparisons.
This is the easiest type. A boolean expresses a truth value. It can be either TRUE or FALSE.
Nota: The boolean type was introduced in PHP 4.
To specify a boolean literal, use either the keyword TRUE or FALSE. Both are case-insensitive.
Usually you use some kind of operator which returns a boolean value, and then pass it on to a control structure.
To explicitly convert a value to boolean, use either the (bool) or the (boolean) cast. However, in most cases you do not need to use the cast, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
See also Type Juggling.
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
Avvertimento |
-1 is considered TRUE, like any other non-zero (whether negative or positive) number! |
<?php var_dump((bool) ""); // bool(false) var_dump((bool) 1); // bool(true) var_dump((bool) -2); // bool(true) var_dump((bool) "foo"); // bool(true) var_dump((bool) 2.3e5); // bool(true) var_dump((bool) array(12)); // bool(true) var_dump((bool) array()); // bool(false) var_dump((bool) "false"); // bool(true) ?> |
An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.
See also: Arbitrary length integer / GMP, Floating point numbers, and Arbitrary precision / BCMath
Integers can be specified in decimal (10-based), hexadecimal (16-based) or octal (8-based) notation, optionally preceded by a sign (- or +).
If you use the octal notation, you must precede the number with a 0 (zero), to use hexadecimal notation precede the number with 0x.
If you specify a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, if you perform an operation that results in a number beyond the bounds of the integer type, a float will be returned instead.
<?php $large_number = 2147483647; var_dump($large_number); // output: int(2147483647) $large_number = 2147483648; var_dump($large_number); // output: float(2147483648) // this doesn't go for hexadecimal specified integers: var_dump( 0x100000000 ); // output: int(2147483647) $million = 1000000; $large_number = 50000 * $million; var_dump($large_number); // output: float(50000000000) ?> |
Avvertimento |
Unfortunately, there was a bug in PHP so that this does not always work correctly when there are negative numbers involved. For example: when you do -50000 * $million, the result will be -429496728. However, when both operands are positive there is no problem. This is solved in PHP 4.1.0. |
There is no integer division operator in PHP. 1/2 yields the float 0.5. You can cast the value to an integer to always round it downwards, or you can use the round() function.
To explicitly convert a value to integer, use either the (int) or the (integer) cast. However, in most cases you do not need to use the cast, since a value will be automatically converted if an operator, function or control structure requires an integer argument. You can also convert a value to integer with the function intval().
See also type-juggling.
When converting from float to integer, the number will be rounded towards zero.
If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31), the result is undefined, since the float hasn't got enough precision to give an exact integer result. No warning, not even a notice will be issued in this case!
Avvertimento |
Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results. See for more information the warning about float-precision. |
Attenzione |
Behaviour of converting to integer is undefined for other types. Currently, the behaviour is the same as if the value was first converted to boolean. However, do not rely on this behaviour, as it can change without notice. |
Floating point numbers (AKA "floats", "doubles" or "real numbers") can be specified using any of the following syntaxes:
Formally:LNUM [0-9]+ DNUM ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*) EXPONENT_DNUM ( ({LNUM} | {DNUM}) [eE][+-]? {LNUM}) |
Floating point precision |
It is quite usual that simple decimal fractions like 0.1 or 0.7 cannot be converted into their internal binary counterparts without a little loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8 as the result of the internal representation really being something like 7.9999999999.... This is related to the fact that it is impossible to exactly express some fractions in decimal notation with a finite number of digits. For instance, 1/3 in decimal form becomes 0.3333333. . .. So never trust floating number results to the last digit and never compare floating point numbers for equality. If you really need higher precision, you should use the arbitrary precision math functions or gmp functions instead. |
For information on when and how strings are converted to floats, see the section titled String conversion to numbers. For values of other types, the conversion is the same as if the value would have been converted to integer and then to float. See the Converting to integer section for more information. As of PHP 5, notice is thrown if you try to convert object to float.
A string is series of characters. In PHP, a character is the same as a byte, that is, there are exactly 256 different characters possible. This also implies that PHP has no native support of Unicode. See utf8_encode() and utf8_decode() for some Unicode support.
Nota: It is no problem for a string to become very large. There is no practical bound to the size of strings imposed by PHP, so there is no reason at all to worry about long strings.
A string literal can be specified in three different ways.
The easiest way to specify a simple string is to enclose it in single quotes (the character ').
To specify a literal single quote, you will need to escape it with a backslash (\), like in many other languages. If a backslash needs to occur before a single quote or at the end of the string, you need to double it. Note that if you try to escape any other character, the backslash will also be printed! So usually there is no need to escape the backslash itself.
Nota: In PHP 3, a warning will be issued at the E_NOTICE level when this happens.
Nota: Unlike the two other syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
<?php echo 'this is a simple string'; echo 'You can also have embedded newlines in strings this way as it is okay to do'; // Outputs: Arnold once said: "I'll be back" echo 'Arnold once said: "I\'ll be back"'; // Outputs: You deleted C:\*.*? echo 'You deleted C:\\*.*?'; // Outputs: You deleted C:\*.*? echo 'You deleted C:\*.*?'; // Outputs: This will not expand: \n a newline echo 'This will not expand: \n a newline'; // Outputs: Variables do not $expand $either echo 'Variables do not $expand $either'; ?> |
If the string is enclosed in double-quotes ("), PHP understands more escape sequences for special characters:
Tabella 11-1. Escaped characters
sequence | meaning |
---|---|
\n | linefeed (LF or 0x0A (10) in ASCII) |
\r | carriage return (CR or 0x0D (13) in ASCII) |
\t | horizontal tab (HT or 0x09 (9) in ASCII) |
\\ | backslash |
\$ | dollar sign |
\" | double-quote |
\[0-7]{1,3} | the sequence of characters matching the regular expression is a character in octal notation |
\x[0-9A-Fa-f]{1,2} | the sequence of characters matching the regular expression is a character in hexadecimal notation |
Again, if you try to escape any other character, the backslash will be printed too!
But the most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.
Another way to delimit strings is by using heredoc syntax ("<<<"). One should provide an identifier after <<<, then the string, and then the same identifier to close the quotation.
The closing identifier must begin in the first column of the line. Also, the identifier used must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.
Avvertimento | |
It is very important to note that the line with the closing identifier contains no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs after or before the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by your operating system. This is \r on Macintosh for example. If this rule is broken and the closing identifier is not "clean" then it's not considered to be a closing identifier and PHP will continue looking for one. If in this case a proper closing identifier is not found then a parse error will result with the line number being at the end of the script. It is not allowed to use heredoc syntax in initializing class members. Use other string syntaxes instead. |
Heredoc text behaves just like a double-quoted string, without the double-quotes. This means that you do not need to escape quotes in your here docs, but you can still use the escape codes listed above. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.
Esempio 11-4. Heredoc string quoting example
|
Nota: Heredoc support was added in PHP 4.
When a string is specified in double quotes or with heredoc, variables are parsed within it.
There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to parse a variable, an array value, or an object property.
The complex syntax was introduced in PHP 4, and can be recognised by the curly braces surrounding the expression.
If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces if you want to explicitly specify the end of the name.
<?php $beer = 'Heineken'; echo "$beer's taste is great"; // works, "'" is an invalid character for varnames echo "He drank some $beers"; // won't work, 's' is a valid character for varnames echo "He drank some ${beer}s"; // works echo "He drank some {$beer}s"; // works ?> |
Similarly, you can also have an array index or an object property parsed. With array indices, the closing square bracket (]) marks the end of the index. For object properties the same rules apply as to simple variables, though with object properties there doesn't exist a trick like the one with variables.
<?php // These examples are specific to using arrays inside of strings. // When outside of a string, always quote your array string keys // and do not use {braces} when outside of strings either. // Let's show all errors error_reporting(E_ALL); $fruits = array('strawberry' => 'red', 'banana' => 'yellow'); // Works but note that this works differently outside string-quotes echo "A banana is $fruits[banana]."; // Works echo "A banana is {$fruits['banana']}."; // Works but PHP looks for a constant named banana first // as described below. echo "A banana is {$fruits[banana]}."; // Won't work, use braces. This results in a parse error. echo "A banana is $fruits['banana']."; // Works echo "A banana is " . $fruits['banana'] . "."; // Works echo "This square is $square->width meters broad."; // Won't work. For a solution, see the complex syntax. echo "This square is $square->width00 centimeters broad."; ?> |
For anything more complex, you should use the complex syntax.
This isn't called complex because the syntax is complex, but because you can include complex expressions this way.
In fact, you can include any value that is in the namespace in strings with this syntax. You simply write the expression the same way as you would outside the string, and then include it in { and }. Since you can't escape '{', this syntax will only be recognised when the $ is immediately following the {. (Use "{\$" or "\{$" to get a literal "{$"). Some examples to make it clear:
<?php // Let's show all errors error_reporting(E_ALL); $great = 'fantastic'; // Won't work, outputs: This is { fantastic} echo "This is { $great}"; // Works, outputs: This is fantastic echo "This is {$great}"; echo "This is ${great}"; // Works echo "This square is {$square->width}00 centimeters broad."; // Works echo "This works: {$arr[4][3]}"; // This is wrong for the same reason as $foo[bar] is wrong // outside a string. In other words, it will still work but // because PHP first looks for a constant named foo, it will // throw an error of level E_NOTICE (undefined constant). echo "This is wrong: {$arr[foo][3]}"; // Works. When using multi-dimensional arrays, always use // braces around arrays when inside of strings echo "This works: {$arr['foo'][3]}"; // Works. echo "This works: " . $arr['foo'][3]; echo "You can even write {$obj->values[3]->name}"; echo "This is the value of the var named $name: {${$name}}"; ?> |
Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string in curly braces.
Nota: For backwards compatibility, you can still use array-brackets for the same purpose. However, this syntax is deprecated as of PHP 4.
Esempio 11-5. Some string examples
|
Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. Please see String operators for more information.
There are a lot of useful functions for string modification.
See the string functions section for general functions, the regular expression functions for advanced find&replacing (in two tastes: Perl and POSIX extended).
There are also functions for URL-strings, and functions to encrypt/decrypt strings (mcrypt and mhash).
Finally, if you still didn't find what you're looking for, see also the character type functions.
You can convert a value to a string using the (string) cast, or the strval() function. String conversion is automatically done in the scope of an expression for you where a string is needed. This happens when you use the echo() or print() functions, or when you compare a variable value to a string. Reading the manual sections on Types and Type Juggling will make the following clearer. See also settype().
A boolean TRUE value is converted to the string "1", the FALSE value is represented as "" (empty string). This way you can convert back and forth between boolean and string values.
An integer or a floating point number (float) is converted to a string representing the number with its digits (including the exponent part for floating point numbers).
Arrays are always converted to the string "Array", so you cannot dump out the contents of an array with echo() or print() to see what is inside them. To view one element, you'd do something like echo $arr['foo']. See below for tips on dumping/viewing the entire contents.
Objects are always converted to the string "Object". If you would like to print out the member variable values of an object for debugging reasons, read the paragraphs below. If you would like to find out the class name of which an object is an instance of, use get_class(). As of PHP 5, __toString() method is used if applicable.
Resources are always converted to strings with the structure "Resource id #1" where 1 is the unique number of the resource assigned by PHP during runtime. If you would like to get the type of the resource, use get_resource_type().
NULL is always converted to an empty string.
As you can see above, printing out the arrays, objects or resources does not provide you any useful information about the values themselves. Look at the functions print_r() and var_dump() for better ways to print out values for debugging.
You can also convert PHP values to strings to store them permanently. This method is called serialization, and can be done with the function serialize(). You can also serialize PHP values to XML structures, if you have WDDX support in your PHP setup.
When a string is evaluated as a numeric value, the resulting value and type are determined as follows.
The string will evaluate as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will evaluate as an integer.
The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.
<?php $foo = 1 + "10.5"; // $foo is float (11.5) $foo = 1 + "-1.3e3"; // $foo is float (-1299) $foo = 1 + "bob-1.3e3"; // $foo is integer (1) $foo = 1 + "bob3"; // $foo is integer (1) $foo = 1 + "10 Small Pigs"; // $foo is integer (11) $foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2) $foo = "10.0 pigs " + 1; // $foo is float (11) $foo = "10.0 pigs " + 1.0; // $foo is float (11) ?> |
For more information on this conversion, see the Unix manual page for strtod(3).
If you would like to test any of the examples in this section, you can cut and paste the examples and insert the following line to see for yourself what's going on:
Do not expect to get the code of one character by converting it to integer (as you would do in C for example). Use the functions ord() and chr() to convert between charcodes and characters.
An array in PHP is actually an ordered map. A map is a type that maps values to keys. This type is optimized in several ways, so you can use it as a real array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. Because you can have another PHP array as a value, you can also quite easily simulate trees.
Explanation of those data structures is beyond the scope of this manual, but you'll find at least one example for each of them. For more information we refer you to external literature about this broad topic.
An array can be created by the array() language-construct. It takes a certain number of comma-separated key => value pairs.
array( [key =>] value , ... ) // key may be an integer or string // value may be any value |
A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. There are no different indexed and associative array types in PHP; there is only one array type, which can both contain integer and string indices.
A value can be of any PHP type.
<?php $arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42)); echo $arr["somearray"][6]; // 5 echo $arr["somearray"][13]; // 9 echo $arr["somearray"]["a"]; // 42 ?> |
If you do not specify a key for a given value, then the maximum of the integer indices is taken, and the new key will be that maximum value + 1. If you specify a key that already has a value assigned to it, that value will be overwritten.
<?php // This array is the same as ... array(5 => 43, 32, 56, "b" => 12); // ...this array array(5 => 43, 6 => 32, 7 => 56, "b" => 12); ?> |
Avvertimento |
As of PHP 4.3.0, the index generation behaviour described above has changed. Now, if you append to an array in which the current maximum key is negative, then the next key created will be zero (0). Before, the new index would have been set to the largest existing key + 1, the same as positive indices are. |
Using TRUE as a key will evaluate to integer 1 as key. Using FALSE as a key will evaluate to integer 0 as key. Using NULL as a key will evaluate to the empty string. Using the empty string as key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets.
You cannot use arrays or objects as keys. Doing so will result in a warning: Illegal offset type.
You can also modify an existing array by explicitly setting values in it.
This is done by assigning values to the array while specifying the key in brackets. You can also omit the key, add an empty pair of brackets ("[]") to the variable name in that case.
$arr[key] = value; $arr[] = value; // key may be an integer or string // value may be any value |
<?php $arr = array(5 => 1, 12 => 2); $arr[] = 56; // This is the same as $arr[13] = 56; // at this point of the script $arr["x"] = 42; // This adds a new element to // the array with key "x" unset($arr[5]); // This removes the element from the array unset($arr); // This deletes the whole array ?> |
Nota: As mentioned above, if you provide the brackets with no key specified, then the maximum of the existing integer indices is taken, and the new key will be that maximum value + 1 . If no integer indices exist yet, the key will be 0 (zero). If you specify a key that already has a value assigned to it, that value will be overwritten.
Avvertimento As of PHP 4.3.0, the index generation behaviour described above has changed. Now, if you append to an array in which the current maximum key is negative, then the next key created will be zero (0). Before, the new index would have been set to the largest existing key + 1, the same as positive indices are.
Note that the maximum integer key used for this need not currently exist in the array. It simply must have existed in the array at some time since the last time the array was re-indexed. The following example illustrates:
<?php // Create a simple array. $array = array(1, 2, 3, 4, 5); print_r($array); // Now delete every item, but leave the array itself intact: foreach ($array as $i => $value) { unset($array[$i]); } print_r($array); // Append an item (note that the new key is 5, instead of 0 as you // might expect). $array[] = 6; print_r($array); // Re-index: $array = array_values($array); $array[] = 7; print_r($array); ?>Il precedente esempio visualizzerà:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) Array ( ) Array ( [5] => 6 ) Array ( [0] => 6 [1] => 7 )
There are quite a few useful functions for working with arrays. See the array functions section.
Nota: The unset() function allows unsetting keys of an array. Be aware that the array will NOT be reindexed. If you only use "usual integer indices" (starting from zero, increasing by one), you can achieve the reindex effect by using array_values().
The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array.
You should always use quotes around a string literal array index. For example, use $foo['bar'] and not $foo[bar]. But why is $foo[bar] wrong? You might have seen the following syntax in old scripts:
This is wrong, but it works. Then, why is it wrong? The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes), and PHP may in future define constants which, unfortunately for your code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.Nota: This does not mean to always quote the key. You do not want to quote keys which are constants or variables, as this will prevent PHP from interpreting them.
<?php error_reporting(E_ALL); ini_set('display_errors', true); ini_set('html_errors', false); // Simple array: $array = array(1, 2); $count = count($array); for ($i = 0; $i < $count; $i++) { echo "\nChecking $i: \n"; echo "Bad: " . $array['$i'] . "\n"; echo "Good: " . $array[$i] . "\n"; echo "Bad: {$array['$i']}\n"; echo "Good: {$array[$i]}\n"; } ?>Nota: Il precedente esempio visualizzerà:
Checking 0: Notice: Undefined index: $i in /path/to/script.html on line 9 Bad: Good: 1 Notice: Undefined index: $i in /path/to/script.html on line 11 Bad: Good: 1 Checking 1: Notice: Undefined index: $i in /path/to/script.html on line 9 Bad: Good: 2 Notice: Undefined index: $i in /path/to/script.html on line 11 Bad: Good: 2
More examples to demonstrate this fact:
<?php // Let's show all errors error_reporting(E_ALL); $arr = array('fruit' => 'apple', 'veggie' => 'carrot'); // Correct print $arr['fruit']; // apple print $arr['veggie']; // carrot // Incorrect. This works but also throws a PHP error of // level E_NOTICE because of an undefined constant named fruit // // Notice: Use of undefined constant fruit - assumed 'fruit' in... print $arr[fruit]; // apple // Let's define a constant to demonstrate what's going on. We // will assign value 'veggie' to a constant named fruit. define('fruit', 'veggie'); // Notice the difference now print $arr['fruit']; // apple print $arr[fruit]; // carrot // The following is okay as it's inside a string. Constants are not // looked for within strings so no E_NOTICE error here print "Hello $arr[fruit]"; // Hello apple // With one exception, braces surrounding arrays within strings // allows constants to be looked for print "Hello {$arr[fruit]}"; // Hello carrot print "Hello {$arr['fruit']}"; // Hello apple // This will not work, results in a parse error such as: // Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING' // This of course applies to using autoglobals in strings as well print "Hello $arr['fruit']"; print "Hello $_GET['foo']"; // Concatenation is another option print "Hello " . $arr['fruit']; // Hello apple ?> |
When you turn error_reporting() up to show E_NOTICE level errors (such as setting it to E_ALL) then you will see these errors. By default, error_reporting is turned down to not show them.
As stated in the syntax section, there must be an expression between the square brackets ('[' and ']'). That means that you can write things like this:
This is an example of using a function return value as the array index. PHP also knows about constants, as you may have seen the E_* ones before.<?php $error_descriptions[E_ERROR] = "A fatal error has occured"; $error_descriptions[E_WARNING] = "PHP issued a warning"; $error_descriptions[E_NOTICE] = "This is just an informal notice"; ?> |
<?php $error_descriptions[1] = "A fatal error has occured"; $error_descriptions[2] = "PHP issued a warning"; $error_descriptions[8] = "This is just an informal notice"; ?> |
As we already explained in the above examples, $foo[bar] still works but is wrong. It works, because bar is due to its syntax expected to be a constant expression. However, in this case no constant with the name bar exists. PHP now assumes that you meant bar literally, as the string "bar", but that you forgot to write the quotes.
At some point in the future, the PHP team might want to add another constant or keyword, or you may introduce another constant into your application, and then you get in trouble. For example, you already cannot use the words empty and default this way, since they are special reserved keywords.
Nota: To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings.
For any of the types: integer, float, string, boolean and resource, if you convert a value to an array, you get an array with one element (with index 0), which is the scalar value you started with.
If you convert an object to an array, you get the properties (member variables) of that object as the array's elements. The keys are the member variable names.
If you convert a NULL value to an array, you get an empty array.
The array type in PHP is very versatile, so here will be some examples to show you the full power of arrays.
<?php // this $a = array( 'color' => 'red', 'taste' => 'sweet', 'shape' => 'round', 'name' => 'apple', 4 // key will be 0 ); // is completely equivalent with $a['color'] = 'red'; $a['taste'] = 'sweet'; $a['shape'] = 'round'; $a['name'] = 'apple'; $a[] = 4; // key will be 0 $b[] = 'a'; $b[] = 'b'; $b[] = 'c'; // will result in the array array(0 => 'a' , 1 => 'b' , 2 => 'c'), // or simply array('a', 'b', 'c') ?> |
Esempio 11-6. Using array()
|
Changing values of the array directly is possible since PHP 5 by passing them as reference. Prior versions need workaround:
Esempio 11-8. Collection
Il precedente esempio visualizzerà:
|
This example creates a one-based array.
Arrays are ordered. You can also change the order using various sorting functions. See the array functions section for more information. You can count the number of items in an array using the count() function.
Because the value of an array can be anything, it can also be another array. This way you can make recursive and multi-dimensional arrays.
Esempio 11-12. Recursive and multi-dimensional arrays
|
You should be aware that array assignment always involves value copying. You need to use the reference operator to copy an array by reference.
To initialize an object, you use the new statement to instantiate the object to a variable.
For a full discussion, please read the section Classes and Objects.
If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built in class is created. If the value was NULL, the new instance will be empty. Array converts to an object with properties named by array keys and with corresponding values. For any other value, a member variable named scalar will contain the value.
A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. See the appendix for a listing of all these functions and the corresponding resource types.
Nota: The resource type was introduced in PHP 4
See also get_resource_type().
As resource types hold special handlers to opened files, database connections, image canvas areas and the like, you cannot convert any value to a resource.
Due to the reference-counting system introduced with PHP 4's Zend Engine, it is automatically detected when a resource is no longer referred to (just like Java). When this is the case, all resources that were in use for this resource are made free by the garbage collector. For this reason, it is rarely ever necessary to free the memory manually by using some free_result function.
Nota: Persistent database links are special, they are not destroyed by the garbage collector. See also the section about persistent connections.
The special NULL value represents that a variable has no value. NULL is the only possible value of type NULL.
Nota: The null type was introduced in PHP 4.
A variable is considered to be NULL if
it has been assigned the constant NULL.
it has not been set to any value yet.
it has been unset().
mixed indicates that a parameter may accept multiple (but not necessarily all) types.
gettype() for example will accept all PHP types, while str_replace() will accept strings and arrays.
Some functions like call_user_func() or usort() accept user defined callback functions as a parameter. Callback functions can not only be simple functions but also object methods including static class methods.
A PHP function is simply passed by its name as a string. You can pass any builtin or user defined function with the exception of array(), echo(), empty(), eval(), exit(), isset(), list(), print() and unset().
A method of an instantiated object is passed as an array containing an object as the element with index 0 and a method name as the element with index 1.
Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object as the element with index 0.
Esempio 11-13. Callback function examples
|
PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var, $var becomes a string. If you then assign an integer value to $var, it becomes an integer.
An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.
<?php $foo = "0"; // $foo is string (ASCII 48) $foo += 2; // $foo is now an integer (2) $foo = $foo + 1.3; // $foo is now a float (3.3) $foo = 5 + "10 Little Piggies"; // $foo is integer (15) $foo = 5 + "10 Small Pigs"; // $foo is integer (15) ?> |
If the last two examples above seem odd, see String conversion to numbers.
If you wish to force a variable to be evaluated as a certain type, see the section on Type casting. If you wish to change the type of a variable, see settype().
If you would like to test any of the examples in this section, you can use the var_dump() function.
Nota: The behaviour of an automatic conversion to array is currently undefined.
Since PHP (for historical reasons) supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem: should $a become an array with its first element being "f", or should "f" become the first character of the string $a?
The current versions of PHP interpret the second assignment as a string offset identification, so $a becomes "f", the result of this automatic conversion however should be considered undefined. PHP 4 introduced the new curly bracket syntax to access characters in string, use this syntax instead of the one presented above:
See the section titled String access by character for more information.
Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.
The casts allowed are:
(int), (integer) - cast to integer
(bool), (boolean) - cast to boolean
(float), (double), (real) - cast to float
(string) - cast to string
(array) - cast to array
(object) - cast to object
Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:
Nota: Instead of casting a variable to string, you can also enclose the variable in double quotes.
It may not be obvious exactly what will happen when casting between certain types. For more info, see these sections:
Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.
Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
Nota: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255 (0x7f-0xff).
For information on variable related functions, see the Variable Functions Reference.
<?php $var = 'Bob'; $Var = 'Joe'; echo "$var, $Var"; // outputs "Bob, Joe" $4site = 'not yet'; // invalid; starts with a number $_4site = 'not yet'; // valid; starts with an underscore $täyte = 'mansikka'; // valid; 'ä' is (Extended) ASCII 228. ?> |
In PHP 3, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see the chapter on Expressions.
As of PHP 4, PHP offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa. This also means that no copying is performed; thus, the assignment happens more quickly. However, any speedup will likely be noticed only in tight loops or when assigning large arrays or objects.
To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice:
<?php $foo = 'Bob'; // Assign the value 'Bob' to $foo $bar = &$foo; // Reference $foo via $bar. $bar = "My name is $bar"; // Alter $bar... echo $bar; echo $foo; // $foo is altered too. ?> |
One important thing to note is that only named variables may be assigned by reference.
PHP provides a large number of predefined variables to any script which it runs. Many of these variables, however, cannot be fully documented as they are dependent upon which server is running, the version and setup of the server, and other factors. Some of these variables will not be available when PHP is run on the command line. For a listing of these variables, please see the section on Reserved Predefined Variables.
Avvertimento |
In PHP 4.2.0 and later, the default value for the PHP directive register_globals is off. This is a major change in PHP. Having register_globals off affects the set of predefined variables available in the global scope. For example, to get DOCUMENT_ROOT you'll use $_SERVER['DOCUMENT_ROOT'] instead of $DOCUMENT_ROOT, or $_GET['id'] from the URL http://www.example.com/test.php?id=3 instead of $id, or $_ENV['HOME'] instead of $HOME. For related information on this change, read the configuration entry for register_globals, the security chapter on Using Register Globals , as well as the PHP 4.1.0 and 4.2.0 Release Announcements. Using the available PHP Reserved Predefined Variables, like the superglobal arrays, is preferred. |
From version 4.1.0 onward, PHP provides an additional set of predefined arrays containing variables from the web server (if applicable), the environment, and user input. These new arrays are rather special in that they are automatically global--i.e., automatically available in every scope. For this reason, they are often known as 'autoglobals' or 'superglobals'. (There is no mechanism in PHP for user-defined superglobals.) The superglobals are listed below; however, for a listing of their contents and further discussion on PHP predefined variables and their natures, please see the section Reserved Predefined Variables. Also, you'll notice how the older predefined variables ($HTTP_*_VARS) still exist. As of PHP 5.0.0, the long PHP predefined variable arrays may be disabled with the register_long_arrays directive.
Variable variables: Superglobals cannot be used as variable variables inside functions or class methods.
Nota: Even though both the superglobal and HTTP_*_VARS can exist at the same time; they are not identical, so modifying one will not change the other.
If certain variables in variables_order are not set, their appropriate PHP predefined arrays are also left empty.
PHP Superglobals
Contains a reference to every variable which is currently available within the global scope of the script. The keys of this array are the names of the global variables. $GLOBALS has existed since PHP 3.
Variables set by the web server or otherwise directly related to the execution environment of the current script. Analogous to the old $HTTP_SERVER_VARS array (which is still available, but deprecated).
Variables provided to the script via URL query string. Analogous to the old $HTTP_GET_VARS array (which is still available, but deprecated).
Variables provided to the script via HTTP POST. Analogous to the old $HTTP_POST_VARS array (which is still available, but deprecated).
Variables provided to the script via HTTP cookies. Analogous to the old $HTTP_COOKIE_VARS array (which is still available, but deprecated).
Variables provided to the script via HTTP post file uploads. Analogous to the old $HTTP_POST_FILES array (which is still available, but deprecated). See POST method uploads for more information.
Variables provided to the script via the environment. Analogous to the old $HTTP_ENV_VARS array (which is still available, but deprecated).
Variables provided to the script via the GET, POST, and COOKIE input mechanisms, and which therefore cannot be trusted. The presence and order of variable inclusion in this array is defined according to the PHP variables_order configuration directive. This array has no direct analogue in versions of PHP prior to 4.1.0. See also import_request_variables().
Attenzione |
Since PHP 4.3.0, FILE information from $_FILES does not exist in $_REQUEST. |
Nota: When running on the command line , this will not include the argv and argc entries; these are present in the $_SERVER array.
Variables which are currently registered to a script's session. Analogous to the old $HTTP_SESSION_VARS array (which is still available, but deprecated). See the Session handling functions section for more information.
The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:
Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:
<?php $a = 1; /* global scope */ function Test() { echo $a; /* reference to local scope variable */ } Test(); ?> |
This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.
First, an example use of global:
The above script will output "3". By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.
A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:
The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal. Here's an example demonstrating the power of superglobals:
Esempio 12-3. Example demonstrating superglobals and scope
|
Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example:
This function is quite useless since every time it is called it sets $a to 0 and prints "0". The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:
Now, every time the Test() function is called it will print the value of $a and increment it.
Static variables also provide one way to deal with recursive functions. A recursive function is one which calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10, using the static variable $count to know when to stop:
Nota: Static variables may be declared as seen in the examples above. Trying to assign values to these variables which are the result of expressions will cause a parse error.
The Zend Engine 1, driving PHP 4, implements the static and global modifier for variables in terms of references. For example, a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. This can lead to unexpected behaviour which the following example addresses:
<?php function test_global_ref() { global $obj; $obj = &new stdclass; } function test_global_noref() { global $obj; $obj = new stdclass; } test_global_ref(); var_dump($obj); test_global_noref(); var_dump($obj); ?> |
Executing this example will result in the following output:
NULL object(stdClass)(0) { } |
A similar behaviour applies to the static statement. References are not stored statically:
<?php function &get_instance_ref() { static $obj; echo 'Static object: '; var_dump($obj); if (!isset($obj)) { // Assign a reference to the static variable $obj = &new stdclass; } $obj->property++; return $obj; } function &get_instance_noref() { static $obj; echo 'Static object: '; var_dump($obj); if (!isset($obj)) { // Assign the object to the static variable $obj = new stdclass; } $obj->property++; return $obj; } $obj1 = get_instance_ref(); $still_obj1 = get_instance_ref(); echo "\n"; $obj2 = get_instance_noref(); $still_obj2 = get_instance_noref(); ?> |
Executing this example will result in the following output:
Static object: NULL Static object: NULL Static object: NULL Static object: object(stdClass)(1) { ["property"]=> int(1) } |
This example demonstrates that when assigning a reference to a static variable, it's not remembered when you call the &get_instance_ref() function a second time.
Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:
A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.
At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement:
produces the exact same output as:
i.e. they both produce: hello world.
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
Avvertimento |
Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. |
When a form is submitted to a PHP script, the information from that form is automatically made available to the script. There are many ways to access this information, for example:
Depending on your particular setup and personal preferences, there are many ways to access data from your HTML forms. Some examples are:
Esempio 12-9. Accessing data from a simple POST HTML form
|
Using a GET form is similar except you'll use the appropriate GET predefined variable instead. GET also applies to the QUERY_STRING (the information after the '?' in a URL). So, for example, http://www.example.com/test.php?id=3 contains GET data which is accessible with $_GET['id']. See also $_REQUEST and import_request_variables().
Nota: Superglobal arrays, like $_POST and $_GET, became available in PHP 4.1.0
As shown, before PHP 4.2.0 the default value for register_globals was on. And, in PHP 3 it was always on. The PHP community is encouraging all to not rely on this directive as it's preferred to assume it's off and code accordingly.
Nota: The magic_quotes_gpc configuration directive affects Get, Post and Cookie values. If turned on, value (It's "PHP!") will automagically become (It\'s \"PHP!\"). Escaping is needed for DB insertion. See also addslashes(), stripslashes() and magic_quotes_sybase.
PHP also understands arrays in the context of form variables (see the related faq). You may, for example, group related variables together, or use this feature to retrieve values from a multiple select input. For example, let's post a form to itself and upon submission display the data:
Esempio 12-10. More complex form variables
|
In PHP 3, the array form variable usage is limited to single-dimensional arrays. As of PHP 4, no such restriction applies.
When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:
When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image. The experienced may note that the actual variable names sent by the browser contains a period rather than an underscore, but PHP converts the period to an underscore automatically.
PHP transparently supports HTTP cookies as defined by Netscape's Spec. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() function. Cookies are part of the HTTP header, so the SetCookie function must be called before any output is sent to the browser. This is the same restriction as for the header() function. Cookie data is then available in the appropriate cookie data arrays, such as $_COOKIE, $HTTP_COOKIE_VARS as well as in $_REQUEST. See the setcookie() manual page for more details and examples.
If you wish to assign multiple values to a single cookie variable, you may assign it as an array. For example:
<?php setcookie("MyCookie[foo]", 'Testing 1', time()+3600); setcookie("MyCookie[bar]", 'Testing 2', time()+3600); ?> |
That will create two separate cookies although MyCookie will now be a single array in your script. If you want to set just one cookie with multiple values, consider using serialize() or explode() on the value first.
Note that a cookie will replace a previous cookie by the same name in your browser unless the path or domain is different. So, for a shopping cart application you may want to keep a counter and pass this along. i.e.
Esempio 12-11. A setcookie() example
|
Typically, PHP does not alter the names of variables when they are passed into a script. However, it should be noted that the dot (period, full stop) is not a valid character in a PHP variable name. For the reason, look at it:
<?php $varname.ext; /* invalid variable name */ ?> |
For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores.
Because PHP determines the types of variables and converts them (generally) as needed, it is not always obvious what type a given variable is at any one time. PHP includes several functions which find out what type a variable is, such as: gettype(), is_array(), is_float(), is_int(), is_object(), and is_string(). See also the chapter on Types.
Una costante è un identificatore (nome) per un valore. Come si può intuire, tale valore non può cambiare durante l'esecuzione dello script (fanno eccezione le costanti magiche, che, in realtà, non sono costanti). Una costante è "case-sensitive" per default. È convenzione comune che i nomi di costante siano sempre maiuscoli.
In PHP il nome di una costante segue le regole di qualsiasi "etichetta". Un nome di costante valido inizia con una lettera o underscore, seguita da un numero qualsiasi di caratteri alfanumerici o underscore. L'espressione regolare che esprime questa convenzione è: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
Esempio 13-1. Nomi di costanti validi ed errati
|
Nota: In questo contesto una lettera è a-z, A-Z e i caratteri ASCII dal 127 al 255 (0x7f-0xff).
Come le superglobals, costante è sempre globale. Si può accedere alle costanti da qualsiasi punto dello script senza tenere conto della visibilità. Per maggiori dettagli sulla visibilità, leggere la sezione variable scope.
È possibile definire una variabile utilizzando la funzione define(). Una volta definita, a una costante non è possibile cambiare il valore o eliminarla.
Le costanti possono contenere solo dati di tipo scalare (boolean, integer, float e string).
Per ottenere il valore di una costante è sufficiente specificarne il nome. A differenza delle variabili, non è necessario anteporre il simbolo $ al nome di una variabile. Si può anche utilizzare la funzione constant(), per leggere il valore di una costante, nel caso in cui se ne ottenga dinamicamente il nome. Si utilizzi get_defined_constants() per ottenere una lista delle variabili definite.
Nota: Costanti e variabili (globali) si trovano in un "namespace" differente. Questo implica che generalmente TRUE e $TRUE sono differenti.
Se si utilizza il nome di una costante che non è definita, PHP assume che detto valore sia il nome della costante stessa, come se si fosse inserito il testo nel nome . Quando ciò accade PHP segnala il problema con un E_NOTICE. Vedere anche il capitolo del manuale sul perchè $foo[bar] è errata (a meno che prima non definisca bar come costante con define()). Per sapere se una costante è definita, si può utilizzare la funzione defined().
Di seguito sono riportate le principali differenze rispetto le variabili:
Le costanti non iniziano con il segno del dollaro ($);
Le costanti possono essere definite solo con la funzione define() e non tramite assegnazione;
Le costanti possono essere definite e utilizzate ovunque senza seguire le regole di visibilità;
Una volta impostate, le costanti non posso essere redefinite e ne annullate;
Le costanti possono essere solo valori scalari;
Il PHP mette a disposizione ad ogni script diverse costanti predefinite disponibili a tutti gli script. Alcune di queste, tuttavia, sono create dai vari moduli, e, pertanto, saranno disponibili solo quando questi moduli sono caricati, sia dinamicamente sia staticamente.
Esistono cinque costanti magiche il cui valore cambia in base al contesto in cui sono utilizzate. Ad esempio, il valore di __LINE__ dipende da quale linea si trova nel momento in cui è richiamata. Queste costanti speciali sono 'case-insensitive' e sono:
Tabella 13-1. Le costanti "magiche" del PHP
Nome | Descrizione |
---|---|
__LINE__ | Il numero di linea corrente. |
__FILE__ | Il nome e percorso assoluto del file. Se viene utilizzata all'interno di un'include, la costante restituisce il nome del file incluso. Dal PHP 4.0.2, __FILE__ contiene sempre il percorso assoluto del file, mentre nelle versioni precedenti, in base alle circostanze, poteva contenere il percorso relativo. |
__FUNCTION__ | Nome della funzione. (Aggiunta nel PHP 4.3.0.) Dal PHP 5 questa costante restituisce il nome della funzione così come è stato dichiarato (rispettando le lettere maiuscole). In PHP 4 è sempre minuscolo. |
__CLASS__ | Nome della classe. (Aggiunta nel PHP 4.3.0.). Dal PHP 5 questa costante restituisce il nome della classe così come è stato dichiarato (rispettando le lettere maiuscole). In PHP 4 è sempre minuscolo. |
__METHOD__ | Nome del metodo della classe. (Aggiunta nel PHP 5.0.0.). Questa costante restituisce il nome del metodo così come è stato dichiarato (rispettando le lettere maiuscole). |
Vedere anche get_class(), get_object_vars(), file_exists() e function_exists().
Expressions are the most important building stones of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value".
The most basic forms of expressions are constants and variables. When you type "$a = 5", you're assigning '5' into $a. '5', obviously, has the value 5, or in other words '5' is an expression with the value of 5 (in this case, '5' is an integer constant).
After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value of 5 as well. If everything works right, this is exactly what will happen.
Slightly more complex examples for expressions are functions. For instance, consider the following function:
Assuming you're familiar with the concept of functions (if you're not, take a look at the chapter about functions), you'd assume that typing $c = foo() is essentially just like writing $c = 5, and you're right. Functions are expressions with the value of their return value. Since foo() returns 5, the value of the expression 'foo()' is 5. Usually functions don't just return a static value but compute something.
Of course, values in PHP don't have to be integers, and very often they aren't. PHP supports four scalar value types: integer values, floating point values (float), string values and boolean values (scalar values are values that you can't 'break' into smaller pieces, unlike arrays, for instance). PHP also supports two composite (non-scalar) types: arrays and objects. Each of these value types can be assigned into variables or returned from functions.
PHP takes expressions much further, in the same way many other languages do. PHP is an expression-oriented language, in the sense that almost everything is an expression. Consider the example we've already dealt with, '$a = 5'. It's easy to see that there are two values involved here, the value of the integer constant '5', and the value of $a which is being updated to 5 as well. But the truth is that there's one additional value involved here, and that's the value of the assignment itself. The assignment itself evaluates to the assigned value, in this case 5. In practice, it means that '$a = 5', regardless of what it does, is an expression with the value 5. Thus, writing something like '$b = ($a = 5)' is like writing '$a = 5; $b = 5;' (a semicolon marks the end of a statement). Since assignments are parsed in a right to left order, you can also write '$b = $a = 5'.
Another good example of expression orientation is pre- and post-increment and decrement. Users of PHP and many other languages may be familiar with the notation of variable++ and variable--. These are increment and decrement operators. In PHP/FI 2, the statement '$a++' has no value (is not an expression), and thus you can't assign it or use it in any way. PHP enhances the increment/decrement capabilities by making these expressions as well, like in C. In PHP, like in C, there are two types of increment - pre-increment and post-increment. Both pre-increment and post-increment essentially increment the variable, and the effect on the variable is identical. The difference is with the value of the increment expression. Pre-increment, which is written '++$variable', evaluates to the incremented value (PHP increments the variable before reading its value, thus the name 'pre-increment'). Post-increment, which is written '$variable++' evaluates to the original value of $variable, before it was incremented (PHP increments the variable after reading its value, thus the name 'post-increment').
A very common type of expressions are comparison expressions. These expressions evaluate to either FALSE or TRUE. PHP supports > (bigger than), >= (bigger than or equal to), == (equal), != (not equal), < (smaller than) and <= (smaller than or equal to). The language also supports a set of strict equivalence operators: === (equal to and same type) and !== (not equal to or not same type). These expressions are most commonly used inside conditional execution, such as if statements.
The last example of expressions we'll deal with here is combined operator-assignment expressions. You already know that if you want to increment $a by 1, you can simply write '$a++' or '++$a'. But what if you want to add more than one to it, for instance 3? You could write '$a++' multiple times, but this is obviously not a very efficient or comfortable way. A much more common practice is to write '$a = $a + 3'. '$a + 3' evaluates to the value of $a plus 3, and is assigned back into $a, which results in incrementing $a by 3. In PHP, as in several other languages like C, you can write this in a shorter way, which with time would become clearer and quicker to understand as well. Adding 3 to the current value of $a can be written '$a += 3'. This means exactly "take the value of $a, add 3 to it, and assign it back into $a". In addition to being shorter and clearer, this also results in faster execution. The value of '$a += 3', like the value of a regular assignment, is the assigned value. Notice that it is NOT 3, but the combined value of $a plus 3 (this is the value that's assigned into $a). Any two-place operator can be used in this operator-assignment mode, for example '$a -= 5' (subtract 5 from the value of $a), '$b *= 7' (multiply the value of $b by 7), etc.
There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:
If the value of the first subexpression is TRUE (non-zero), then the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.
The following example should help you understand pre- and post-increment and expressions in general a bit better:
<?php function double($i) { return $i*2; } $b = $a = 5; /* assign the value five into the variable $a and $b */ $c = $a++; /* post-increment, assign original value of $a (5) to $c */ $e = $d = ++$b; /* pre-increment, assign the incremented value of $b (6) to $d and $e */ /* at this point, both $d and $e are equal to 6 */ $f = double($d++); /* assign twice the value of $d before the increment, 2*6 = 12 to $f */ $g = double(++$e); /* assign twice the value of $e after the increment, 2*7 = 14 to $g */ $h = $g += 10; /* first, $g is incremented by 10 and ends with the value of 24. the value of the assignment (24) is then assigned into $h, and $h ends with the value of 24 as well. */ ?> |
Some expressions can be considered as statements. In this case, a statement has the form of 'expr' ';' that is, an expression followed by a semicolon. In '$b=$a=5;', $a=5 is a valid expression, but it's not a statement by itself. '$b=$a=5;' however is a valid statement.
One last thing worth mentioning is the truth value of expressions. In many events, mainly in conditional execution and loops, you're not interested in the specific value of the expression, but only care about whether it means TRUE or FALSE. The constants TRUE and FALSE (case-insensitive) are the two possible boolean values. When necessary, an expression is automatically converted to boolean. See the section about type-casting for details about how.
PHP provides a full and powerful implementation of expressions, and documenting it entirely goes beyond the scope of this manual. The above examples should give you a good idea about what expressions are and how you can construct useful expressions. Throughout the rest of this manual we'll write expr to indicate any valid PHP expression.
Un operatore è un qualcosa che si posiziona tra uno o più valori (od espressioni, in gergo tecnico) e produce un'altro valore (in modo tale che la costruzione stessa diventi a sua volta un'espressione). In questo modo si può considerare operatori le funzioni o costruzioni che restituiscono valori (tipo print), e quelle che non restituiscono nulla (come echo) possono essere considerate come altro tipo di funzione.
Esistono tre tipi di operatori. Una tipologia sono gli operatori unari, i quali richiedono un solo valore, ad esempio ! (l'operatore di negazione) oppure ++ (l'operatore di autoincremento). Nel secondo gruppo troviamo gli operatori binari; questi costituiscono la maggior parte degli operatori disponibili in PHP, un e elenco di questi è presente alla sezione Precednza degli operatori.
Il terzo gruppo è costituito dal operatore ternario: ?:. Questo si può utilizzare per selezionare un espressione tra due possibili, in base ad una terza; piuttosto che dovere scegliere tra due righe di istruzioni o diversi percorsi di esecuzione. Racchiudere l'operatore ternario tra parentesi tonde è una buona idea.
La precedenza di un operatore specifica come esso tenga legate assieme "strettamente" due espressioni. Per esempio, nell'espressione 1 + 5 * 3, la risposta è 16 e non 18 perché l'operatore di moltiplicazione ("*") ha una precedenza più alta rispetto all'operatore di addizione ("+"). Le parentesi possono essere usate per forzare la precedenza, se necessario. Per esempio: (1 + 5) * 3 viene valutata 18. Se la precedenza tra gli operatori è simile, si utilizza l'associazione da sinistra a destra.
La seguente tabella fornisce una lista della precedenza degli operatori con gli operatori a più alta precedenza elencati prima. Gli operatori presenti nella medesima linea hanno uguale precedenza, in questi casi la loro associativià decide l'ordine con cui sono valutati.
Tabella 15-1. Precedenza degli operatori
Associatività | Operatori | Informazioni aggiuntive |
---|---|---|
non associativi | new | new |
destra | [ | array() |
destra | ! ~ ++ -- (int) (float) (string) (array) (object) @ | incremento/decremento |
destra | ! ~ + - (int) (float) (string) (array) (object) @ | tipi |
sinistra | * / % | operatori aritmetici |
sinistra | + - . | operatori aritmetici e operatori su stringhe |
sinistra | << >> | operatori sui bit |
non associativi | < <= > >= | operatori di confronto |
non associativi | == != === !== | operatori di confronto |
sinistra | & | operatori sui bit e riferimenti |
sinistra | ^ | operatori sui bit |
sinistra | | | operatori sui bit |
sinistra | && | operatori logici |
sinistra | || | operatori logici |
sinistra | ? : | Operatore ternario |
sinistra | = += -= *= /= .= %= &= |= ^= ~= <<= >>= | operatori di assegnazione |
sinistra | and | operatori logici |
sinistra | xor | operatori logici |
sinistra | or | operatori logici |
sinistra | , | diversi usi |
L'associazione a sinistra indica che l'espressione viene valutata da sinistra verso destra, l'associazione destra indica il contrario.
Nota: Sebbene ! abbia una maggiore pecedenza rispetto a =, il PHP cintinua a permetter espressioni tipo la seguente: if (!$a = foo()), in questo caso l'output di foo() viene inserito in $a.
Ricordate l'aritmetica di base dalla scuola? Questi funzionano proprio come quelli.
Tabella 15-2. Operatori aritmetici
Esempio | Nome | Risultato |
---|---|---|
-$a | Negazione | Opposto di $a. |
$a + $b | Addizione | La somma di $a e $b. |
$a - $b | Sottrazione | La differenza di $a e $b. |
$a * $b | Moltiplicazione | il prodotto di $a e $b. |
$a / $b | Divisione | Quoziente di $a e $b. |
$a % $b | Modulo | Il resto di $a diviso da $b. |
L'operatore di divisione ("/") restituisce un valore float in ogni caso, anche se i due operandi sono interi (oppure stringhe che vengono convertite in interi).
Nota: Il resto $a % $b è negativo per $a negativo.
Vedere anche le pagine del manuale sulle funzioni matematiche.
L'operatore di base dell'assegnazione è "=". La vostra prima inclinazione potrebbe essere di pensare che ciò sia come "uguale a". No. Esso significa realmente che l'operando a sinistra assume il valore dell'espressione a destra (ciò significa, "assegna il valore a").
Il valore di un'espressione di assegnazione è il valore assegnato. Cioè il valore di "$a = 3" è 3. Questo vi permette di fare qualche trucchetto:
In aggiunta all'operatore di base dell'assegnazione, ci sono gli "operatori combinati" per tutta l'aritmetica binaria e gli operatori di stringa che vi consentono di usare un valore in un'espressione e poi impostare il suo valore al risultato di quell'espressione. Per esempio:
<?php $a = 3; $a += 5; // imposta $a a 8, come se avessimo detto: $a = $a + 5; $b = "Ciao "; $b .= "Lì!"; // imposta $b a "Ciao Lì!", proprio come $b = $b . "Lì!"; ?> |
Notare che l'assegnazione copia la variabile originale alla nuova (assegnazione per valore), così i cambiamenti ad una non si verificheranno nell' altra. Ciò può anche avere rilevanza se avete bisogno di copiare qualcosa come un grande array in un ciclo molto stretto. Dal PHP 4 viene supportato l'assegnazione per riferimento, usando la sintassi $var = &$othervar;, ma ciò non è possibile in PHP 3. 'L'assegnazione per riferimento' vuol dire che entrambe le variabili finiscono con il puntare agli stessi dati, e nulla è copiato in nessun posto. Per ulteriori approfondimenti sui riferimenti, consultare References explained.
Gli operatori bitwise vi permettono di alterare bit specifici in posizione on oppure off. Se entrambi i parametri di sinistra e destra sono stringhe, l'operatore bitwise opererà sui caratteri ASCII della stringa.
<?php echo 12 ^ 9; // L'output è '5' echo "12" ^ "9"; // L'output è il carattere Backspace (ascii 8) // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8 echo "hallo" ^ "hello"; // L'output è il valore ascii #0 #4 #0 #0 #0 // 'a' ^ 'e' = #4 ?> |
Tabella 15-3. Operatori bitwise
Esempio | Nome | Risultato |
---|---|---|
$a & $b | And | Sono impostati ad ON i bit che sono ON sia in $a che in $b. |
$a | $b | Or | Sono impostati ad ON i bit che sono ON in $a oppure in $b. |
$a ^ $b | Xor | Sono impostati ad ON i bit che sono ON in $a oppure in $b na non quelli che sono entrambi ON. |
~ $a | Not | Sono impostati ad ON i bit che sono OFF in $a, e viceversa. |
$a << $b | Shift left | Sposta i bit di $a a sinistra di $b passi (ogni passo significa "moltiplica per due") |
$a >> $b | Shift right | Sposta i bit di $a a destra di $b passi (ogni passo significa "dividi per due") |
Avvertimento |
Non spostare a destra per più di 32 bit sui sistemi a 32 bit. Non spostare a sinistra nei casi in cui il risultato è un numero più lungo di 32 bit. |
Gli operatori di confronto, come suggerisce il loro nome, permettono di confrontare due valori. Può essere interessante vedere la tabella di raffronto dei tipi, dato che mostra esempi di vari confronti tra i tipi di variabili.
Tabella 15-4. Operatori di confronto
Esempio | Nome | Risultato |
---|---|---|
$a == $b | Uguale | TRUE se $a è uguale a $b. |
$a === $b | Identico | TRUE se $a è uguale a $b, ed essi sono dello stesso tipo. (Dal PHP 4) |
$a != $b | Diversi | TRUE se $a è diverso da $b. |
$a <> $b | Diversi | TRUE se $a è diverso da $b. |
$a !== $b | Non identici | TRUE se $a è diverso da $b, o se essi non sono dello stesso tipo. (Dal PHP 4) |
$a < $b | Minore | TRUE se $a è strettamente minore di $b. |
$a > $b | Maggiore | TRUE se $a è strettamente maggiore di $b. |
$a <= $b | Minore o uguale | TRUE se $a è minore o uguale a $b. |
$a >= $b | Maggiore o uguale | TRUE se $a è maggiore o uguale a $b. |
Se si confronta interi con stringhe, la stringa viene convertita in numero. Se si confronta due stringhe numeriche, queste vengono confrontate come interi. Queste regole valgono anche per l'istruzione switch.
<?php var_dump(0 == "a"); // 0 == 0 -> true var_dump("1" == "01"); // 1 == 1 -> true switch ("a") { case 0: echo "0"; break; case "a": // mai raggiunta perchè "a" è già riconosciuta come 0 echo "a"; break; } ?> |
Se i tipi di operarandi utilizzati differiscono, il confronto viene svolto nell'ordine indicato della seguente tabella.
Tabella 15-5. Confronti con differenti tipi
Tipo dell'operando 1 | Tipo dell'operando 2 | Risultato |
---|---|---|
null oppure string | string | Si converte NULL in "", confronto numerico o lessicale |
bool oppure null | qualsiasi | Convertito in bool, FALSE < TRUE |
object | object | Le classi predefinite possono avere la propria funzione di confronto, differenti classi non sono confrontabili, classi uguali - hanno le medesime proprietà di confronto delle matrici (PHP 4), pre il PHP 5 vedere qui per maggiori spiegazioni. |
string, resource oppure number | string, resource oppure number | Stringhe e risorse sono converti in numeri, confronto matematico |
array | array | La matrice con meno membri è più piccola, se la chiave dell'operando 1 non si trova nell'operando 2 allora le matrici non si possono confrontare, in altri casi il confronto avviene valore per valore (vedere l'esempio seguente) |
array | qualsiasi | array è sempre più grande |
object | qualsiasi | object è sempre più grande |
Esempio 15-2. Trascrizione del confronto standard tra matrici
|
Vedere anche strcasecmp(), strcmp(), Array operators, e la sezione del manuale su Types.
Un'altro operatore condizionale è l'operatore ternario "?:".
Nota: Si noti che l'operatore ternario è un'istruzione, e non viene valutato come variabile, ma come risultato di un'istruzione. Questo è importante da sapere nel caso si desideri restituire una variabile per riferimento. La riga return $var == 42 ? $a : $b; in una funzione che restituisce per riferimento non funzionerà e, nelle ultime versioni di PHP, genererà un warning.
PHP supporta un operatore di controllo dell'errore: il carattere at (@). Quando prefisso ad una espressione in PHP, qualunque messaggio di errore che potesse essere generato da quella espressione sarà ignorato.
Se la caratteristica track_errors è abilitata, qualsiasi messaggio di errore generato dall'espressione sarà salvato nella variabile globale $php_errormsg. Questa variabile sarà sovrascritta ad ogni errore, così controllatela subito se volete usarla.
<?php /* Errore di file intenzionale */ $my_file = @file ('file_inesistente') or die ("Apertura del file fallita: l'errore è '$php_errormsg'"); // questo funziona per qualsiasi espressione, non solo funzioni: $value = @$cache[$key]; // non verrà generata una notifica se l'indice $key non esiste. ?> |
Nota: L'operatore @ funziona solo sulle espressioni. Una semplice regola è: se potete prendere il valore di qualcosa, potete anteporre ad esso l'operatore @. Per esempio, potete anteporre esso a variabili, funzioni e chiamate ad include(), costanti, e così via. non potete anteporre esso a definizioni di funzioni o classi, o strutture condizionali come if e foreach, e così via.
Vedere anche error_reporting() e la sezione del manuale Gestione degli errori e funzioni di log.
Avvertimento |
Attualmente il prefisso operatore di controllo dell'errore "@" disabiliterà la restituzione di errori per errori critici che interromperanno l'esecuzione dello script. Tra le altre cose, questo significa che se state usando "@" per sopprimere errori da una certa funzione ed essa non è disponibile oppure è stata scritta male, lo script terminerà senza dare indicazioni sul perché. |
PHP supporta un operatore di esecuzione: backticks (``). Notare che quelli non sono apostrofi! PHP cercherà di eseguire il contenuto dei backticks come comando di shell; sarà restituito l'output (i.e., non sarà semplicemente esportato come output; può essere assegnato ad una variabile). L'uso dell'operatore backtick è identico alla funzione shell_exec().
Nota: L'operatore backtick è disabilitato quando è abilitata modalità sicura oppure quando è disabilitata shell_exec().
Vedere anche la sezione del manuale Funzioni per l'esecuzione di programmi, popen(), proc_open() e Utilizzo del PHP da linea di comando.
PHP supporta lo stile C degli operatori di pre- e post-incremento e decremento.
Nota: Gli operatori di incremento e decremento non agiscono sui valori boolean. Anche decrementare il valore NULL non ha effetti, ma incrementarlo darà come risultato 1.
Tabella 15-6. Operatori di incremento/decremento
Esempio | Nome | Effetto |
---|---|---|
++$a | Pre-incremento | Incrementa $a di una unità, inoltre restituisce $a. |
$a++ | Post-incremento | Restituisce $a, inoltre incrementa $a di una unità. |
--$a | Pre-decremento | Decrementa $a di una unità, inoltre restituisce $a. |
$a-- | Post-decremento | Restituisce $a, inoltre decrementa $a di una unità. |
Qui c'è un semplice script di esempio:
<?php echo "<h3>Postincrement</h3>"; $a = 5; echo "Dovrebbe essere 5: " . $a++ . "<br />\n"; echo "Dovrebbe essere 6: " . $a . "<br />\n"; echo "<h3>Pre-incremento</h3>"; $a = 5; echo "Dovrebbe essere 6: " . ++$a . "<br />\n"; echo "Dovrebbe essere 6: " . $a . "<br />\n"; echo "<h3>Post-decremento</h3>"; $a = 5; echo "Dovrebbe essere 5: " . $a-- . "<br />\n"; echo "Dovrebbe essere 4: " . $a . "<br />\n"; echo "<h3>Pre-decremento</h3>"; $a = 5; echo "Dovrebbe essere 4: " . --$a . "<br />\n"; echo "Dovrebbe essere 4: " . $a . "<br />\n"; ?> |
Il PHP segue le convenzioni di Perl e non del C quando tratta le operazioni matematiche sui caratteri. Ad esempio, in Perl 'Z'+1 restituisce 'AA', mentre in C 'Z'+1 restituisce '[' ( ord('Z') == 90, ord('[') == 91 ). Attenzione che le variabili con caratteri possono essere sommate e non sottratte.
Incrementare o decrementare valori booleani non ha effetto.
Tabella 15-7. Operatori logici
Esempio | Nome | Risultato |
---|---|---|
$a and $b | And | TRUE se entrambi $a e $b sono TRUE. |
$a or $b | Or | TRUE se uno tra $a o $b è TRUE. |
$a xor $b | Xor | TRUE se uno tra $a o $b è TRUE, ma non entrambi. |
! $a | Not | TRUE se $a non è TRUE. |
$a && $b | And | TRUE se entrambi $a e $b sono TRUE. |
$a || $b | Or | TRUE se uno tra $a o $b è TRUE. |
La ragione per le due differenti variazioni degli operatori "and" e "or" è che essi operano con differenti precedenze. (Vedere Precedenza degli operatori.)
Ci sono due operatori di stringa. Il primo è l'operatore di concatenazione ('.'), che restituisce la concatenazione dei suoi argomenti di destra e di sinistra. Il secondo è l'operatore di assegnazione concatenata ('.='), che accoda l'argomento sul lato destro all'argomento sul lato sinistro. Per favore consultare Operatori di assegnazione per maggiori informazioni.
<?php $a = "Ciao "; $b = $a . "Mondo!"; // ora $b contiene "Ciao Mondo!" $a = "Ciao "; $a .= "Mondo!"; // ora $a contiene "Ciao Mondo!" ?> |
Vedere anche le sezioni Stringhe e Funzioni per le stringhe nel manuale.
Tabella 15-8. Operatori per matrici
Esempio | Nome | Risultato |
---|---|---|
$a + $b | Unione | Unione di $a e $b. |
$a == $b | Uguaglianza | TRUE se $a e $b hanno le stesse coppie di chiavi/valori. |
$a === $b | Identità | TRUE se $a e $b hanno le stesse coppie di chiavi/valori nel medesimo ordine e dl medesimo tipo. |
$a != $b | Disuguaglianza | TRUE se $a non è uguale a $b. |
$a <> $b | Disuguaglianza | TRUE se $a non è uguale a $b. |
$a !== $b | Non-identità | TRUE se $a non è identico a $b. |
L'operatore + aggiunge la matrice di destra a quella di sinistra, mentre le chiavi duplicate NON sono sovrascritte.
<?php $a = array("a" => "apple", "b" => "banana"); $b = array("a" => "pear", "b" => "strawberry", "c" => "cherry"); $c = $a + $b; // Unione di $a e $b echo "Union of \$a and \$b: \n"; var_dump($c); $c = $b + $a; // Unione di $b e $a echo "Union of \$b and \$a: \n"; var_dump($c); ?> |
Union of $a and $b: array(3) { ["a"]=> string(5) "apple" ["b"]=> string(6) "banana" ["c"]=> string(6) "cherry" } Union of $b and $a: array(3) { ["a"]=> string(4) "pear" ["b"]=> string(10) "strawberry" ["c"]=> string(6) "cherry" } |
Gli elementi di una matrice sono uguali nel confronto se hanno le stesse chiavi e gli stessi valori.
Vedere anche la sezione del manuale sulle Matrici e Funzioni per le matrici.
PHP ha un unico operatore di tipo: instanceof. instanceof è utilizzato per determinare se un dato oggetto appartiene ad una data classe di oggetti.
L'operatore instanceof è stato introdotto in PHP 5. Prima di questo si utilizzava is_a(), ma ora is_a() viene sconsigliato in favore di instanceof.
<?php class A { } class B { } $thing = new A; if ($thing instanceof A) { echo 'A'; } if ($thing instanceof B) { echo 'B'; } ?> |
Poichè $thing è un oggetto di tipo A, ma non di tipo B, sarà eseguito soltanto il blocco dipendente dal tipo A:
A |
Vedere anche get_class() e is_a().
Qualsiasi script PHP è costituito da una serie di istruzioni. Una istruzione può essere un'assegnazione, una chiamata di funzione, un loop, una istruzione condizionale che non fa nulla (istruzione vuota). Le istruzioni terminano con un punto e virgola. Inoltre, le istruzioni si possono raggruppare in blocchi di istruzioni racchiudendole tra parentesi graffa. Un gruppo di istruzioni è, a sua volta, un'istruzione. Il presente capitolo descrive i differenti tipi di istruzioni.
Il costrutto if è una delle più importanti caratteristiche di qualsiasi linguaggio, incluso PHP. Permette l'esecuzione condizionata di frammenti di codice. La struttura di controllo if di PHP è simile a quella del linguaggio C:
Come descritto nella sezione sulle espressioni, espressione restiruirà il suo valore booleano. Se espressione vale TRUE, PHP eseguirà istruzione, e se essa vale FALSE - la ignorerà. Più informazioni riguardo i valori valutati FALSE possono essere trovati nella sezione 'Conversione in booleano' .
L'esempio che segue visualizzerà a è maggiore di b se $a sarà maggiore di $b:
Spesso sarà necessario eseguire più di una istruzione condizionale. Naturalmente non è necessario, utilizzare una singola clausola if per ciascuna istruzione. Si possono raggruppare diverse istruzioni in un singolo gruppo di istruzioni. Per esempio, il codice che segue visualizzerà a è maggiore di b se $a è maggiore di $b, e successivamente assegnerà il valore della variabile $a alla variabile $b:
Si possono annidare indefinitamente istruzioni if, la qual cosa fornisce piena flessibilità per l'esecuzione di istruzioni condizionali in diversi punti del programma.
Spesso è necessario eseguire un'istruzione se una proposizione è vera e un'altra istruzione se la proposizione è falsa. Per questo si usa la clausola else. else estende il costrutto if aggiungendo la possibilità di eseguire un'istruzione se l'espressione nel ramo if è FALSE. L'esempio che segue visualizzerà a è maggiore di b se $a è maggiore di $b e a NON è maggiore di b altrimenti:
Il ramo else viene eseguito solo se l'espressione nel ramo if è FALSE, e, nel caso ci fossero delle clausole elseif, solamente se le espressioni in esse contenute fossero anch'esse FALSE (vedere elseif).elseif, come è facile intuire, è una combinazione di if ed else. Analogamente ad else, estende if aggiungendo la possibilità di eseguire un'altra istruzione nel caso in cui l'espressione contenuta nel ramo if sia FALSE. Però, a differenza di else, si eseguirà l'istruzione alternativa solamente se l'espressione contenuta nel ramo elseif sarà TRUE. L'esempio che segue, visualizzerà a è maggiore di b, a è uguale a b oppure a è minore di b:
<?php if ($a > $b) { echo "a è maggiore di b"; } elseif ($a == $b) { echo "a è uguale a b"; } else { echo "a è minore di b"; } ?> |
Nel medesimo blocco if possono essere presenti più di una clausola elseif. Verrà eseguita l'istruzione del primo ramo elseif la cui espressione sia TRUE. In PHP è possibile scrivere 'else if' (due parole) e il significato sarà lo stesso di 'elseif' (una sola parola). Il significato sintattico è leggermente differente (se si ha familiarità con il linguaggio C, esso ha lo stesso comportamento) però al lato pratico l'effetto è il medesimo.
L'istruzione di un ramo elseif verrà eseguita solo se l'espressione del ramo if e le espressioni dei rami elseif precedenti sono FALSE, e se l'espressione del ramo elseif è TRUE.
PHP offre una sintassi alternativa per alcune delle sue strutture di controllo; vale a dire, if, while, for, foreach e switch. Fondamentalmente la sintassi alternativa consiste nel sostituire la prima parentesi graffa con il carattere "duepunti" (:) e la seconda parentesi graffa con endif;, endwhile;, endfor;, endforeach;, oppure endswitch;, rispettivamente.
Nell'esempio precedente, il blocco HTML "a è uguale a 5" è incluso nel ramo if scritto utilizzando la sintassi alternativa. Il blocco HTML verrà visualizzato solamente se $a è uguale a 5.
La sintassi alternativa si applica anche ad else ed elseif. Nell'esempio che segue si mostra come utilizzare la sintassi alternativa nel caso di un if con elseif ed else:
Il ciclo while è la forma di ciclo più semplice tra quelle possibili in PHP. Si comporta come la sua controparte nel linguaggio C. La forma di base di un ciclo while è la seguente:
Il significato di un ciclo while è semplice. Istruisce l'interprete PHP perchè esegua l'istruzione (o le istruzioni) in esso racchiuse, ripetutamente, fintanto che l'espressione contenuta nella clausola while ha valore TRUE. Il valore dell'espressione viene verificato ogni volta che il ciclo si ripete (iterazione), così che anche se il valore dell'espressione cambia durante l'esecuzione dell'istruzione, il ciclo non termina fino all'iterazione successiva. Ovviamente, se l'espressione nella clausola while ha valore FALSE dall'inizio, l'istruzione racchiusa nel blocco non verrà eseguita nemmeno una volta.
Come nel caso della struttura di controllo if, si possono raggruppare più istruzioni nello medesimo ciclo while racchiudendo le istruzioni in parentesi graffa, oppure utilizzando la sintassi alternativa:
Gli esempi seguenti sono identici e entrambi visualizzano i numeri da 1 a 10:
Il ciclo do-while è simile al ciclo while, con l'unica differenza che il valore dell'espressione viene controllato alla fine di ogni iterazione anzichè all'inizio. La differenza più importante rispetto a while è che la prima iterazione di un blocco do-while verrà sempre eseguita (il valore dell'espressione viene controllato alla fine del ciclo), mentre non sarà necessariamente eseguito in un ciclo while (il valore dell'espressione viene controllato all'inizio del ciclo, e se tale valore è FALSE dall'inizio, l'esecuzione del ciclo termina immediatamente).
È ammessa una sola sintassi per il ciclo do-while:
Il ciclo precedente verrà eseguito un'unica volta, dal momento che alla prima iterazione, quando si controlla l'espressione, il suo valore sarà FALSE ($i non è maggiore di 0) e il ciclo di esecuzioni, termina.
Chi ha utilizzato il linguaggio C conosce probabilmente un'altro modo di utilizzare il ciclo do-while, che permette di terminare l'esecuzione delle istruzioni durante l'esecuzione stessa, utilizzando do-while(0), e usando l'istruzione break. Il codice che segue esemplifica questa possibilità:
<?php do { if ($i < 5) { echo "i non è abbastanza grande"; break; } $i *= $factor; if ($i < $minimum_limit) { break; } echo "i è ok"; /* processa i */ } while (0); ?> |
Non vi preoccupate se l'esempio non è sufficientemente chiaro. Si possono scrivere ottimi programmi PHP anche senza far ricorso a questa 'possibilità'.
Il ciclo for è il ciclo più complesso tra quelli disponibili in PHP. Si comporta come la sua controparte nel linguaggio C. La sintassi di un clico for è:
Il valore della prima espressione (espressione1) viene verificato (eseguito) una sola volta incondizionatamente all'inizio del ciclo.
Ad ogni iterazione, si controlla il valore di espressione2. Se è TRUE, il ciclo prosegue e viene eseguita l'istruzione (o le istruzioni) contenuta nel blocco; se è FALSE, l'esecuzione del ciclo termina.
Al termine di ogni iterazione, si verifica (si esegue) il valore di espressione3.
Le due espressioni possono anche non essere presenti. Se non esiste espressione2 significa che il ciclo deve essere eseguito indefinitamente (PHP considera implicitamente che il suo valore è TRUE, come in C). Questa possibilità in fondo non è utile come può sembrare perchè obbliga a terminare il ciclo utilizzando l'istruzione break invece di utilizzare le espressioni booleane del ciclo for .
Si considerino gli esempi seguenti. In ciascun caso si visualizzeranno i numeri da 1 a 10:
<?php /* esempio 1 */ for ($i = 1; $i <= 10; $i++) { echo $i; } /* esempio 2 */ for ($i= 1; ; $i++) { if ($i > 10) { break; } echo $i; } /* esempio 3 */ $i = 1; for (; ; ) { if ($i > 10) { break; } echo $i; $i++; } /* esempio 4 */ for ($i = 1; $i <= 10; print $i, $i++) ; ?> |
Naturalmente il primo esempio sembra il migliore (o forse il quarto), ma l'uso del ciclo for senza espressioni può essere utile in molti casi.
PHP offre una sintassi alternativa (con i "punto e virgola") per i cicli for.
PHP 4 (non PHP 3) permette l'uso della struttura di controllo foreach, alla stessa maniera del linguaggio Perl e altri. Ciò semplicemente fornisce una facile metodo per attraversare un array. foreach funziona solo con le matrici e genera un errore se si tenta di utilizzarlo con variabili di tipo diffente oppure non inizializzate. Esistono due possibili notazioni sintattiche; la seconda è un'utile estensione della prima:
foreach(array_expression as $value) istruzione foreach(array_expression as $key => $value) i struzione |
La prima attraversa l'array dato da array_expression. Ad ogni ciclo, si assegna il valore dell'elemento corrente a $value e il puntatore interno avanza di una posizione (in modo tale che al ciclo successivo l'elemento corrente sarà il successivo elemento dell'array).
La seconda esegue lo stesso ciclo con la differenza che il valore dell'indice corrente viene assegnato ad ogni ciclo, alla variabile $key.
Dal PHP sono anche possibili cicli sugli oggetti.
Nota: All'inizio dell'esecuzione di un ciclo foreach il puntatore interno viene automaticamente posizionato nella prima posizione. Questo significa che non è necessario utilizzare la funzione reset() prima di un ciclo foreach.
Nota: A meno che la matrice non sia per riferimento, foreach agisce su una copia e non sulla matrice stessa. Pertanto il puntatore dell'array originale non viene modificato come accade utilizzando la funzione each() e le modifiche agli elementi dell'array non appaiono nell'array originale. Tuttavia il puntatore interno della matrice originale viene avanzato durante l'elaborazione della matrice. Se si assume che il ciclo foreach giunga al termine, allorasi avrà che il puntatore interno della matrcie sarà al termine della matrice stessa.
Dal PHP 5 si può modificare facilmente gli elementi di una matrice anteponendo & a $value with &. Questo assegna un riferimento anzichè copiare il valore.
Questo è possibile soltanto se l'array indicato può essere referenziato (ad esempio è una variabile).
Nota: foreach non offre la possibilità di annullare la generazione di messaggi d'errore utilizzando il carattere '@'.
Avete probabilmente notato che i due cicli seguenti sono identici da un punto di vista funzionale:
<?php $arr = array("one", "two", "three"); reset ($arr); while (list(, $value) = each ($arr)) { echo "Valore: $value<br />\n"; } foreach ($arr as $value) { echo "Valore: $value<br />\n"; } ?> |
<?php $arr = array("one", "two", "three"); reset ($arr); while (list($key, $value) = each ($arr)) { echo "Chiave: $key; Valore: $value<br />\n"; } foreach ($arr as $key => $value) { echo "Chiave: $key; Valore: $value<br>\n"; } ?> |
Di seguito, altri esempi per mostrare possibili utilizzi:
<?php /* esempio 1 foreach: solo il valore */ $a = array(1, 2, 3, 17); foreach ($a as $v) { echo "Valore corrente di \$a: $v.\n"; } /* esempio 2 foreach: valore (con la chiave stampata) */ $a = array(1, 2, 3, 17); $i = 0; /* solo per un proposito illustrativo */ foreach ($a as $v) { echo "\$a[$i] => $v.\n"; $i++; } /* esempio 3 foreach: chiave e valore */ $a = array( "uno" => 1, "due" => 2, "tre" => 3, "diciassette" => 17 ); foreach ($a as $k => $v) { echo "\$a[$k] => $v.\n"; } /* esempio 4 foreach: array multidimensionali */ $a = array(); $a[0][0] = "a"; $a[0][1] = "b"; $a[1][0] = "y"; $a[1][1] = "z"; foreach ($a as $v1) { foreach ($v1 as $v2) { echo "$v2\n"; } } /* esempio 5 foreach: array dinamici */ foreach (array(1, 2, 3, 4, 5) as $v) { echo "$v\n"; } ?> |
break termina l'esecuzione di una struttura for, foreach, while, do-while o switch.
break accetta un argomento opzionale che definisce, nel caso di cicli annidati, il livello del ciclo che è da interrompere.
<?php $arr = array ('uno', 'due', 'tre', 'quattro', 'stop', 'cinque'); while (list (, $val) = each ($arr)) { if ($val == 'stop') { break; /* Qui si può anche usare 'break 1;'. */ } echo "$val<br />\n"; } /* Uso dell'argomento opzionale. */ $i = 0; while (++$i) { switch ($i) { case 5: echo "At 5<br />\n"; break 1; /* Interrompe solo awitch. */ case 10: echo "At 10; quitting<br />\n"; break 2; /* Interrompe switch e while. */ default: break; } } ?> |
continue si utilizza per interrompere l'esecuzione del ciclo corrente e continuare con l'esecuzione dall'inizio del ciclo successivo dopo avere valutato la condizione.
Nota: Si noti che in PHP l'istruzione switch è considerata un'elemento di loop per gli scopi di continue.
continue accetta un argomento numerico opzionale che definisce, nel caso di cicli annidati, il numero di cicli da interrompere e da cui iniziare l'esecuzione dell'iterazione successiva.
<?php while (list($key, $value) = each ($arr)) { if (!($key % 2)) { // salta odd members continue; } do_something_odd($value); } $i = 0; while ($i++ < 5) { echo "Esterno<br />\n"; while (1) { echo " Centrale<br />\n"; while (1) { echo " Interno<br />\n"; continue 3; } echo "Questo non sarà mai stampato.<br />\n"; } echo "Nemmeno questo.<br />\n"; } ?> |
L'omissione del punto e virgola dopo continue può creare confuzione. Nel sseguente esempio si illustra cosa non di deve fare.
<?php for ($i = 0; $i < 5; ++$i) { if ($i == 2) continue print "$i\n"; } ?> |
Ci si può aspettare come risultato:
1 3 4 |
invece si avrà:
2 |
poichè il valore restituida da print() è int(1) e sembrerà il numero opzionale indicato in precedenza.
switch è simile a una serie di if sulla stessa espressione. In molti casi può essere necessario confrontare una variabile (o espressione) con differenti valori ed eseguire un differente blocco di istruzioni a seconda del valore di detta variabile. Questo è esattamente quello che fa la struttura di controllo switch.
Nota: Si noti che a differenza di altri linguaggi, l'istruzione continue si può utilizzare anche con switch ed ha un comportamento simile a break. Se si ha uno switch all'interno di un ciclo e si desidera continuare con il prossimo ciclo del loop esterno, utilizzare continue 2.
Gli esempi seguenti mostrano due maniere differenti di scrivere la stessa cosa, uno utilizzando una serie di istruzioni if ed elseif l'altro utilizzando switch:
È importante comprendere esattamente come viene eseguita la clausola switch per evitare errori. Un'istruzione switch esegue linea dopo linea le istruzioni in essa contenuta. All'inizio non viene eseguito alcun codice. Solamente quando incontra una clausola case il cui valore è uguale al valore della viariabile, PHP inizia ad eseguire le istruzioni contenute nel blocco case. PHP continua l'esecuzione delle istruzioni fino alla termine del blocco switch, o quando incontra un'istruzione break. Se non esiste alcuna istruzione break al termine di un blocco case PHP continuerà l'esecuzione delle istruzioni del blocco case successivo. Per esempio:
<?php switch ($i) { case 0: echo "i è uguale a 0"; case 1: echo "i è uguale a 1"; case 2: echo "i è uguale a 2"; } ?> |
In questo caso se $i è uguale a 0, PHP eseguirà tutte le istruzioni echo!. Se $i è uguale a 1, PHP eseguirà le ultime due echo. Si sarebbe ottenuto il comportamento atteso ( visualizzazione di 'i uguale a 2') solamente se $i è uguale a 2. Pertanto è importante non dimenticare l'istruzione break (anche se in alcuni casi potrà essere necessario non utilizzarla).
In un'istruzione switch, la condizione in parentesi viene valutata una sola volta e il risultato viene confrontato con ciascun ramo case. Utilizzando elseif, la condizione viene valutata una seconda volta. Se tale condizione è più complessa di un semplice confronto e/o è in un ciclo piuttosto pesante, l'uso di switch dovrebbe garantire un minor tempo di esecuzione.
Un blocco case può anche non contenere istruzioni, nel qual caso il controllo passa semplicemente al successivo blocco case.
<?php switch ($i) { case 0: case 1: case 2: print "i è minore di 3 ma non negativo"; break; case 3: print "i è 3"; } ?> |
Un blocco case speciale è il il blocco case di default. Uguaglia tutte le condizioni non uguagliate nei blocchi case precedenti e dev'essere l'ultimo blocco case. Per esempio:
<?php switch ($i) { case 0: echo "i è uguale a 0"; break; case 1: echo "i è uguale a 1"; break; case 2: echo "i è uguale a 2"; break; default: echo "i è diverso da 0, 1 o 2"; } ?> |
L'espressione in un ramo case può essere qualsiasi espressione il cui valore sarà di tipo intero, decimale, numerico e stringa. Array e oggetti (objects) non sono ammessi a meno che non siano dereferenziati a un tipo di dato semplice tra quelli precedentemente elencati.
Come per altre strutture di controllo è possibile utilizzare una sintassi alternativa. Si veda Sintassi alternativa per le strutture di controllo per ulteriori esempi.
Il costrutto declare si usa per definire direttive di esecuzione per blocchi di istruzioni. La sintassi è simile alla sintassi di altre strutture di controllo:
La sezione direttiva permette di impostare il comportamento del blocco declare . Attualmente è riconosciuta una sola direttiva: la direttiva ticks. (Fare riferimento più in basso per ulteriori informazioni relative alla direttiva ticks)
Verrà eseguita la parte istruzione del blocco declare -- come verrà eseguita e quali effetti collaterali emergeranno durante l'esecuzione potrà dipendere dalla direttiva impostata nel blocco direttiva.
L'istruzione declare può essere usata anche con visubilità globale, influenzando tutto il codice che la segue.
<?php // queste righe hanno il medesimo effetto: // si può utitlizzare in questo modo: declare(ticks=1) { // inserire tutto il codice } // o in questo modo declare(ticks=1); // inserire tutto il codice ?> |
Un tick è un evento che si verifica per ogni N istruzioni di basso livello eseguite dal parser all'interno del blocco declare. Il valore per N viene specificato usando ticks=N all'interno della sezione direttiva del blocco declare.
L'evento (o gli eventi) che si verifica su ogni tick è specificato usando register_tick_function(). Vedere l'esempio più in basso per ulteriori dettagli. Notare che può verificarsi più di un evento per ogni tick.
Esempio 16-3. Segue una sezione di codice PHP
|
I tick sono ben adeguati per il debugging, l'implementazione di semplici multitasking, backgrounded I/O e molti altri compiti.
Vedere anche register_tick_function() e unregister_tick_function().
Se viene chiamato all'interno di una funzione, l'istruzione return() termina immediatamente l'esecuzione della funzione corrente, e restituisce il suo argomento come valore della funzione chiamata. return() terminerà anche l'esecuzione di un'istruzione eval() o di un file di script.
Se viene chiamato in uno scope globale, allora verrà terrminata l'esecuzione del file di script corrente. Nel caso in cui il file di script corrente sia un file chiamato da include() o require(), il controllo viene passato al file chiamante. Ciononostante, se il file di script corrente è un file chiamato da include(), allora il valore dato da return() verrà restituito come valore della chiamata include(). Se viene chiamato return() all'interno del file di script principale, allora l'esecuzione dello script terminerà. Se il file di script corrente è stato nominato da auto_prepend_file o auto_append_file con le opzioni di configurazione nelphp.ini, allora l'esecuzione di quello script termina.
Per maggiori informazioni, consultare Valori restituiti.
Nota: Notate che poichè return() è un costrutto di linguaggio e non una funzione, le parentesi che circondano i suoi argomenti sono soltanto richieste se l'argomento contiene un'espressione. E' comune non utilizzarle quando si ritorna una variabile, ed inoltre il PHP ha meno lavoro da svolgere in questo caso.
Nota: Non si dovrebbe mai utilizzare le parantesi intorno alle variabili restituite quando sono restituite per riferimento, poichè non funzionerebbe. Per riferimento si possono restituire solo variabili, non il risultato di un'istruzione. Se si utilizza return ($a); non si restituisce una variabile, ma il risultato dell'espressione ($a) (che, ovviamente, è il valore di $a).
L'istruzione require() include e valuta il file specifico.
require() include e valuta uno specifico file. Informazioni dettagliate su come funziona quest'inclusione sono descritte nella documentazione di include().
require() e include() sono identiche in ogni senso eccetto per come esse trattano gli errori. include() produce un Warning mentre require() restituisce un Fatal Error. In altre parole, non esitate ad usare require() se volete che un file mancante fermi l'esecuzione della pagina. include() non si comporta in questo modo, lo script continuerà nonostante tutto. Assicuratevi di avere un appropriato include_path impostato a dovere.
Esempio 16-4. Esempio di base con require()
|
Vedere la documentazione di include() per più esempi.
Nota: Prima di PHP 4.0.2, si applica la seguente logica: require() tenterà sempre di leggere il file chiamato, anche se la riga su cui si trova non verrà mai eseguita. L'istruzione condizionale non avrà effetto su require(). Comunque, se la riga su cui si verifica require() non viene eseguita, non sarà eseguito nemmeno il codice del file incluso. Similmente, le strutture cicliche non avranno effetto sul comportamento di require(). Sebbene il codice contenuto nel file incluso è ancora soggetto a ciclo, require() stesso si verifica solo una volta.
Nota: Poichè questo è un costrutto del linguaggio e non una funzione, non può essere chiamato con le variabili funzione
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
Vedere anche include(), require_once(), include_once(), eval(), file(), readfile(), virtual() e include_path.
L'istruzione include() include e valuta il file specificato.
La documentazione seguente si applica anche a require(). I due costrutti sono identici in ogni aspetto eccetto per come essi trattano gli errori. include() produce un Warning mentre require() restituisce un Fatal Error. In altre parole, usate require() se volete che un file mancante fermi l'esecuzione della pagina. include() non si comporta in questo modo, lo script continuerà nonostante tutto. Assicuratevi di avere un appropriato include_path impostato a dovere. Attenzione che nelle versioni di PHP antecedenti la release 4.3.5 errori di parsing nei file inclusi non bloccavano l'esecuzione. Da questa versione lo fanno.
I file da includere sono prima cercati nella include_path relativa rispetto alla directory di lavoro e quindi nella include_path relativa alla directory dello script. Ad esempio, se la include_path è impostata a ., e la directory di lavoro corrente è /www/, si può includere include/a.php e qui vi è include "b.php", il file b.php verrà prima cercato in /www/ e quindi in /www/include/. Se il nome del file inizia con ../, viene cercato solo nella include_path relativa alla directory di lavoro corrente.
Quando un file viene incluso, il codice che esso contiene eredita lo scope delle variabili della riga in cui si verifica l'inclusione. Qualsiasi variabile disponibile in quella riga nella chiamata al file sarà disponibile all'interno del file chiamato, da quel punto in avanti. Tuttavia tutte le funzioni a le classi definite all'interno di un file di include hanno visibilità glibale.
Esempio 16-5. Esempio di base con include()
|
Se l'inclusione si verifica dentro una funzione all'interno del file chiamato, allora tutto il codice contenuto nel file chiamato si comporterà come se esso sia stato definito all'interno di una funzione. Così, esso seguirà lo scope delle variabili di quella funzione.
Esempio 16-6. Inclusione all'interno di funzioni
|
Quando un file viene incluso, il parsing esce dalla modalità PHP e entra in modalità HTML all'inizio del file incluso, e riprende alla fine. Per questa ragione, qualunque codice all'interno del file incluso che dovrebbe essere eseguito come codice PHP deve essere incluso all'interno dei tag PHP validi di apertura e chiusura.
Se "URL fopen wrappers" nel PHP sono abilitati (come nella configurazione di default), potete specificare il file da includere usando un URL (via HTTP o altri wrapper supportati - vedere Appendice M per avere la lista dei protocolli supportati ) invece che un percorso locale. Se il server chiamato interpreta il file incluso come codice PHP, le variabili possono essere passate al file incluso usando una stringa di richiesta URL come con l'utilizzo di HTTP GET. Non è proprio parlare della stessa cosa includere il file e averlo ereditato dallo scope di variabili del file chiamante; lo script è stato attualmente eseguito su un server remoto e il risultato è poi stato incluso nello script locale.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
Esempio 16-7. include() attraverso HTTP
|
Poichè include() e require() sono speciali costrutti di linguaggio, dovete includerli all'interno di blocchi di istruzioni se si trovano in un blocco condizionale.
Trattamento dei valori restituiti: È possibile eseguire un'istruzione return() in un file incluso per terminare l'esecuzione di quel file e restituirlo allo script che l'ha chiamato. È anche possibile restituire valori dai file inclusi. Potete prendere il valore di una chiamata di inclusione come fareste con una normale funzione. Tuttavia questo non è possibile quando si include file remoti, a meno che l'output del file remoto non contenga tag di inizio e fine codice validi in PHP (come i file locali). Si possono dichiarare variabili all'interno di questi tag e queste saranno inserite nel punto in cui il file è stato incluso.
Poichè include() è un costrutto del linguaggio speciale, non richiede le parentesi per i propri argomenti. Fare attenzione quando lo si confronta i valori restituiti.
Nota: In PHP 3, return potrebbe non apparire in un blocco a meno che esso sia un blocco di funzione, nel qual caso return() si applica a quella funzione e non all'intero file.
$bar ha valore 1 perchè l'inclusione è stata eseguita con successo. Notare la differenza tra gli esempi sopra. Il primo usa return() all'interno di un file incluso mentre l'altro no. Se il file non può essere incluso la funzione restituisce FALSE e genera un messaggio di E_WARNING
Se esistono funzioni definite nel file di include, queste possono essere utilizzate nel file principale a prescindere se esse siano prima o dopo il return(). Se un file viene incluso due volte, il PHP 5 genera un errore fatale, poichè le funzioni sono già dichiarate, mentre il PHP 4 non considera le funzioni dichiarate dopo il return(). Si raccomanda di utilizzare include_once() invece di verificare se un file è già stato incluso ed uscire tramite condizione dal file incluso.
Un'altro metodo per "includere" file PHP in una variabile consiste nel catturarne l'output tramite le funzioni di controllo dell'output ed include(). Ad esempio:
Esempio 16-11. Utilizzo del buffering dell'output per inserire un file PHP in una stringa
|
Per includere automaticamente dei file negli script vedere i parametri auto_prepend_file e auto_append_file nel php.ini.
Nota: Poichè questo è un costrutto del linguaggio e non una funzione, non può essere chiamato con le variabili funzione
Vedere anche require(), require_once(), include_once(), readfile(), virtual(), e include_path.
L'istruzione require_once() include e valuta il file specificato durante l'esecuzione dello script. È un comportamento simile all'istruzione require(), con la sola differenza che se il codice di un file è stato già incluso, esso non sarà incluso nuovamente. Vedere la documentazione di require() per maggiori informazioni su come funziona quest'istruzione.
require_once() dovrebbe essere usato nei casi dove lo stesso file potrebbe essere incluso e valutato più di una volta durante una particolare esecuzione di uno script, e volete essere sicuri che esso sia incluso esattamente una volta per evitare problemi con la ridefinizione di funzioni, riassegnazione di valori a variabili, etc.
Per esempi sull'utilizzo di require_once() e include_once(), consultare il codice PEAR incluso nell'ultima distribuzione del codice sorgente di PHP.
Il valore restituito è simile a include(). Se il file è già stato incluso, la funzione restituisce TRUE.
Nota: require_once() è stato aggiunto in PHP 4.0.1pl2
Nota: Fare attenzione al fatto che il comportamento di require_once() e include_once() può non essere quello atteso in sistemi che non distinguono le maiuscole dalle minuscole (tipo Windows).
Questo comportamento è stato modificato in PHP 5 - il percorso viene normalizzato, in modo tale che C:\PROGRA~1\A.php diventa simile a C:\Program Files\a.php e quindi il file vine incluso solo una volta.
Esempio 16-12. require_once() non distingue tra maiuscole e minuscole in Windows
<?php require_once("a.php"); // questo include include a.php require_once("A.php"); // questo include a.php ancora, in Windows! (solo PHP 4) ?>
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
Vedere anche: require(), include(), include_once(), get_required_files(), get_included_files(), readfile() e virtual().
L'istruzione include_once() include e valuta il file specificato durante l'esecuzione dello script. È un comportamento simile all'istruzione include(), con la sola differenza che se il codice di un file è stato già incluso, esso non sarà incluso nuovamente. Come suggerisce il nome, esso sarà incluso solo una volta.
include_once() dovrebbe essere usato nei casi dove lo stesso file potrebbe essere incluso e valutato più di una volta durante una particolare esecuzione di uno script, e volete essere sicuri che esso sia incluso esattamente una volta per evitare problemi con la ridefinizione di funzioni, riassegnazione di valori a variabili, etc.
Per maggiori esempi sull'utilizzo di require_once() e include_once(), consultare il codice PEAR incluso nell'ultima distribuzione del codice sorgente di PHP.
Il valore restituito è il simile a include(). Se il file è già stato incluso, la funzione restituisce TRUE.
Nota: include_once() è stato aggiunto in PHP 4.0.1pl2
Nota: Fare attenzione al fatto che il comportamento di include_once() e require_once() può non essere quello atteso in sistemi che non distinguono le maiuscole dalle minuscole (tipo Windows).
Questo comportamento è stato modificato in PHP 5 - il percorso viene normalizzato, in modo tale che C:\PROGRA~1\A.php diventa simile a C:\Program Files\a.php e quindi il file vine incluso solo una volta.
Esempio 16-13. include_once() non distingue tra maiuscole e minuscole in Windows
<?php include_once("a.php"); // questo include include a.php include_once("A.php"); // questo include a.php ancora, in Windows! (solo PHP 4) ?>
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
Vedere anche include(), require(), require_once(), get_required_files(), get_included_files(), readfile() e virtual().
Una funzione può essere definita usando la seguente sintassi:
All'interno di una funzione può apparire qualunque codice PHP valido, persino altre funzioni e definizioni di classe.
In PHP 3, le funzioni devono essere definite prima di essere referenziate. Non esiste nessun requisito in PHP 4. Tranne quando una funzione è definita condizionalmente come illustrato nei due esempi seguenti.
Quando una funzione è definita in modo condizionale, come illustrato nei seguenti esempi, occorre che ne venga processata prima la definizione poi venga chiamata la funzione stessa.
Esempio 17-2. Funzioni condizionali
|
Esempio 17-3. Funzioni dentro a funzioni
|
Tutte le funzioni e le classi, in PHP, hanno visibilità globale - possono essere chiamate dall'esterno di una funzione anche se sono definite all'interno di questa e vice-versa.
PHP non supporta l'overloading di funzioni, non è possibile indefinire o ridefinire funzioni precedentemente dichiarate.
Nota: I nomi delle funzioni non distinguono tra maiuscolo e minuscolo, ma, solitamente, è buona norma richiamare le funzioni nel modo con cui sono state definite.
PHP 3 non supporta un numero variabile di argomenti per le funzioni, sebbene siano supportati gli argomenti di default (vedere Argomenti con valori di default per maggiori informazioni). PHP 4 li supporta entrambi: vedere Liste di argomenti a lunghezza variabile e i riferimenti alle funzioni func_num_args(), func_get_arg() e func_get_args() per maggiori informazioni.
In PHP è possibile utilizzare le chiamate ricorsive. Tuttavia si consiglia di evitare funzioni/metodi ricorsivi profondi oltre 100-200 livelli, potrebbero riempire lo stack e bloccare l'esecuzione dello script.
L'informazione può essere passata alle funzioni tramite la lista degli argomenti, che sono liste di espressioni delimitati dalla virgola.
PHP supporta il passaggio di argomenti per valore (comportamento di default), il passaggio per riferimento, e i valori di default degli argomenti. Le liste di argomenti di lunghezza varabile sono supportate solo in PHP 4 e successivi; vedere Liste di argomenti a lunghezza variabile e i riferimenti alle funzioni func_num_args(), func_get_arg(), e func_get_args() per maggiori informazioni. Un effetto simile può essere ottenuto in PHP 3 passando una array di argomenti alla funzione.
Di default, gli argomenti della funzione sono passati per valore (così se cambiate il valore dell'argomento all'interno della funzione , esso non cambierà fuori della funzione). Se volete permettere ad una funzione di modificare i suoi argomenti, dovete passarli per riferimento.
Se volete che una argomento sia passato sempre per riferimento ad una funzione, dovete anteporre un ampersand (&) al nome dell'argomento nella definizione della funzione:
Una funzione può definire valori predefiniti in stile C++ per argomenti scalari come segue:
L'output dal frammento di sopra è:
Sto facendo una tazza di cappuccino. Sto facendo una tazza di espresso. |
Anche il PHP permette di utilizzare matrici ed il tipo speciale NULL come valore di default, ad esempio:
Esempio 17-8. Utilizzo di tipi non scalari come valori di default
|
Il valore predefinito deve essere un'espressione costante, non (per esempio) una variabile, un membro di classe o una chiamata ad una funzione.
Da notare che quando vengono usati argomenti predefiniti, qualunque argomento predefinito dovrebbe essere a destra degli argomenti non-predefiniti; diversamente, le cose non funzioneranno come ci si aspetti. Si consideri il seguente frammento di codice:
L'output dell'esempio di sopra è:
Warning: Missing argument 2 in call to fare_lo_yogurt() in /usr/local/etc/httpd/htdocs/php3test/functest.html on line 41 Fare una vaschetta di fragola a. |
Ora, si confronti il codice di sopra con questo:
L'output di questo esempio è:
Fare una vaschetta di yogurt a fragola. |
Nota: Dal PHP 5 i valori di default possono essere passati per riferimento.
PHP 4 ha il supporto per le liste di argomenti a lunghezza variabile nelle funzioni definite dall'utente. Ciò è realmente abbastanza semplice, usando le funzioni func_num_args(), func_get_arg(), e func_get_args().
Non è richiesta una speciale sintassi, e le liste di argomenti possono ancora essere provviste esplicitamente con le definizioni di funzioni e si comporteranno normalmente.
I valori vengono restituiti usando l'istruzione opzionale return. Può essere restituito qualsiasi tipo, incluse liste ed oggetti. Ciò provoca l'interruzione dell'esecuzione della funzione immediatamente e la restituzione del controllo alla linea da cui è stata chiamata. Vedere return() per maggiori informazioni.
Esempio 17-11. Esempio di uso di return()
|
Non possono essere restituiti valori multipli da una funzione, ma risultati simili possono essere ottenuti restituendo una lista.
Per restituire un riferimento da una funzione, è necessario usare l'operatore di passaggio per riferimento & in entrambe le dichiarazioni di funzioni e quando viene assegnato il valore restituito ad una variabile:
Per maggiori informazioni sui riferimenti, consultare References Explained.
PHP supporta il concetto di funzioni variabili. Ciò significa che se un nome di variabile ha le parentesi accodate ad esso, PHP cercherà una funzione con lo stesso nome del valore della variabile, e cercherà di eseguirla. Tra le altre cose, ciò puo essere usato per implementare delle callbacks, tabelle di funzioni e così via.
Le funzioni variabili non funzionano con costrutti di linguaggio come echo(), print(), unset(), isset(), empty(), include(), require() e like. Occorre costruire una propria funzione per utilizzare questi costrutti come variabili per funzioni.
Esempio 17-14. Esempio di funzioni variabili
|
Tramite le funzioni variabili si può eseguire anche metodi di oggetti.
Vedere anche call_user_func(), variabili variabili e function_exists().
Il PHP possiede diverse funzioni e costrutti standard. Esistono, inoltre, funzioni che richiedono la compila di specifici moduli del PHP, altrimenti si ottiene l'errore "undefined function" errors. Ad esempio, per utilizzare le funzioni image, tipo imagecreatetruecolor(), occorre che il PHP sia compilato con il supporto GD. Oppure, per utilizzare mysql_connect() occorre che il PHP sia compilato con il supporto per MySQL Esistono anche diversi funzioni di base incluse in ogni versione del PHP tipo le funzioni stringa e per variabili. L'esecuzione di phpinfo() o di get_loaded_extensions() visualizzerà quali moduli sono caricati nel PHP. Inoltre si noti che diverse estensioni sono abilitate per default e che il manule PHP è suddiviso per estensione. Vedere i capitoli configurazione, installazione, ed i capitoli dei singoli moduli per avere maggiori dettagli su come configurare il PHP.
Come leggere e comprendere il prototipo di una funzione è spiegato nella sezione del manuale intitolata come leggere la definizione di una funzione. E' importante comprendere che cosa restituisce una funzione o se una funzione lavora direttamente sui dati passati. Ad esempio str_replace() restituisce la stringa modificata, mentre usort() lavora sulla variabile passata. Ciascuna pagina del manuale fornisce informazioni specifiche per ogni funzione tipo notizie sui parametri, modifiche di funzinamento, valori restituiti in caso di successo o di errore, ed altre informazioni disponibili. La conoscenza di queste differenze importanti è cruciale per la scrittura di codice PHP corretto.
Vedere anche function_exists(), the function reference, get_extension_funcs(), e dl().
Una classe è una collezione di variabili e funzioni che utilizzano queste variabili. Una classe si definisce usando la seguente sintassi:
<?php class Cart { var $items; // Articoli nel carrello // Aggiunge $num articoli di $artnr nel carrello function add_item ($artnr, $num) { $this->items[$artnr] += $num; } // Prende $num articoli di $artnr e li rimuove dal carrello function remove_item ($artnr, $num) { if ($this->items[$artnr] > $num) { $this->items[$artnr] -= $num; return true; } elseif ($this->items[$artnr] == $num) { unset($this->items[$artnr]); return true; } else { return false; } } } ?> |
Il codice definisce una classe chiamata Cart composta da un array associativo che archivia gli articoli nel carrello e due funzioni per aggiungere e rimuovere gli articoli dal carrello stesso.
Avvertimento |
NON spezzate una definizione di classe in più file o in più blocchi PHP. Si può anche EVITARE di spezzare la definizione di una classe in più blocchi PHP, a meno che la suddivisione non sia all'interno della dichiarazione di un metodo. Il seguente codice non funziona:
Tuttavia è permessa la seguente struttura:
|
Le seguenti note cautelative sono valide per PHP 4.
Attenzione |
Il nome stdClass è usato esclusivamente da Zend ed è riservato. Non è quindi possibile creare una classe chiamata stdClass in PHP. |
Attenzione |
I nomi di funzione __sleep e __wakeup sono riservati e magici nelle classi PHP. Non è possibile creare funzioni con questi nomi nelle classi definite dall'utente, a meno che non sia desiderata la funzionalità magica connessa a questi nomi. Si veda sotto per avere più informazioni. |
Attenzione |
PHP riserva tutti i nomi di funzione che iniziano con __ a funzioni magiche. Si suggerisce di non usare nomi di funzioni che utilizzano con i caratteri __ in PHP a meno che non si desideri implementare una funzionalità magica. |
In PHP 4, sono permesse inizializzazioni di variabili con valori costanti solamente grazie all'uso di var. Per inizializzare variabili con valori non-costanti, bisogna creare una funzione d'inizializzazione che è chiamata automaticamente all'istanziazione di un oggetto da una classe. Questo tipo di funzione si chiama costruttore (vedi sotto).
<?php class Cart { /* questo non funziona in PHP 4. */ var $todays_date = date("Y-m-d"); var $name = $firstname; var $owner = 'Fred ' . 'Jones'; /* E' permesso l'uso di matrici contenenti costanti */ var $items = array("VCR", "TV"); } /* Questo è corretto. */ class Cart { var $todays_date; var $name; var $owner; var $items; var $items = array("VCR", "TV"); function Cart() { $this->todays_date = date("Y-m-d"); $this->name = $GLOBALS['firstname']; /* etc ... */ } } ?> |
Le classi sono tipi del linguaggio, e sono modelli per variabili reali. Per creare una variabile oggetto si usa l'operatore new.
<?php $cart = new Cart; $cart->add_item("10", 1); $another_cart = new Cart; $another_cart->add_item("0815", 3); ?> |
Il codice sopra, genera gli oggetti $cart e $another_cart, dalla classe Cart. La funzione add_item() dell'oggetto $cart è chiamata per aggiungere una ricorrenza dell'articolo numero 10 a $cart. Ad $another_cart sono aggiunte 3 ricorrenze dell'articolo numero 0815.
Sia $cart che $another_cart dispongono delle funzioni add_item(), remove_item() e della variabile $items, ma per ogni oggetto queste sono funzioni e variabili sono distinte. Potete pensare agli oggetti come a qualcosa di simile alle directories di un filesystem. In un filesystem si possono avere due diversi files README.TXT, purchè siano in directories differenti. Così come in un filesystem dovete digitare il nome (percorso) completo per raggiungere un determinato file partendo da una directory toplevel, così dovete specificare il nome completo di una funzione o variabile che desiderate richiamare da un oggetto. Per PHP, la directory toplevel è il namespace globale dell'oggetto ed il separatore del pathname (/) è ->. Così $cart->items e $another_cart->items sono due diverse variabili che differiscono per il nome. Si noti che la variabile si chiama $cart->items, e non $cart->$items, questo perchè le variabili il PHP si scrivono con un unico simbolo di dollaro.
<?php // corretto con un singolo $ $cart->items = array("10" => 1); // non valido, perchè $cart->$items diventa $cart->"" $cart->$items = array("10" => 1); // corretto, ma non sempre può funzionare: // $cart->$myvar diventa $cart->items $myvar = 'items'; $cart->$myvar = array("10" => 1); ?> |
Quando si definisce una classe, non è possibile prevedere quale nome avrà l'oggetto istanziato nel programma. Quando la classe Cart è stata scritta, non si poteva prevedere che l'oggetto istanziato da essa si sarebbe potuto chiamare $cart o $another_cart. Quindi non è possibile scrivere $cart->items all'interno della classe Cart in fase di progettazione. Per poter accedere alle funzioni e alle variabili interne di una classe perciò si usa la pseudo-variabile $this che può essere letta come 'la mia\il mio' o 'di questo oggetto'. Quindi, '$this->items[$artnr] += $num' può essere letto come 'aggiungi $num al contatore $artnr al del mio array degli articoli' o 'aggiungi $num al contatore $artnr dell'array degli articoli di questo oggetto'.
Nota: La pseudo variabile $this di norma non è definita se il metodo in cui è utilizzata è richiamato staticamente. Tuttavia questa non è la regola: $this è definita se il metodo è chiamato staticamente da un'altro oggetto. In questo caso il valore di $this è l'oggetto chiamante. Tutto ciò viene illustrato dal seguente esempio:
<?php class A { function foo() { if (isset($this)) { echo '$this is defined ('; echo get_class($this); echo ")\n"; } else { echo "\$this is not defined.\n"; } } } class B { function bar() { A::foo(); } } $a = new A(); $a->foo(); A::foo(); $b = new B(); $b->bar(); B::bar(); ?>Il precedente esempio visualizzerà:
$this is defined (a) $this is not defined. $this is defined (b) $this is not defined.
Nota: Ci sono molte utili funzioni per manipolare classi ed oggetti. Se desiderate conoscerle potete dare un'occhiata alle Class/Object Functions.
Spesso si ha bisogno di avere classi con variabili e funzioni simili ad altre classi. É buona norma definire una classe in modo generico, sia per poterla riutilizzare spesso, sia per poterla adattare a scopi specifici.Per facilitare questa operazione, è possibile generare classi per estensione di altre classi. Una classe estesa o derivata ha tutte le variabili e le funzioni della classe di base (questo fenomeno è chiamato 'eredità', anche se non muore nessuno) più tutto ciò che viene aggiunto dall'estensione. Non è possibile che una sottoclasse, ridefinisca variabili e funzioni di una classe madre. Una classe estesa dipende sempre da una singola classe di base: l'eredità multipla non è supportata. Le classi si estendono usando la parola chiave 'extends'.
<?php class Named_Cart extends Cart { var $owner; function set_owner ($name) { $this->owner = $name; } } ?> |
Qui viene definita una classe Named_Cart che ha tutte le funzioni e variabili di Cart più la variabile $owner e la funzione set_owner(). Viene creato un carrello con nome con il metodo usato in precedenza, in più la classe estesa permette di settare o leggere il nome del carrello. Si possono usare variabili e funzioni sia di Cart che della sua estensione:
<?php $ncart = new Named_Cart; // Crea un carrello con nome $ncart->set_owner("kris"); // Assegna il nome al carrello print $ncart->owner; // stampa il nome del proprietario $ncart->add_item("10", 1); // (funzionalità ereditata da Cart) ?> |
La relazione mostrata è chiamata relazione "genitore-figlio". Si crea una classe di base, poi utilizzando extends si crea una nuova classe basata sulla classe genitore: la classe figlia. Successivamente si può usare la classe figlia come classe base per un'altra classe.
Nota: Una classe deve essere definita prima di essere utilizzata! Se si vuole la classe Named_Cart che estende la classe Cart, bisogna definire una classe Cart prima. Se si vuole creare un'altra classe chiamata Yellow_named_cart basata sulla classe Named_Cart bisogna definire la classe Named_Cart prima. Per farla breve: l'ordine di definizione delle classi è importante.
I costruttori sono funzioni che esistono in una classe e che sono chiamate automaticamente quando si crea una nuova istanza di una classe con new. In PHP 4, una funzione diventa un costruttore, quando ha lo stesso nome della classe. Se una classe non ha costruttore, allora si richiama il costruttore della classe base, se esiste.
Questo codice definisce una classe Auto_Cart, che non è altro che Cart più un costruttore che inizializza il carrello con una occorrenza dell'articolo numero "10" ogni volta che un nuovo Auto_Cart è creato con "new". I costruttori possono avere degli argomenti, e gli argomenti possono essere facoltativi, questo li rende molto versatili. Per poter usare una classe senza specificare parametri, tutti i parametri del costruttore devono essere resi facoltativi con valori di default.
<?php class Constructor_Cart extends Cart { function Constructor_Cart($item = "10", $num = 1) { $this->add_item ($item, $num); } } // Istanzia il vecchio e noioso carrello. $default_cart = new Constructor_Cart; // Un carrello nuovo ... $different_cart = new Constructor_Cart("20", 17); ?> |
E possibile utilizzare l'operatore @ per inibire gli errori provocati dal costruttore, es: @new.
<?php class A { function A() { echo "Sono il costtruttore di A.<br />\n"; } function B() { echo "Sono una normale funzione di nome B della classe A.<br>\n"; echo "Non sono il costruttore di A.<br>\n"; } } class B extends A { } // This will call B() as a constructor. $b = new B; ?> |
La funzione B() della classe A si transformerà improvvisamente in un costruttore per la classe B, anche se questo non era previsto. PHP 4 non si preoccupa se la funzione è stata definita nella classe B o se è stata ereditata.
Attenzione |
Il PHP 4 non richiama i costruttori di una classe base automaticamente da un costruttore di una classe derivata. È responsabilità del programmatore propagare la chiamata ai costruttori dove è necessario. |
I distruttori sono funzioni che sono chiamate automaticamente quando una variabile è distrutta con unset() o semplicemente uscendo dal suo ambito. Non ci sono distruttori in PHP. Si può utilizzare register_shutdown_function() per simulare gli effetti del distruttore.
Attenzione |
Ciò che segue è valido soltanto per PHP 4. |
A volte è utile riferirsi alle funzioni ed alle variabili di classi base o riferirsi alle funzioni di classi senza istanziarle. L'operatore :: è usato per questi scopi.
<?php class A { function example() { echo "Sono la funzione originale A::example().<br />\n"; } } class B extends A { function example() { echo "Sono la funzione ridefinita B::example().<br />\n"; A::example(); } } // non viene istanziato nessun oggetto dalla classe A. // ma il codice stampa // Sono la funzione originale A::example().<br /> A::example(); // crea un oggetto dalla classe B. $b = new B; // questo codice stampa // Sono la funzione ridefinita B::example().<br /> // Sono la funzione originale A::example().<br /> $b->example(); ?> |
L'esempio chiama la funzione example() della classe A, ma senza creare un'istanza di A, di modo che la funzione non si possa richiamare con $a->example(). example() è chiamata come 'funzione della classe', e non come funzione di un oggetto della classe.
Si possono usare funzioni della classe, ma non le variabili della classe. Infatti, non esiste nessun oggetto nel momento della chiamata della funzione. Quindi, la funzione della classe non può usare le variabili dell'oggetto (ma può usare le variabili locali e globali) e $this non può essere usato.
Nel suddetto esempio, la classe B ridefinisce la funzione example(). La funzione originale definita nella classe A è adombrata e non più disponibile, a meno che voi non chiamiate esplicitamente con l'operatore :: scrivendo A::example() per richiamare la funzione (è possibile anche scrivere parent::example(), come mostra la sezione seguente).
In questo contesto, c'è un oggetto corrente che può avere determinate variabili. Una volta usate da parte di una funzione dell'oggetto, potete usare $this per le variabili dell'oggetto.
E possibile ritrovarsi a scrivere classi con codice che si riferisce a variabili e funzioni di classi base. Ciò è particolarmente VERO se una classe derivata è un perfezionamento o una specializzazione di una classe base.
Invece di usare il nome letterale della classe, bisognerebbe usare il nome speciale parent, che si riferisce al nome della classe base definita nella dichiarazione di extends. Usando questo metodo, si evita di usare il nome della classe base nel codice scritto. Se l'albero di eredità cambiasse durante lo sviluppo della classe, il cambiamento si ridurrebbe semplicemente alla modifica della dichiarazione extends della classe.
<?php class A { function example() { echo "Sono A::example() e fornisco una funzionalità di base.<br />\n"; } } class B extends A { function example() { echo "Sono B::example() e fornisco una funzionalità aggiuntiva.<br />\n"; parent::example(); } } $b = new B; // Il codice chiama B::example(), che a sua volta chiama A::example(). $b->example(); ?> |
Nota: In PHP 3, gli oggetti perdono la loro associazione di classe durante il processo di serializzazione e di deserializzazione. La variabile risultante è di tipo oggetto, ma non ha classe e metodi, e diventa inutile (come un buffo array).
Attenzione |
Le seguenti informazioni sono valide soltanto per PHP 4. |
serialize() restituisce una stringa che contiene una rappresentazione byte-stream di tutti i valori che possono essere memorizzati in PHP. unserialize() può usare questa stringa per ricreare i valori variabili utilizzabili. Usando serialize() per salvare un oggetto si salveranno tutte le variabili dell'oggetto. Le funzioni dell'oggetto non sono salvate, viene salvato solo il nome della classe.
Per potere usare unserialize() su un oggetto, la classe dell'oggetto deve essere definita. Cioè se avete un oggetto $a della classe A su una pagina di nome page1.php e usate serialize(), otterrete una stringa che si riferisce alla classe A e contiene tutti i valori delle variabili contenute in $a. Se desiderate potere deserializzare l'oggetto in un'altra pagina chiamata page2.php, dovete ricreare $a dalla classe A, la definizione della classe A perciò deve essere presente nella pagina page2.php. Questo può essere fatto per esempio memorizzando la definizione della classe A in un file che viene incluso sia in page1.php che in page2.php.
<?php // classa.inc: class A { var $one = 1; function show_one() { echo $this->one; } } // page1.php: include("classa.inc"); $a = new A; $s = serialize($a); // memorizzare $s in qualche posto della page2. $fp = fopen("store", "w"); fwrite($fp, $s); fclose($fp); // page2.php: // questo è necessario perchè unserialize() funzioni correttamente. include("classa.inc"); $s = implode("", @file("store")); $a = unserialize($s); // ora usiamo la function show_one() dell'oggetto $a. $a->show_one(); ?> |
Se state usando le sessioni ed usate session_register() per registrare oggetti, questi oggetti vengono serializzati automaticamente alla fine di ogni pagina PHP e sono deserializzate automaticamente su ogni pagina della sessione. Ciò significa che gli oggetti possono mostrarsi in ogni pagina e che sono parte integrante della sessione.
Si suggerisce vivamente di includere le definizioni delle classi degli oggetti registrati su tutte le pagine, anche se le classi non sono usate su tutte le pagine. Se un oggetto viene deserializzato senza la relativa definizione della classe, perderà l'associazione ad essa e si transformerà in in un oggetto della classe stdClass senza nessuna funzione disponibile, diventando inutile.
Così se nell'esempio qui sopra $a diventasse parte di una sessione e fosse registrato con session_register("a"), dovreste includere un file classa.inc su tutte le pagine in cui è valida la sessione, non soltanto nella page1.php e nella page2.php.
serialize() controlla se la vostra classe ha una funzione dal nome magico __sleep. In caso affermativo, quella funzione viene eseguita prima di qualsiasi serializzazione. La funzione può pulire l'oggetto e restituire un array con i nomi di tutte le variabili di quell' oggetto che dovrebbero essere serializzate.
Si intende usare __sleep quando chiudendo un collegamento ad un database l'oggetto può avere dati pendenti e l'oggetto ha bisogno di essere ripulito. Inoltre, la funzione è utile se avete oggetti molto grandi che non devono essere salvati completamente.
Per contro, unserialize() controlla per vedere se c'è nella classe una funzione dal nome magico __wakeup. Se è presente questa funzione può ricostruire qualunque risorsa che l'oggetto aveva.
L'intento di __wakeup è quello di ristabilire le connessioni ai database che possono esser state persi durante la serializzazione ed effettuare altre mansioni reinizializzazione.
La creazione di riferimenti con costruttori può condurre a risultati confusi. Questa sezione in stile Tutorial vi aiuterà ad evitare problemi.
<?php class Foo { function Foo($name) { // crea un riferimento all'interno della variabile $globalref global $globalref; $globalref[] = &$this; // setta Name con il valore passato $this->setName($name); // e lo manda all'output $this->echoName(); } function echoName() { echo "<br>",$this->name; } function setName($name) { $this->name = $name; } } ?> |
Verifichiamo se c'è una differenza fra $bar1 che è stato creato usando l'operatore = e $bar2 che è stato creato usando l'operatore di riferimento =& ...
<?php $bar1 = new Foo('set in constructor'); $bar1->echoName(); $globalref[0]->echoName(); /* output: imposta nel costruttore imposta nel costruttore imposta nel costruttore */ $bar2 =& new Foo('set in constructor'); $bar2->echoName(); $globalref[1]->echoName(); /* output: imposta nel costruttore imposta nel costruttore imposta nel costruttore */ ?> |
Apparentemente non c'è differenza, ed in effetti questo è molto significativo: $bar1 e $globalref[0] _ NON _ sono riferimenti, ma sono due variabili diverse. Questo succede perché "new" non restituisce per default un riferimento, ma restituisce una copia.
Nota: Non c'è perdita di prestazioni (da php 4 in su si usa il riferimento) ad istanziare copie per riferimento. Al contrario spesso è meglio lavorare con copie istanziate per riferimento, perché creare copie reali richiede un certo tempo, mentre creare riferimenti virtuali è immediato, (a meno che non si parli di un grande array o un oggetto che viene modificato in modo successivo, allora sarebbe saggio usare i riferimenti per cambiargli tutti i valori simultaneamente).
<?php // ora cambieremo il nome che cosa vi aspettate? // potreste prevedere che $bar e $globalref[0] cambino i loro nomi ... $bar1->setName('set from outside'); // come accennato prima ecco il risultato. $bar1->echoName(); $globalref[0]->echoName(); /* output: set from outside set in constructor */ // vediamo le differenze tra $bar2 e $globalref[1] $bar2->setName('set from outside'); // fortunatamen sono solo uguali, ma sono la stessa variabile // $bar2->name e $globalref[1]->name sono la stessa cosa $bar2->echoName(); $globalref[1]->echoName(); /* output: set from outside set from outside */ ?> |
Un esempio finale, prova a farvi capire.
<?php class A { function A($i) { $this->value = $i; // provare a capire perchè qui non abbiamo bisogno d'un riferimento $this->b = new B($this); } function createRef() { $this->c = new B($this); } function echoValue() { echo "<br />","class ",get_class($this),': ',$this->value; } } class B { function B(&$a) { $this->a = &$a; } function echoValue() { echo "<br />","class ",get_class($this),': ',$this->a->value; } } // prova a capire perchè usando una semplice copia si avrebbe // in un risultato indesiderato nella riga segnata con * $a =& new A(10); $a->createRef(); $a->echoValue(); $a->b->echoValue(); $a->c->echoValue(); $a->value = 11; $a->echoValue(); $a->b->echoValue(); // * $a->c->echoValue(); ?> |
Il precedente esempio visualizzerà:
class A: 10 class B: 10 class B: 10 class A: 11 class B: 11 class B: 11 |
In PHP 4, gli oggetti sono confrontati semplicemente, cioè: due istanze di oggetto sono uguali se hanno gli stessi attributi e valori, e sono istanze della stessa classe. Questa regola regola è applicata anche nel confronto di due oggetti utilizzando l'operatore di identità (===).
Eseguendo il codice seguente:
Esempio 18-1. Esempio di confronto di oggetti in PHP 4
Il precedente esempio visualizzerà:
|
Anche nei casi in cui l'oggetto è composto si applicano le stesse regole di confronto. Nell'esempio seguente creiamo una classe contenitore che archivia nell'array associativo Flag altri oggetti.
Esempio 18-2. Confronto di oggetti composti in PHP 4
Il precedente esempio visualizzerà:
|
In PHP 5 there is a new Object Model. PHP's handling of objects has been completely rewritten, allowing for better performance and more features.
Every class definition begins with the keyword class, followed by a class name, which can be any name that isn't a reserved word in PHP. Followed by a pair of curly braces, of which contains the definition of the classes members and methods. A pseudo-variable, $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but can be another object, if the method is called statically from the context of a secondary object). This is illustrated in the following example:
<?php class A { function foo() { if (isset($this)) { echo '$this is defined ('; echo get_class($this); echo ")\n"; } else { echo "\$this is not defined.\n"; } } } class B { function bar() { A::foo(); } } $a = new A(); $a->foo(); A::foo(); $b = new B(); $b->bar(); B::bar(); ?> |
Il precedente esempio visualizzerà:
$this is defined (a) $this is not defined. $this is defined (b) $this is not defined. |
To create an instance of an object, a new object must be created and assigned to a variable. An object will always be assigned when creating a new object unless the object has a constructor defined that throws an exception on error.
When assigning an already created instance of an object to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A new instance of an already created object can be made by cloning it.
Esempio 19-3. Object Assignment
Il precedente esempio visualizzerà:
|
A class can inherit methods and members of another class by using the extends keyword in the declaration. It is not possible to extend multiple classes, a class can only inherit one base class.
The inherited methods and members can be overridden, unless the parent class has defined a method as final, by redeclaring them within the same name defined in the parent class. It is possible to access the overrided method or members by referencing them with parent::
Esempio 19-4. Simple Class Inherintance
Il precedente esempio visualizzerà:
|
Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).
In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class which hasn't been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.
Nota: Exceptions thrown in __autoload function cannot be caught in the catch block and results in a fatal error.
PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.
Nota: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.
Esempio 19-6. using new unified constructors
|
For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.
PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed.
Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly call parent::__destruct() in the destructor body.
Nota: Destructor is called during the script shutdown so headers are always already sent.
Nota: Attempting to throw an exception from a desctructor causes a fatal error.
The visibility of a property or method can be defined by prefixing the declaration with the keywords: public, protected or private. Public declared items can be accessed everywhere. Protected limits access to inherited and parent classes (and to the class that defines the item). Private limits visibility only to the class that defines the item.
Class members must be defined with public, private, or protected.
Esempio 19-8. Member declaration
|
Nota: The PHP 4 method of declaring a variable with the var keyword is no longer valid for PHP 5 objects. For compatibility a variable declared in php will be assumed with public visibility, and a E_STRICT warning will be issued.
Class methods must be defined with public, private, or protected. Methods without any declaration are defined as public.
Esempio 19-9. Method Declaration
|
The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden members or methods of a class.
When referencing these items from outside the class definition, use the name of the class.
Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon. However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team decided to call it. It actually does mean double-colon - in Hebrew!
Two special keywords self and parent are used to access members or methods from inside the class definition.
When an extending class overrides the parents definition of a method, PHP will not call the parent's method. It's up to the extended class on whether or not the parent's method is called. This also applies to Constructors and Destructors, Overloading, and Magic method definitions.
Esempio 19-12. Calling a parent's method
|
Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can).
The static declaration must be after the visibility declaration. For compatibility with PHP 4, if no visibility declaration is used, then the member or method will be treated as if it was declared as public.
Because static methods are callable without an instance of the object created, the pseudo variable $this is not available inside the method declared as static.
In fact static method calls are resolved at compile time. When using an explicit class name the method is already identified completely and no inheritance rules apply. If the call is done by self then self is translated to the current class, that is the class the code belongs to. Here also no inheritance rules apply.
Static properties cannot be accessed through the object using the arrow operator ->.
Calling non-static methods statically generates an E_STRICT level warning.
Esempio 19-13. Static member example
|
It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don't use the $ symbol to declare or use them. Like static members, constant values cannot be accessed from an instance of the object (using $object::constant).
The value must be a constant expression, not (for example) a variable, a class member, result of a mathematical operation or a function call.
PHP 5 introduces abstract classes and methods. It is not allowed to create an instance of a class that has been defined as abstract. Any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature they cannot define the implementation.
When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or weaker) visibillity. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public.
Esempio 19-16. Abstract class example
Il precedente esempio visualizzerà:
|
Old code that has no user-defined classes or functions named 'abstract' should run without modifications.
Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.
Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.
All methods declared in an interface must be public, this is the nature of an interface.
To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.
Esempio 19-17. Interface example
|
See also the instanceof operator.
Both method calls and member accesses can be overloaded via the __call, __get and __set methods. These methods will only be triggered when your object or inherited object doesn't contain the member or method you're trying to access. All overloading methods must not be defined as static.
Since PHP 5.1.0 it is also possible to overload the isset() and unset() functions via the __isset and __unset methods respectively.
Class members can be overloaded to run custom code defined in your class by defining these specially named methods. The $name parameter used is the name of the variable that should be set or retrieved. The __set() method's $value parameter specifies the value that the object should set the $name.
Esempio 19-18. overloading with __get, __set, __isset and __unset example
Il precedente esempio visualizzerà:
|
Class methods can be overloaded to run custom code defined in your class by defining this specially named method. The $name parameter used is the name as the function name that was requested to be used. The arguments that were passed in the function will be defined as an array in the $arguments parameter. The value returned from the __call() method will be returned to the caller of the method.
Esempio 19-19. overloading with __call example
Il precedente esempio visualizzerà:
|
PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement. By default, all visible properties will be used for the iteration.
Esempio 19-20. Simple Object Iteration
Il precedente esempio visualizzerà:
|
As the output shows, the foreach iterated through all visible variables that can be accessed. To take it a step further you can implement one of PHP 5's internal interface named Iterator. This allows the object to decide what and how the object will be iterated.
Esempio 19-21. Object Iteration implementing Iterator
Il precedente esempio visualizzerà:
|
You can also define your class so that it doesn't have to define all the Iterator functions by simply implementing the PHP 5 IteratorAggregate interface.
Esempio 19-22. Object Iteration implementing IteratorAggregate
Il precedente esempio visualizzerà:
|
Nota: For more examples of iterators, see the SPL Extension.
Patterns are ways to describe best practices and good designs. They show a flexible solution to common programming problems.
The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for "manufacturing" an object.
Esempio 19-23. Factory Method
Defining this method in a class allows drivers to be loaded on the fly. If the Example class was a database abstraction class, loading a MySQL and SQLite driver could be done as follows:
|
The Singleton pattern applies to situations in which there needs to be a single instance of a class. The most common example of this is a database connection. Implementing this pattern allows a programmer to make this single instance easily accessible by many other objects.
Esempio 19-24. Singleton Function
This allows a single instance of the Example class to be retrieved.
|
The function names __construct, __destruct (see Constructors and Destructors), __call, __get, __set, __isset, __unset (see Overloading), __sleep, __wakeup, __toString, __clone and __autoload are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.
Attenzione |
PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality. |
serialize() checks if your class has a function with the magic name __sleep. If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized.
The intended use of __sleep is to close any database connections that the object may have, commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely.
Conversely, unserialize() checks for the presence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that the object may have.
The intended use of __wakeup is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.
Esempio 19-25. Sleep and wakeup
|
The __toString method allows a class to decide how it will react when it is converted to a string.
It is worth noting that the __toString method will only be called when it is directly combined with echo() or print().
Esempio 19-27. Cases where __toString is called
|
PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
Esempio 19-28. Final methods example
|
Esempio 19-29. Final class example
|
Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors, is if you have an object which represents a GTK window and the object holds the resource of this GTK window, when you create a duplicate you might want to create a new window with the same properties and have the new object hold the resource of the new window. Another example is if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy.
An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly.
When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references. If a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.
Esempio 19-30. Cloning an object
Il precedente esempio visualizzerà:
|
In PHP 5, object comparison is more complicated than in PHP 4 and more in accordance to what one will expect from an Object Oriented Language (not that PHP 5 is such a language).
When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.
On the other hand, when using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.
An example will clarify these rules.
Esempio 19-31. Example of object comparison in PHP 5
Il precedente esempio visualizzerà:
|
PHP 5 comes with a complete reflection API that adds the ability to reverse-engineer classes, interfaces, functions and methods as well as extensions. Additionally, the reflection API also offers ways of retrieving doc comments for functions, classes and methods.
The reflection API is an object-oriented extension to the Zend Engine, consisting of the following classes:
<?php class Reflection { } interface Reflector { } class ReflectionException extends Exception { } class ReflectionFunction implements Reflector { } class ReflectionParameter implements Reflector { } class ReflectionMethod extends ReflectionFunction { } class ReflectionClass implements Reflector { } class ReflectionObject extends ReflectionClass { } class ReflectionProperty implements Reflector { } class ReflectionExtension implements Reflector { } ?> |
Nota: For details on these classes, have a look at the next chapters.
If we were to execute the code in the example below:
Esempio 19-32. Basic usage of the reflection API
Il precedente esempio visualizzerà:
|
ReflectionException extends the standard Exception and is thrown by Reflection API. No specific methods or properties are introduced.
The ReflectionFunction class lets you reverse-engineer functions.
<?php class ReflectionFunction implements Reflector { final private __clone() public object __construct(string name) public string __toString() public static string export() public string getName() public bool isInternal() public bool isUserDefined() public string getFileName() public int getStartLine() public int getEndLine() public string getDocComment() public array getStaticVariables() public mixed invoke(mixed* args) public mixed invokeArgs(array args) public bool returnsReference() public ReflectionParameter[] getParameters() public int getNumberOfParameters() public int getNumberOfRequiredParameters() } ?> |
Nota: getNumberOfParameters() and getNumberOfRequiredParameters() were added in PHP 5.0.3, while invokeArgs() was added in PHP 5.1.0.
To introspect a function, you will first have to create an instance of the ReflectionFunction class. You can then call any of the above methods on this instance.
Esempio 19-33. Using the ReflectionFunction class
|
Nota: The method invoke() accepts a variable number of arguments which are passed to the function just as in call_user_func().
The ReflectionParameter class retrieves information about a function's or method's parameters.
<?php class ReflectionParameter implements Reflector { final private __clone() public object __construct(string name) public string __toString() public static string export() public string getName() public bool isPassedByReference() public ReflectionClass getClass() public bool isArray() public bool allowsNull() public bool isOptional() public bool isDefaultValueAvailable() public mixed getDefaultValue() } ?> |
Nota: getDefaultValue(), isDefaultValueAvailable() and isOptional() were added in PHP 5.0.3, while isArray() was added in PHP 5.1.0.
To introspect function parameters, you will first have to create an instance of the ReflectionFunction or ReflectionMethod classes and then use their getParameters() method to retrieve an array of parameters.
Esempio 19-34. Using the ReflectionParameter class
|
The ReflectionClass class lets you reverse-engineer classes.
<?php class ReflectionClass implements Reflector { final private __clone() public object __construct(string name) public string __toString() public static string export() public string getName() public bool isInternal() public bool isUserDefined() public bool isInstantiable() public bool hasConstant(string name) public bool hasMethod(string name) public bool hasProperty(string name) public string getFileName() public int getStartLine() public int getEndLine() public string getDocComment() public ReflectionMethod getConstructor() public ReflectionMethod getMethod(string name) public ReflectionMethod[] getMethods() public ReflectionProperty getProperty(string name) public ReflectionProperty[] getProperties() public array getConstants() public mixed getConstant(string name) public ReflectionClass[] getInterfaces() public bool isInterface() public bool isAbstract() public bool isFinal() public int getModifiers() public bool isInstance(stdclass object) public stdclass newInstance(mixed* args) public ReflectionClass getParentClass() public bool isSubclassOf(ReflectionClass class) public array getStaticProperties() public mixed getStaticPropertyValue(string name [, mixed default]) public void setStaticPropertyValue(string name, mixed value) public array getDefaultProperties() public bool isIterateable() public bool implementsInterface(string name) public ReflectionExtension getExtension() public string getExtensionName() } ?> |
Nota: hasConstant(), hasMethod(), hasProperty(), getStaticPropertyValue() and setStaticPropertyValue() were added in PHP 5.1.0.
To introspect a class, you will first have to create an instance of the ReflectionClass class. You can then call any of the above methods on this instance.
Esempio 19-35. Using the ReflectionClass class
|
Nota: The method newInstance() accepts a variable number of arguments which are passed to the function just as in call_user_func().
Nota: $class = new ReflectionClass('Foo'); $class->isInstance($arg) is equivalent to $arg instanceof Foo or is_a($arg, 'Foo').
The ReflectionMethod class lets you reverse-engineer class methods.
<?php class ReflectionMethod extends ReflectionFunction { public __construct(mixed class, string name) public string __toString() public static string export() public mixed invoke(stdclass object, mixed* args) public mixed invokeArgs(stdclass object, array args) public bool isFinal() public bool isAbstract() public bool isPublic() public bool isPrivate() public bool isProtected() public bool isStatic() public bool isConstructor() public bool isDestructor() public int getModifiers() public ReflectionClass getDeclaringClass() // Inherited from ReflectionFunction final private __clone() public string getName() public bool isInternal() public bool isUserDefined() public string getFileName() public int getStartLine() public int getEndLine() public string getDocComment() public array getStaticVariables() public bool returnsReference() public ReflectionParameter[] getParameters() public int getNumberOfParameters() public int getNumberOfRequiredParameters() } ?> |
To introspect a method, you will first have to create an instance of the ReflectionMethod class. You can then call any of the above methods on this instance.
Esempio 19-36. Using the ReflectionMethod class
|
Nota: Trying to invoke private, protected or abstract methods will result in an exception being thrown from the invoke() method.
Nota: For static methods as seen above, you should pass NULL as the first argument to invoke(). For non-static methods, pass an instance of the class.
The ReflectionProperty class lets you reverse-engineer class properties.
<?php class ReflectionProperty implements Reflector { final private __clone() public __construct(mixed class, string name) public string __toString() public static string export() public string getName() public bool isPublic() public bool isPrivate() public bool isProtected() public bool isStatic() public bool isDefault() public int getModifiers() public mixed getValue(stdclass object) public void setValue(stdclass object, mixed value) public ReflectionClass getDeclaringClass() public string getDocComment() } ?> |
Nota: getDocComment() was added in PHP 5.1.0.
To introspect a property, you will first have to create an instance of the ReflectionProperty class. You can then call any of the above methods on this instance.
Esempio 19-37. Using the ReflectionProperty class
|
Nota: Trying to get or set private or protected class property's values will result in an exception being thrown.
The ReflectionExtension class lets you reverse-engineer extensions. You can retrieve all loaded extensions at runtime using the get_loaded_extensions().
<?php class ReflectionExtension implements Reflector { final private __clone() public __construct(string name) public string __toString() public static string export() public string getName() public string getVersion() public ReflectionFunction[] getFunctions() public array getConstants() public array getINIEntries() public ReflectionClass[] getClasses() public array getClassNames() } ?> |
To introspect an extension, you will first have to create an instance of the ReflectionExtension class. You can then call any of the above methods on this instance.
Esempio 19-38. Using the ReflectionExtension class
|
In case you want to create specialized versions of the built-in classes (say, for creating colorized HTML when being exported, having easy-access member variables instead of methods or having utility methods), you may go ahead and extend them.
Esempio 19-39. Extending the built-in classes
|
Nota: Caution: If you're overwriting the constructor, remember to call the parent's constructor _before_ any code you insert. Failing to do so will result in the following: Fatal error: Internal error: Failed to retrieve the reflection object
PHP 5 introduces Type Hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype) or arrays (since PHP 5.1).
Esempio 19-40. Type Hinting examples
Failing to satisfy the type hint results in a fatal error.
Type hinting also works with functions:
|
Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.
PHP 5 has an exception model similar to that of other programming languages. An exception can be thrown, try and caught within PHP. A Try block must include at least one catch block. Multiple catch blocks can be used to catch different classtypes; execution will continue after that last catch block defined in sequence. Exceptions can be thrown within catch blocks.
When an exception is thrown, code following the statement will not be executed and PHP will attempt to find the first matching catch block. If an exception is not caught a PHP Fatal Error will be issued with an Uncaught Exception message, unless there has been a handler defined with set_exception_handler().
Esempio 20-1. Throwing an Exception
|
A User defined Exception class can be defined by extending the built-in Exception class. The members and properties below, show what is accessible within the child class that derives from the built-in Exception class.
Esempio 20-2. The Built in Exception class
|
If a class extends the built-in Exception class and re-defines the constructor, it is highly recomended that it also call parent::__construct() to ensure all available data has been properly assigned. The __toString() method can be overriden to provide a custom output when the object is presented as a string.
Esempio 20-3. Extending the Exception class
|
I riferimenti in PHP sono il mezzo per accedere ad uno stesso contenuto di variabile utilizzando diversi nomi. Non si sta parlando di puntatori come in C, ma di alias nella tabella dei simboli. Si noti che in PHP, il nome delle variabili e il loro contenuto sono cose diverse, uno stesso contenuto infatti può avere nomi diversi. L'analogia più prossima è quella con i nomi dei file e i file stessi in Unix - i nomi delle variabili sono come directory, mentre il contenuto delle variabili è il file stesso. I riferimenti possono essere pensati come hardlink del filesystem Unix.
I riferimenti permettono di creare due o più variabili che si riferiscono allo stesso contenuto. Questo significa, che scrivendo:
$a e $b puntano allo stesso contenuto.Nota: $a e $b sono completamente uguali, ma $a non è un puntatore a $b o vice versa, $a e $b puntano semplicemente nello stesso posto.
Nota: Se si copia una matrice contenete dei riferimenti, i valori non sono dereferenziati. Questo vale anche per le matrici passate per valore alle funzioni.
Questa sintassi si può usare con le funzioni, nella restituzione per riferimento, e con l'operatore new (da PHP 4.0.4 in poi):
Nota: Se non si usa l'operatore & l'oggeto appena creato viene copiato. Usando $this in una classe, opererà sulla sua istanza corrente. L'assegnazione senza & copia perciò l'istanza (l'oggetto) e $this opera sulla copia, che non è sempre ciò che si desidera. Normalmente si lavora su una singola istanza di oggetto, sia per motivi di prestazioni che di consumo di memoria.
Utilizzando l'operatore @ con new, si sopprimono gli errori nel costruttore in questo modo @new, il metodo però non funziona se si usa l'istruzione &new. Questa è una limitazione dello Zend Engine e provoca un parser error.
Avvertimento | ||
Se si assegna un riferimento ad una varibile dichiarata global dall'interno di una funzione, il riferimento sarà visibile solo all'interno della funzione stessa. Si può evitare tutto ciò utilizzando la matrice $GLOBALS.
|
Nota: Se si assegna un valore ad una variabile con riferimenti in una istruzione foreach, anche la variabile a cui si fa riferimento sarà modificata.
Avvertimento | |
Spesso le matrici complesse sono copiate che referenziate. Il seguente esempio non gira come atteso. |
Il secondo utilizzo del riferimento è il passaggio di una variabile per riferimento. Questo si fa dichiarando una variabile locale di una funzione e una variabile nell'ambito della chiamata del riferimento con lo stesso contenuto. Esempio:
$a assume il valore 6. Questo accade perchè nella funzione foo, la variabile $var si riferisce allo stesso contenuto di $a. Si vedano le spiegazioni più dettagliate per passaggio per riferimento.Il terzo utilizzo del riferimento è il ritorno per riferimento.
Come detto prima, i riferimenti non sono puntatori. Questo significa, che il seguente costrutto non fà quello che ci si aspetterebbe:
Nell'esempio $var in foo viene scambiato con $bar nella chiamata, e poi riscambiato con $GLOBALS["baz"]. Questo non è il modo per collegare $bar nell'ambito della chiamata con qualcos'altro usando il meccanismo di riferimento, poichè $bar non è disponibile nella funzione foo (è rappresentato da $var, ma $var possiede soltanto il contenuto della variabile e non il nome del valore collegato nella tabella dei simboli). Si può utilizzare restiture i riferimenti per fare riferimenti a variabili selezionate dalla funzione.
Si può passare una variabile ad una funzione per riferimento, modificandone gli argomenti. La sintassi è la seguente:
Nota che non si usa il segno di riferimento nella chiamata della funzione, ma solo nella definizione. La definizione della funzione basta da sola per passare correttamente un argomento per riferimento. Nelle versioni recenti di PHP si avrà un warning indicante che "Call-time pass-by-reference" è deprecato quando si usa & foo(&$a); .Le seguenti cose possono essere passate per riferimento:
Variabili, es. foo($a)
Operatore New, es. foo(new foobar())
Riferimento restituito da una funazione, es.
Vedi anche le spiegazioni sulla restituzione per riferimento.Qualunque altra cosa non dovrebbe essere passata per riferimento, poichè il risultato sarebbe indefinito. Per esempio, il seguente passaggio per riferimento non è valido:
Questi requisiti sono validi per PHP 4.0.4 e seguenti.La restituzione per riferimento è utile quando si vuole usare una funzione per trovare quale variabile un riferimento dovrebbe limitare. non utilizzare il ritorno per riferimento per incrementare le prestazioni, l'engine è abbastanza abile da ottimizzare il codice per proprio conto. Restituire valori per riferimento solo se si hanno validi motivi tecnici! Per restituire per riferimento, si usa questa sintassi:
<?php function &find_var($param) { ...codice... return $found_var; } $foo =& find_var($bar); $foo->x = 2; ?> |
Nota: Diversamente dal passaggio di un parametro, bisogna utilizzare & in entrambi i posti - nella dichiarazione per indicare che si vuole restituire per riferimento, e non per copia come di consueto, e per indicare nella chiamata, il collegamento del riferimento, piuttosto che l'usuale assegnazione che verrebbe fatta per $foo.
Nota: Se si tenta di restituire un valore per riferimento da una funzione con la sintassi: return ($found_var); questo non funzionerà poichè si sta tntando di restituire per riferimento il risultato di un' espressione, e non una variabile. Da una funzione, si possono restituire per riferimento solo le variabili.
Quando si cancella un riferimento, si rompe il collegamento tra il nome della variabile e il contenuto della variabile. Questo non significa che il contenuto della variabile venga distrutto. Per esempio:
non cancella $b, ma solo $a.Di nuovo, può essere utile pensare a questo con un'analogia col comendo Unix unlink.
Diversi costrutti in PHP sono implementati attraverso il meccanismo dei riferimenti, dove ogni cosa detta precedentemente, si applica anche a questi costrutti. Alcuni, come il passaggio e la restituzione per riferimento, sono stati menzionati sopra, gli altri sono:
Quando si dichiara una variabile come global $var di fatto si crea un riferimento ad una variabile globale. Questo ha lo stesso significato, dell'espressione:
Questo significa, per esempio, che cancellando $var non si cancella la variabile globale.
PHP is a powerful language and the interpreter, whether included in a web server as a module or executed as a separate CGI binary, is able to access files, execute commands and open network connections on the server. These properties make anything run on a web server insecure by default. PHP is designed specifically to be a more secure language for writing CGI programs than Perl or C, and with correct selection of compile-time and runtime configuration options, and proper coding practices, it can give you exactly the combination of freedom and security you need.
As there are many different ways of utilizing PHP, there are many configuration options controlling its behaviour. A large selection of options guarantees you can use PHP for a lot of purposes, but it also means there are combinations of these options and server configurations that result in an insecure setup.
The configuration flexibility of PHP is equally rivalled by the code flexibility. PHP can be used to build complete server applications, with all the power of a shell user, or it can be used for simple server-side includes with little risk in a tightly controlled environment. How you build that environment, and how secure it is, is largely up to the PHP developer.
This chapter starts with some general security advice, explains the different configuration option combinations and the situations they can be safely used, and describes different considerations in coding for different levels of security.
A completely secure system is a virtual impossibility, so an approach often used in the security profession is one of balancing risk and usability. If every variable submitted by a user required two forms of biometric validation (such as a retinal scan and a fingerprint), you would have an extremely high level of accountability. It would also take half an hour to fill out a fairly complex form, which would tend to encourage users to find ways of bypassing the security.
The best security is often unobtrusive enough to suit the requirements without the user being prevented from accomplishing their work, or over-burdening the code author with excessive complexity. Indeed, some security attacks are merely exploits of this kind of overly built security, which tends to erode over time.
A phrase worth remembering: A system is only as good as the weakest link in a chain. If all transactions are heavily logged based on time, location, transaction type, etc. but the user is only verified based on a single cookie, the validity of tying the users to the transaction log is severely weakened.
When testing, keep in mind that you will not be able to test all possibilities for even the simplest of pages. The input you may expect will be completely unrelated to the input given by a disgruntled employee, a cracker with months of time on their hands, or a housecat walking across the keyboard. This is why it's best to look at the code from a logical perspective, to discern where unexpected data can be introduced, and then follow how it is modified, reduced, or amplified.
The Internet is filled with people trying to make a name for themselves by breaking your code, crashing your site, posting inappropriate content, and otherwise making your day interesting. It doesn't matter if you have a small or large site, you are a target by simply being online, by having a server that can be connected to. Many cracking programs do not discern by size, they simply trawl massive IP blocks looking for victims. Try not to become one.
Using PHP as a CGI binary is an option for setups that for some reason do not wish to integrate PHP as a module into server software (like Apache), or will use PHP with different kinds of CGI wrappers to create safe chroot and setuid environments for scripts. This setup usually involves installing executable PHP binary to the web server cgi-bin directory. CERT advisory CA-96.11 recommends against placing any interpreters into cgi-bin. Even if the PHP binary can be used as a standalone interpreter, PHP is designed to prevent the attacks this setup makes possible:
Accessing system files: http://my.host/cgi-bin/php?/etc/passwd
The query information in a URL after the question mark (?) is passed as command line arguments to the interpreter by the CGI interface. Usually interpreters open and execute the file specified as the first argument on the command line.
When invoked as a CGI binary, PHP refuses to interpret the command line arguments.
Accessing any web document on server: http://my.host/cgi-bin/php/secret/doc.html
The path information part of the URL after the PHP binary name, /secret/doc.html is conventionally used to specify the name of the file to be opened and interpreted by the CGI program. Usually some web server configuration directives (Apache: Action) are used to redirect requests to documents like http://my.host/secret/script.php to the PHP interpreter. With this setup, the web server first checks the access permissions to the directory /secret, and after that creates the redirected request http://my.host/cgi-bin/php/secret/script.php. Unfortunately, if the request is originally given in this form, no access checks are made by web server for file /secret/script.php, but only for the /cgi-bin/php file. This way any user able to access /cgi-bin/php is able to access any protected document on the web server.
In PHP, compile-time configuration option --enable-force-cgi-redirect and runtime configuration directives doc_root and user_dir can be used to prevent this attack, if the server document tree has any directories with access restrictions. See below for full the explanation of the different combinations.
If your server does not have any content that is not restricted by password or ip based access control, there is no need for these configuration options. If your web server does not allow you to do redirects, or the server does not have a way to communicate to the PHP binary that the request is a safely redirected request, you can specify the option --enable-force-cgi-redirect to the configure script. You still have to make sure your PHP scripts do not rely on one or another way of calling the script, neither by directly http://my.host/cgi-bin/php/dir/script.php nor by redirection http://my.host/dir/script.php.
Redirection can be configured in Apache by using AddHandler and Action directives (see below).
This compile-time option prevents anyone from calling PHP directly with a URL like http://my.host/cgi-bin/php/secretdir/script.php. Instead, PHP will only parse in this mode if it has gone through a web server redirect rule.
Usually the redirection in the Apache configuration is done with the following directives:
Action php-script /cgi-bin/php AddHandler php-script .php |
This option has only been tested with the Apache web server, and relies on Apache to set the non-standard CGI environment variable REDIRECT_STATUS on redirected requests. If your web server does not support any way of telling if the request is direct or redirected, you cannot use this option and you must use one of the other ways of running the CGI version documented here.
To include active content, like scripts and executables, in the web server document directories is sometimes considered an insecure practice. If, because of some configuration mistake, the scripts are not executed but displayed as regular HTML documents, this may result in leakage of intellectual property or security information like passwords. Therefore many sysadmins will prefer setting up another directory structure for scripts that are accessible only through the PHP CGI, and therefore always interpreted and not displayed as such.
Also if the method for making sure the requests are not redirected, as described in the previous section, is not available, it is necessary to set up a script doc_root that is different from web document root.
You can set the PHP script document root by the configuration directive doc_root in the configuration file, or you can set the environment variable PHP_DOCUMENT_ROOT. If it is set, the CGI version of PHP will always construct the file name to open with this doc_root and the path information in the request, so you can be sure no script is executed outside this directory (except for user_dir below).
Another option usable here is user_dir. When user_dir is unset, only thing controlling the opened file name is doc_root. Opening a URL like http://my.host/~user/doc.php does not result in opening a file under users home directory, but a file called ~user/doc.php under doc_root (yes, a directory name starting with a tilde [~]).
If user_dir is set to for example public_php, a request like http://my.host/~user/doc.php will open a file called doc.php under the directory named public_php under the home directory of the user. If the home of the user is /home/user, the file executed is /home/user/public_php/doc.php.
user_dir expansion happens regardless of the doc_root setting, so you can control the document root and user directory access separately.
A very secure option is to put the PHP parser binary somewhere outside of the web tree of files. In /usr/local/bin, for example. The only real downside to this option is that you will now have to put a line similar to:
as the first line of any file containing PHP tags. You will also need to make the file executable. That is, treat it exactly as you would treat any other CGI script written in Perl or sh or any other common scripting language which uses the #! shell-escape mechanism for launching itself.To get PHP to handle PATH_INFO and PATH_TRANSLATED information correctly with this setup, the PHP parser should be compiled with the --enable-discard-path configure option.
When PHP is used as an Apache module it inherits Apache's user permissions (typically those of the "nobody" user). This has several impacts on security and authorization. For example, if you are using PHP to access a database, unless that database has built-in access control, you will have to make the database accessible to the "nobody" user. This means a malicious script could access and modify the database, even without a username and password. It's entirely possible that a web spider could stumble across a database administrator's web page, and drop all of your databases. You can protect against this with Apache authorization, or you can design your own access model using LDAP, .htaccess files, etc. and include that code as part of your PHP scripts.
Often, once security is established to the point where the PHP user (in this case, the apache user) has very little risk attached to it, it is discovered that PHP is now prevented from writing any files to user directories. Or perhaps it has been prevented from accessing or changing databases. It has equally been secured from writing good and bad files, or entering good and bad database transactions.
A frequent security mistake made at this point is to allow apache root permissions, or to escalate apache's abilities in some other way.
Escalating the Apache user's permissions to root is extremely dangerous and may compromise the entire system, so sudo'ing, chroot'ing, or otherwise running as root should not be considered by those who are not security professionals.
There are some simpler solutions. By using open_basedir you can control and restrict what directories are allowed to be used for PHP. You can also set up apache-only areas, to restrict all web based activity to non-user, or non-system, files.
PHP is subject to the security built into most server systems with respect to permissions on a file and directory basis. This allows you to control which files in the filesystem may be read. Care should be taken with any files which are world readable to ensure that they are safe for reading by all users who have access to that filesystem.
Since PHP was designed to allow user level access to the filesystem, it's entirely possible to write a PHP script that will allow you to read system files such as /etc/passwd, modify your ethernet connections, send massive printer jobs out, etc. This has some obvious implications, in that you need to ensure that the files that you read from and write to are the appropriate ones.
Consider the following script, where a user indicates that they'd like to delete a file in their home directory. This assumes a situation where a PHP web interface is regularly used for file management, so the Apache user is allowed to delete files in the user home directories.
Esempio 26-2. ... A filesystem attack
|
Only allow limited permissions to the PHP web user binary.
Check all variables which are submitted.
Esempio 26-3. More secure file name checking
|
Esempio 26-4. More secure file name checking
|
Depending on your operating system, there are a wide variety of files which you should be concerned about, including device entries (/dev/ or COM1), configuration files (/etc/ files and the .ini files), well known file storage areas (/home/, My Documents), etc. For this reason, it's usually easier to create a policy where you forbid everything except for what you explicitly allow.
Nowadays, databases are cardinal components of any web based application by enabling websites to provide varying dynamic content. Since very sensitive or secret information can be stored in a database, you should strongly consider protecting your databases.
To retrieve or to store any information you need to connect to the database, send a legitimate query, fetch the result, and close the connection. Nowadays, the commonly used query language in this interaction is the Structured Query Language (SQL). See how an attacker can tamper with an SQL query.
As you can surmise, PHP cannot protect your database by itself. The following sections aim to be an introduction into the very basics of how to access and manipulate databases within PHP scripts.
Keep in mind this simple rule: defense in depth. The more places you take action to increase the protection of your database, the less probability of an attacker succeeding in exposing or abusing any stored information. Good design of the database schema and the application deals with your greatest fears.
The first step is always to create the database, unless you want to use one from a third party. When a database is created, it is assigned to an owner, who executed the creation statement. Usually, only the owner (or a superuser) can do anything with the objects in that database, and in order to allow other users to use it, privileges must be granted.
Applications should never connect to the database as its owner or a superuser, because these users can execute any query at will, for example, modifying the schema (e.g. dropping tables) or deleting its entire content.
You may create different database users for every aspect of your application with very limited rights to database objects. The most required privileges should be granted only, and avoid that the same user can interact with the database in different use cases. This means that if intruders gain access to your database using your applications credentials, they can only effect as many changes as your application can.
You are encouraged not to implement all the business logic in the web application (i.e. your script), instead do it in the database schema using views, triggers or rules. If the system evolves, new ports will be intended to open to the database, and you have to re-implement the logic in each separate database client. Over and above, triggers can be used to transparently and automatically handle fields, which often provides insight when debugging problems with your application or tracing back transactions.
You may want to establish the connections over SSL to encrypt client/server communications for increased security, or you can use ssh to encrypt the network connection between clients and the database server. If either of these is used, then monitoring your traffic and gaining information about your database will be difficult for a would-be attacker.
SSL/SSH protects data travelling from the client to the server, SSL/SSH does not protect the persistent data stored in a database. SSL is an on-the-wire protocol.
Once an attacker gains access to your database directly (bypassing the webserver), the stored sensitive data may be exposed or misused, unless the information is protected by the database itself. Encrypting the data is a good way to mitigate this threat, but very few databases offer this type of data encryption.
The easiest way to work around this problem is to first create your own encryption package, and then use it from within your PHP scripts. PHP can assist you in this with several extensions, such as Mcrypt and Mhash, covering a wide variety of encryption algorithms. The script encrypts the data before inserting it into the database, and decrypts it when retrieving. See the references for further examples of how encryption works.
In case of truly hidden data, if its raw representation is not needed (i.e. not be displayed), hashing may also be taken into consideration. The well-known example for the hashing is storing the MD5 hash of a password in a database, instead of the password itself. See also crypt() and md5().
Esempio 27-1. Using hashed password field
|
Many web developers are unaware of how SQL queries can be tampered with, and assume that an SQL query is a trusted command. It means that SQL queries are able to circumvent access controls, thereby bypassing standard authentication and authorization checks, and sometimes SQL queries even may allow access to host operating system level commands.
Direct SQL Command Injection is a technique where an attacker creates or alters existing SQL commands to expose hidden data, or to override valuable ones, or even to execute dangerous system level commands on the database host. This is accomplished by the application taking user input and combining it with static parameters to build a SQL query. The following examples are based on true stories, unfortunately.
Owing to the lack of input validation and connecting to the database on behalf of a superuser or the one who can create users, the attacker may create a superuser in your database.
0; insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd) select 'crack', usesysid, 't','t','crack' from pg_shadow where usename='postgres'; -- |
Nota: It is common technique to force the SQL parser to ignore the rest of the query written by the developer with -- which is the comment sign in SQL.
A feasible way to gain passwords is to circumvent your search result pages. The only thing the attacker needs to do is to see if there are any submitted variables used in SQL statements which are not handled properly. These filters can be set commonly in a preceding form to customize WHERE, ORDER BY, LIMIT and OFFSET clauses in SELECT statements. If your database supports the UNION construct, the attacker may try to append an entire query to the original one to list passwords from an arbitrary table. Using encrypted password fields is strongly encouraged.
SQL UPDATE's are also susceptible to attack. These queries are also threatened by chopping and appending an entirely new query to it. But the attacker might fiddle with the SET clause. In this case some schema information must be possessed to manipulate the query successfully. This can be acquired by examining the form variable names, or just simply brute forcing. There are not so many naming conventions for fields storing passwords or usernames.
<?php // $uid == ' or uid like'%admin%'; -- $query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%'; --"; // $pwd == "hehehe', admin='yes', trusted=100 " $query = "UPDATE usertable SET pwd='hehehe', admin='yes', trusted=100 WHERE ...;"; ?> |
A frightening example how operating system level commands can be accessed on some database hosts.
<?php $query = "SELECT * FROM products WHERE id LIKE '%a%' exec master..xp_cmdshell 'net user test testpass /ADD'--"; $result = mssql_query($query); ?> |
Nota: Some of the examples above is tied to a specific database server. This does not mean that a similar attack is impossible against other products. Your database server may be similarly vulnerable in another manner.
You may plead that the attacker must possess a piece of information about the database schema in most examples. You are right, but you never know when and how it can be taken out, and if it happens, your database may be exposed. If you are using an open source, or publicly available database handling package, which may belong to a content management system or forum, the intruders easily produce a copy of a piece of your code. It may be also a security risk if it is a poorly designed one.
These attacks are mainly based on exploiting the code not being written with security in mind. Never trust any kind of input, especially that which comes from the client side, even though it comes from a select box, a hidden input field or a cookie. The first example shows that such a blameless query can cause disasters.
Never connect to the database as a superuser or as the database owner. Use always customized users with very limited privileges.
Check if the given input has the expected data type. PHP has a wide range of input validating functions, from the simplest ones found in Variable Functions and in Character Type Functions (e.g. is_numeric(), ctype_digit() respectively) and onwards to the Perl compatible Regular Expressions support.
If the application waits for numerical input, consider verifying data with is_numeric(), or silently change its type using settype(), or use its numeric representation by sprintf().
Esempio 27-6. A more secure way to compose a query for paging
|
Quote each non numeric user supplied value that is passed to the database with the database-specific string escape function (e.g. mysql_escape_string(), sql_escape_string(), etc.). If a database-specific string escape mechanism is not available, the addslashes() and str_replace() functions may be useful (depending on database type). See the first example. As the example shows, adding quotes to the static part of the query is not enough, making this query easily crackable.
Do not print out any database specific information, especially about the schema, by fair means or foul. See also Error Reporting and Error Handling and Logging Functions.
You may use stored procedures and previously defined cursors to abstract data access so that users do not directly access tables or views, but this solution has another impacts.
Besides these, you benefit from logging queries either within your script or by the database itself, if it supports logging. Obviously, the logging is unable to prevent any harmful attempt, but it can be helpful to trace back which application has been circumvented. The log is not useful by itself, but through the information it contains. More detail is generally better than less.
With PHP security, there are two sides to error reporting. One is beneficial to increasing security, the other is detrimental.
A standard attack tactic involves profiling a system by feeding it improper data, and checking for the kinds, and contexts, of the errors which are returned. This allows the system cracker to probe for information about the server, to determine possible weaknesses. For example, if an attacker had gleaned information about a page based on a prior form submission, they may attempt to override variables, or modify them:
The PHP errors which are normally returned can be quite helpful to a developer who is trying to debug a script, indicating such things as the function or file that failed, the PHP file it failed in, and the line number which the failure occurred in. This is all information that can be exploited. It is not uncommon for a php developer to use show_source(), highlight_string(), or highlight_file() as a debugging measure, but in a live site, this can expose hidden variables, unchecked syntax, and other dangerous information. Especially dangerous is running code from known sources with built-in debugging handlers, or using common debugging techniques. If the attacker can determine what general technique you are using, they may try to brute-force a page, by sending various common debugging strings:
Regardless of the method of error handling, the ability to probe a system for errors leads to providing an attacker with more information.
For example, the very style of a generic PHP error indicates a system is running PHP. If the attacker was looking at an .html page, and wanted to probe for the back-end (to look for known weaknesses in the system), by feeding it the wrong data they may be able to determine that a system was built with PHP.
A function error can indicate whether a system may be running a specific database engine, or give clues as to how a web page or programmed or designed. This allows for deeper investigation into open database ports, or to look for specific bugs or weaknesses in a web page. By feeding different pieces of bad data, for example, an attacker can determine the order of authentication in a script, (from the line number errors) as well as probe for exploits that may be exploited in different locations in the script.
A filesystem or general PHP error can indicate what permissions the webserver has, as well as the structure and organization of files on the web server. Developer written error code can aggravate this problem, leading to easy exploitation of formerly "hidden" information.
There are three major solutions to this issue. The first is to scrutinize all functions, and attempt to compensate for the bulk of the errors. The second is to disable error reporting entirely on the running code. The third is to use PHP's custom error handling functions to create your own error handler. Depending on your security policy, you may find all three to be applicable to your situation.
One way of catching this issue ahead of time is to make use of PHP's own error_reporting(), to help you secure your code and find variable usage that may be dangerous. By testing your code, prior to deployment, with E_ALL, you can quickly find areas where your variables may be open to poisoning or modification in other ways. Once you are ready for deployment, you should either disable error reporting completely by setting error_reporting() to 0, or turn off the error display using the php.ini option display_errors, to insulate your code from probing. If you choose to do the latter, you should also define the path to your log file using the error_log ini directive, and turn log_errors on.
Perhaps the most controversial change in PHP is when the default value for the PHP directive register_globals went from ON to OFF in PHP 4.2.0. Reliance on this directive was quite common and many people didn't even know it existed and assumed it's just how PHP works. This page will explain how one can write insecure code with this directive but keep in mind that the directive itself isn't insecure but rather it's the misuse of it.
When on, register_globals will inject your scripts with all sorts of variables, like request variables from HTML forms. This coupled with the fact that PHP doesn't require variable initialization means writing insecure code is that much easier. It was a difficult decision, but the PHP community decided to disable this directive by default. When on, people use variables yet really don't know for sure where they come from and can only assume. Internal variables that are defined in the script itself get mixed up with request data sent by users and disabling register_globals changes this. Let's demonstrate with an example misuse of register_globals:
Esempio 29-1. Example misuse with register_globals = on
|
When register_globals = on, our logic above may be compromised. When off, $authorized can't be set via request so it'll be fine, although it really is generally a good programming practice to initialize variables first. For example, in our example above we might have first done $authorized = false. Doing this first means our above code would work with register_globals on or off as users by default would be unauthorized.
Another example is that of sessions. When register_globals = on, we could also use $username in our example below but again you must realize that $username could also come from other means, such as GET (through the URL).
Esempio 29-2. Example use of sessions with register_globals on or off
|
It's even possible to take preventative measures to warn when forging is being attempted. If you know ahead of time exactly where a variable should be coming from, you can check to see if the submitted data is coming from an inappropriate kind of submission. While it doesn't guarantee that data has not been forged, it does require an attacker to guess the right kind of forging. If you don't care where the request data comes from, you can use $_REQUEST as it contains a mix of GET, POST and COOKIE data. See also the manual section on using variables from outside of PHP.
Esempio 29-3. Detecting simple variable poisoning
|
Of course, simply turning off register_globals does not mean your code is secure. For every piece of data that is submitted, it should also be checked in other ways. Always validate your user data and initialize your variables! To check for uninitialized variables you may turn up error_reporting() to show E_NOTICE level errors.
For information about emulating register_globals being On or Off, see this FAQ.
Matrici superglobali: note di disponibilità: A partire da PHP 4.1.0, sono disponibili le matrici superglobali quali $_GET , $_POST, e $_SERVER, ecc. Per maggiori dettagli, si rimanda al capitolo superglobals del manuale
The greatest weakness in many PHP programs is not inherent in the language itself, but merely an issue of code not being written with security in mind. For this reason, you should always take the time to consider the implications of a given piece of code, to ascertain the possible damage if an unexpected variable is submitted to it.
Esempio 30-1. Dangerous Variable Usage
|
Will this script only affect the intended files?
Can unusual or undesirable data be acted upon?
Can this script be used in unintended ways?
Can this be used in conjunction with other scripts in a negative manner?
Will any transactions be adequately logged?
You may also want to consider turning off register_globals, magic_quotes, or other convenience settings which may confuse you as to the validity, source, or value of a given variable. Working with PHP in error_reporting(E_ALL) mode can also help warn you about variables being used before they are checked or initialized (so you can prevent unusual data from being operated upon).
Magic Quotes is a process that automagically escapes incoming data to the PHP script. It's preferred to code with magic quotes off and to instead escape the data at runtime, as needed.
When on, all ' (single-quote), " (double quote), \ (backslash) and NULL characters are escaped with a backslash automatically. This is identical to what addslashes() does.
There are three magic quote directives:
Affects HTTP Request data (GET, POST, and COOKIE). Cannot be set at runtime, and defaults to on in PHP.
See also get_magic_quotes_gpc().
If enabled, most functions that return data from an external source, including databases and text files, will have quotes escaped with a backslash. Can be set at runtime, and defaults to off in PHP.
See also set_magic_quotes_runtime() and get_magic_quotes_runtime().
If enabled, a single-quote is escaped with a single-quote instead of a backslash. If on, it completely overrides magic_quotes_gpc. Having both directives enabled means only single quotes are escaped as ''. Double quotes, backslashes and NULL's will remain untouched and unescaped.
See also ini_get() for retrieving its value.
Useful for beginners
Magic quotes are implemented in PHP to help code written by beginners from being dangerous. Although SQL Injection is still possible with magic quotes on, the risk is reduced.
Convenience
For inserting data into a database, magic quotes essentially runs addslashes() on all Get, Post, and Cookie data, and does so automagically.
Portability
Assuming it to be on, or off, affects portability. Use get_magic_quotes_gpc() to check for this, and code accordingly.
Performance
Because not every piece of escaped data is inserted into a database, there is a performance loss for escaping all this data. Simply calling on the escaping functions (like addslashes()) at runtime is more efficient.
Although php.ini-dist enables these directives by default, php.ini-recommended disables it. This recommendation is mainly due to performance reasons.
Inconvenience
Because not all data needs escaping, it's often annoying to see escaped data where it shouldn't be. For example, emailing from a form, and seeing a bunch of \' within the email. To fix, this may require excessive use of stripslashes().
The magic_quotes_gpc directive may only be disabled at the system level, and not at runtime. In otherwords, use of ini_set() is not an option.
Esempio 31-1. Disabling magic quotes server side An example that sets the value of these directives to Off in php.ini. For additional details, read the manual section titled How to change configuration settings.
If access to the server configuration is unavailable, use of .htaccess is also an option. For example:
|
In the interest of writing portable code (code that works in any environment), like if setting at the server level is not possible, here's an example to disable magic_quotes_gpc at runtime. This method is inefficient so it's preferred to instead set the appropriate directives elsewhere.
Esempio 31-2. Disabling magic quotes at runtime
|
In general, security by obscurity is one of the weakest forms of security. But in some cases, every little bit of extra security is desirable.
A few simple techniques can help to hide PHP, possibly slowing down an attacker who is attempting to discover weaknesses in your system. By setting expose_php = off in your php.ini file, you reduce the amount of information available to them.
Another tactic is to configure web servers such as apache to parse different filetypes through PHP, either with an .htaccess directive, or in the apache configuration file itself. You can then use misleading file extensions:
PHP, like any other large system, is under constant scrutiny and improvement. Each new version will often include both major and minor changes to enhance security and repair any flaws, configuration mishaps, and other issues that will affect the overall security and stability of your system.
Like other system-level scripting languages and programs, the best approach is to update often, and maintain awareness of the latest versions and their changes.
I meccanismi di Autenticazione HTTP sono disponibili in PHP solo quando questo viene usato come un modulo di Apache ed esso non è quindi disponibile nella versione CGI. In uno script PHP modulo di Apache, è possibile usare la funzione header() per inviare un messaggio di "Authentication Required" al browser dell'utente, provocando quindi l'apertura di una finestra contenente una richiesta di Nome utente/Password. Una volta che l'utente ha compilato i campi nome utente e password, l'URL contenente lo script PHP verrà richiamato nuovamente usando le variabili predefinite, PHP_AUTH_USER, PHP_AUTH_PW e AUTH_TYPE impostate con, rispettivamente: nome, password e tipo di autenticazione. Queste variabili predefinite possono essere trovate negli array $_SERVER e $HTTP_SERVER_VARS. Saranno supportati entrambi i metodi di autenticazione, "Basic" e "Digest" (a partire dal PHP 5.1.0). Fare riferimento alla funzione header() per ulteriori informazioni.
Nota sulla versione di PHP: Le variabili autoglobali, come $_SERVER, esistono a partire da PHP 4.1.0. $HTTP_SERVER_VARS è disponibile a partire da PHP 3.
Un frammento di script di esempio che richiede l'autenticazione da parte del browser su una pagina, potrebbe essere il seguente:
Esempio 34-1. Esempio di Autenticazione HTTP "Basic"
|
Esempio 34-2. Esempio di autenticazione HTTP "Digest" Questo esempio illustra come implementare una autenticazione Digest. Per maggiori dettagli vedere RFC 2617.
|
Note sulla compatibilità: Fare molta attenzione quando si scrive codice per le intestazioni HTTP. Per ottenere la massima compatibilità con tutti i client, la paorla-chiave "Basic" deve essere scritta con una "B" maiuscola, la stringa realm deve essere racchiusa in virgolette doppie (non singole), ed esattamente uno spazio deve precedere il codice 401 nella linea di intestazione HTTP/1.0 401.
Invece di stampare semplicemente PHP_AUTH_USER e PHP_AUTH_PW, probabilmente si vorrà controllare la validità dello username e della password. Probabilmente inviando una chiamata al database, o cercando un utente in un file dbm.
Si faccia attenzione ad alcune versioni di Internet Explorer. Sembra che siano molto schizzinosi riguardo all'ordine delle intestazioni. Inviare l'intestazione WWW-Authenticate prima dell'intestazione HTTP/1.0 401 sembra sistemare le cose per il momento.
A partire da PHP 4.3.0, al fine di prevenire che qualcuno scriva uno script che rivela la password di una pagina che era stata autenticata tramite un tradizionale meccanismo esterno, le variabili PHP_AUTH non verranno impostate se è abilitata l'autenticazione esterna per quella determinata pagina e modalità sicura è abilitato. Ciò nonostante, la variabile REMOTE_USER può essere usata per identificare un utente autenticato esternamente. Quindi, potete usare $_SERVER['REMOTE_USER'].
Nota sulla Configurazione: PHP usa la presenza di una direttiva AuthType per determinare se viene utilizzata l'autenticazione esterna.
Si fa notare, però, che quanto scritto sopra non impedisce a qualcuno che controlla un URL non autenticato di sottrarre password da URL autenticati presenti sullo stesso server.
Sia Netscape Navigator che Internet Explorer cancellano la cache locale della finestra del browser, per quanto riguarda il realm, al ricevimento di una risposta 401 da parte del server. Questo è effettivamente un meccanismo di "log out" per l'utente, che lo forza a reinserire lo username e la password. Alcune persone usano questo per fare il "time out" dei login, o per rendere disponibili bottoni di "log-out".
Esempio 34-3. Esempio di Autenticazione HTTP che impone l'inserimento di nuovo username/password
|
Questo comportamento non è richiesto dallo standard di autenticazione HTTP Basic, quindi non si dovrebbe mai fare affidamento su di esso. Test effettuati con Lynx mostrano che Lynx non cancella le credenziali di autenticazione al ricevimento del codice di risposta 401 da parte del server, quindi, premendo indietro e avanti nuovamente, darà nuovamente accesso alla risorsa, ammesso che le rispettive richieste di credenziali non siano cambiate. L'utente può però premere il tasto '_' al fine di cancellare le sue informazioni di autenticazione.
Si noti anche che questo non funziona con il server IIS di Microsoft e con la versione CGI di PHP a causa di una limitazione di IIS. Si noti anche che, prima di PHP 4.3.3, l'Autenticazione HTTP non funzionava usando il server IIS di Microsoft e con la versione CGI di PHP a causa di una limitazione di IIS. Al fine di farla funzionare in PHP 4.3.3+, si deve modificare la vostra configurazione di IIS "Directory Security". Cliccare su "Edit" e selezionare solo "Anonymous Access", tutti gli altri campi dovrebbero essere lasciati deselezionati.
Un'altra limitazione è che se si usa il modulo IIS (ISAPI) e PHP 4, non si possono usare le variabili PHP_AUTH_* ma, al contrario, la variabile HTTP_AUTHORIZATION è disponibile. Per esempio, si consideri il seguente codice: list($user, $pw) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
Nota su IIS:: Al fine di fare funzionare la Autenticazione HTTP con IIS, la direttiva PHP cgi.rfc2616_headers deve essere impostata al valore 0 (il valore predefinito).
Nota: Se è abilitato safe mode viene aggiunto lo uid dello script al realm dell'header WWW-Authenticate.
PHP supporta in modo trasparente i cookies HTTP. I cookies sono un meccanismo per memorizzare dati nel browser remoto e tenere traccia degli utenti o identificarli al loro ritorno. I cookies possono essere impostati tramite le funzioni setcookie() oppure setrawcookie(). I cookies sono parte dell'intestazione HTTP, quindi setcookie() deve essere chiamata prima che qualsiasi output sia inviato al browser. Si tratta della stessa limitazione della funzione header(). Si può utilizzare la funzione di buffer dell'output per posticipare l'output dello script finchè non avete stabilito se impostare o meno qualsiasi cookies o l''invio di header.
Ogni cookie inviato dal client sarà automaticamente trasformato in una variabile PHP, come avviene nel caso di dati GET o POST, in base alle variabili di configurazione register_globals e variables_order. Se si vogliono assegnare più valori ad un singolo cookie, basta aggiungere [] al nome del cookie.
Nel PHP 4.1.0 e successivi, il vettore auto-globale $_COOKIE sarà sempre impostato con qualsiasi cookies inviati dal client. $HTTP_COOKIE_VARS è anch'essa impostata nelle versioni precedenti del PHP se è impostata la variabile di configurazione track_vars. (Questo parametro è sempre a on a partire da PHP 4.0.3.)
Per maggiori dettagli si vedano le funzioni setcookie() e setrawcookie().
Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site. All information is in the Session reference section.
XForms defines a variation on traditional webforms which allows them to be used on a wider variety of platforms and browsers or even non-traditional media such as PDF documents.
The first key difference in XForms is how the form is sent to the client. XForms for HTML Authors contains a detailed description of how to create XForms, for the purpose of this tutorial we'll only be looking at a simple example.
Esempio 37-1. A simple XForms search form
|
The above form displays a text input box (named q), and a submit button. When the submit button is clicked, the form will be sent to the page referred to by action.
Here's where it starts to look different from your web application's point of view. In a normal HTML form, the data would be sent as application/x-www-form-urlencoded, in the XForms world however, this information is sent as XML formatted data.
If you're choosing to work with XForms then you probably want that data as XML, in that case, look in $HTTP_RAW_POST_DATA where you'll find the XML document generated by the browser which you can pass into your favorite XSLT engine or document parser.
If you're not interested in formatting and just want your data to be loaded into the traditional $_POST variable, you can instruct the client browser to send it as application/x-www-form-urlencoded by changing the method attribute to urlencoded-post.
Esempio 37-2. Using an XForm to populate $_POST
|
Nota: As of this writing, many browsers do not support XForms. Check your browser version if the above examples fails.
Questa caratteristica permette di caricare sia file di testo che binari. Utilizzando le funzioni di PHP per l'autenticazione e manipolazione dei file, è possibile avere pieno controllo su chi ha i permessi per caricare un file e su ciò che deve essere fatto una volta che il file è stato caricato.
Il PHP è in grado di riceve upload di file da qualsiasi browser compatibile con la RFC-1867 (compresi Netscape Navigator 3 e successivi, Microsoft Internet Explorer 3 con le patch di Microsoft, oppure le versioni successive senza patch).
Note relative alla configurazione: Si vedano i parametri file_uploads, upload_max_filesize, upload_tmp_dir, post_max_size e max_input_time nel php.ini
Si noti che PHP permette l'upload di file con metodo PUT come utilizzato dai programmi Netscape Composer e W3C Amaya. Si veda Supporto per metodo PUT per maggiori dettagli.
Esempio 38-1. Form di caricamento file La schermata di caricamento di un file può essere costruita con una form particolare, di questo tipo:
L'__URL__ dell'esempio precedente deve essere sostituito con il puntamento ad un file PHP. Il campo nascosto MAX_FILE_SIZE (misurato in byte) deve precedere il campo di input del file, ed il suo valore indica la dimensione massima di file accettata. Questa è un'informazione per il browser, ma anche il PHP lo verifica. E' facile aggirare questa impostazione sul browser, quindi non fate affidamento sul fatto che il navigatore si comporti come desiderato! L'impostazione PHP lato server per la dimensione massima non può comunque essere aggirata. Tuttavia si può comunque inserire MAX_FILE_SIZE per evitare all'utente di attendere il trasferimento di un file prima di scoprire che è di dimensioni eccessive. |
Nota: Accertarsi che il form di upload abbia l'impostazione enctype="multipart/form-data" altrimentio non funzionerà.
A partire dal PHP 4.1.0 esiste la variabile globale $_FILES. (Utilizzare $HTTP_POST_FILES nelle versioni precedenti). Queste matrici contengono tutte le informazioni sui file inviati.
Di seguito verrà illustrato il contenuto di $_FILES nel caso dell'esempio precedente. Si noti che si assume come nome del file inviato userfile, come nell'esempio precedente. Nella realtà questo può assurmere nome.
Il nome originale del file sulla macchina dell'utente.
Il mime-type del file, se il browser fornisce questa informazione. Un esempio potrebbe essere "image/gif".
La dimensione, in bytes, del file caricato.
Il nome del file temporaneo in cui il file caricato è salvato sul server.
Il codice di errore associato all'upload di questo file. Questo elemento è stato aggiunto nella versione 4.2.0 di PHP.
I file sono, di default, salvati in una directory temporanea sul server, a meno che un diverso percorso sia specificato nella direttiva upload_tmp_dir nel file php.ini. La directory del server predefinita può essere cambiata impostando la variabile di ambiente TMPDIR in cui è in esecuzione PHP. Non è possibile impostare questa variabile utilizzando la funzione putenv() da uno script PHP. Questa variabile di ambiente può anche essere usata per assicurarsi che anche altre operazioni stiano lavorando sui file caricati.
Esempio 38-2. Verifica dell'upload di file Si vedano le definizioni delle funzioni is_uploaded_file() e move_uploaded_file() per maggiori dettagli. L'esempio seguente illustra il processamento di un file inviato tramite un form.
|
Lo script PHP che riceve il file caricato dovrebbe implementare la logica necessaria per determinare cosa deve essere fatto con il file caricato. E' possibile, per esempio, utilizzare la variabile $_FILES['userfile']['size'] per eliminare file che siano troppo grandi o troppo piccoli. E' possibile utillizzare la variabile $_FILES['userfile']['type'] per eliminare tutti i file che non soddisfano certi criteri. A partire da PHP 4.2.0, si può utilizzare $_FILES['userfile']['error'] ed organizzare la logica in base ai codici di errore. Quale che sia la logica, bisognerebbe comunque sempre cancellare il file dalla directory temporanea e spostarlo da qualche altra parte.
Se non si è selezinato alcun file per l'upload, il PHP restituità $_FILES['userfile']['size'] a 0, e $_FILES['userfile']['tmp_name'] vuoto.
Il file sarà eliminato dalla directory temporanea al termine della richiesta se non è stato mosso e rinominato.
Esempio 38-3. Upload di una serie di file Il PHP supporta le matrici HTML anche con i file.
|
Dalla versione 4.2.0, il PHP restituisce un codice di errore nella matrice del file. Il codice di errore si trova nell'indice error e viene valorizzato durante l'upload del file da parte del PHP. In altre parole l'errore può essere trovato in $_FILES['userfile']['error'].
Valore: 0; Non vi sono errori, l'upload è stato eseguito con successo.
Valore: 1; Il file inviato eccede le dimensioni specificate nel parametro upload_max_filesize di php.ini.
Valore: 2; Il file inviato eccede le dimensioni specificate nel parametro MAX_FILE_SIZE del form.
Valore: 3; Upload eseguito parzialmente.
Valore: 4; Nessun file è stato inviato.
Valore: 6; Mancanza della cartella temporanea. Inserito in PHP 4.3.10 e PHP 5.0.3.
Nota: Questi valori sono diventate costanti PHP a partire dal PHP 4.3.0.
La voce MAX_FILE_SIZE non può specificare una dimensione del file maggiore di quella impostata dal parametro upload_max_filesize del file php.ini. L'impostazione di default è 2 Megabytes.
Se si è impostato un limite di memoria memory_limit può essere necessario ampliarlo. Occorre essere certi di impostare memory_limit alle dimensioni appropriate.
Se max_execution_time è impostato ad un valore basso, l'esecuzione dello script può eccedere tale valore. Ampliare max_execution_time ad un tempo sufficiente per l'upload.
Nota: max_execution_time influisce solo sul tempo di esecuzione dello script. Il tempo utilizzato per attività esterno allo script, tipo le chiamate di sistema system(), o la funzione sleep(), le query nei database, il tempo inpiegato nell'upload del file non è considerato nel computo del tempo di esecuzione dello script.
Avvertimento |
max_input_time imposta il tempo massimo, in secondi, in cui lo script può ricevere dati; questo comprende l'upload di file. Per file di grandi dimensioni o molteplici file, o su connessioni lente, il valore di default 60 seconds può essere sforato. |
Se post_max_size è impostato ad un valore troppo piccolo, non si può inviare file di grosse dimensioni. Impostare post_max_size alle dimensioni appropriate.
Non controllare il file su cui si sta operando potrebbe dare agli utenti accesso a informazioni sensibili contenute in altre directory.
Si noti che che il server CERN httpd sembra eliminare qualsiasi cosa a partire dal primo spazio nell'header mime content-type che riceve dal client. Fino a che questo si verificherà, il server CERN httpd non supporterà la possibilità di caricare file.
A causa della varietà di formati di directory, non si è in grado di garantire che nomi di file strani (ad esempio contenenti spazi) siano gestiti correttamente.
Un sviluppatore non può mischiare normali campi di input con campi di upload di file con lo stesso nome di campo (utilizzando nomi tipo foo[]).
E' possibile inviare più file contemporanemante utilizzando in input nomi differenti.
E' possibile caricare più file contemporaneamente e avere le informazioni organizzate automaticamente in array. Per questo è necessario utilizzare la medesima sintassi di invio di array da form HTML che è utilizzata con select e checkbox multipli:
Nota: Il supporto per il caricamento di file multipliè stato aggiunto in PHP 3.0.10.
Quando la form è inviata, gli array $_FILES['userfile'], $_FILES['userfile']['name'], e $_FILES['userfile']['size'] saranno inizializzati (come sarà valorizzato $HTTP_POST_FILES per le versioni di PHP precedenti la 4.1.0). Quando il parametro register_globals è impostato a on saranno presenti anche le variabili globali. Ognuno di questi è un array indicizzato numericamente con i valori relativi ai diversi file caricati.
Per esempio, si supponga che i nomi di file /home/test/review.html e /home/test/xwp.out siano inviati. In questo caso, $_FILES['userfile']['name'][0] conterrebbe il valore review.html, e $_FILES['userfile']['name'][1] conterrebbe il valore xwp.out. Analogamente, $_FILES['userfile']['size'][0] conterrebbe la dimensione di review.html, e così via.
Anche $_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0], $_FILES['userfile']['size'][0], e $_FILES['userfile']['type'][0] sono impostati.
Il supporto al metodo PUT è cambiato tra PHP 3 e PHP 4. In PHP 4 occorre utilizzare il flusso standard di input per leggere il contenuto di un PUT HTTP.
Esempio 38-5. Salvataggio di un file HTTP PUT con PHP 4
|
Nota: Tutta la documentazione che segue si applica solo a PHP 3.
PHP fornisce supporto per il metodo HTTP PUT utilizzato da programmi come Netscape Composer e W3C Amaya. Le richieste PUT sono molto più semplici rispetto al caricamento di un file, e assomigliano a
Questo significa che normalmente il programma remoto intende salvare il contenuto della richesta come : /path/filename.html nel filesystem sul server web. Non è ovviamente una buona idea per Apache o PHP lasciare a un qualsiasi utente la possibilità di sovrascrivere file sul server web. Quindi, per gestire questa richiesta si deve chiedere al server web che si vuole che sia un certo script PHP a gestire la richiesta stessa. In Apache si ottiene questo con la direttiva Script. Può essere posta quasi ovunque nel file di configurazione di Apache. Un posto frequente è all'interno di un blocco <Directory> oppurte all'interno del blocco <Virtualhost>. Un linea come la seguente è sufficiente:
Questo chiede ad Apache di inviare tutte le richieste PUT che soddisfano il contesto in cui si è inserito questo comando allo script put.php. Questo richiede, naturalmente, che sia abilitato PHP per l'estensione .php e che PHP sia attivo.
All'interno del file put.php si può inserire qualcosa del tipo:
Questo copia il file nella posizione chiesta dal programma remoto. E' probabile che si vogliano effettuare dei controlli o autenticazioni dell'utente prima di effettuare questa copia. L'unica magia qui presente è che quando PHP vede una richiesta con metodo PUT memorizza il file caricato in un file temporaneo così come per i file caricati con il metodo POST. Quando la richiesta termina, questo file temporaneo è eliminato. Quindi il gestore della richiesta PUT deve copiare il file da qualche parte. Il nome del file temporaneo è memorizzato nella variabile $PHP_PUT_FILENAME, ed è possibile vedere il nome del file di destinazione nella variabile $REQUEST_URI (potrebbe variare su web server diversi da Apache). Qusto nome di file di destinazione è quello specificato dal client remoto. Non è necessario seguire le indicazioni del client. E' possibile, per esempio, copiare tutti i file caricati in una apposita directory.
Se allow_url_fopen è abilitato in php.ini, si possono usare gli URL HTTP e FTP con la maggior parte delle funzioni che richiedono nomi di file come parametri, incluse le funzioni require(), require_once(), include() e include_once(). Vedere Appendice M per maggiori dettagli sui protocolli supportati dal PHP.
Nota: In PHP 4.0.3 e precedenti, al fine di poter utilizzare gli URL wrapper, occorreva specificare l'opzione di configurazione --enable-url-fopen-wrapper.
Nota: Al momento, le versioni Windows di PHP precedenti la 4.3, non supportano l'accesso remoto ai file con le seguenti funzioni: include(), include_once(), require() e require_once() e le funzioni imagecreatefromXXX del modulo Riferimento LVI, Funzioni per le immagini.
Per esempio, si può usare per aprire un file da un web server remoto, elaborare i dati presi da remoto, e usarli per effetuare delle query, o semplicemente visualizzarli con lo stile del proprio sito web.
Esempio 39-1. Leggere il titolo di una pagina web remota
|
Si può anche scrivere in un file remoto via FTP (se l'utente con cui ci si connette ha le autorizzazioni necessarie). Si possono solamente creare nuovi file usando questo metodo, se si prova a sovrascrivere un file che già esiste, fopen() non avrà successo.
Per connettersi con un utenti diversi da 'anonymous' si ha bisogno di specificare lo username (e la relativa password) assieme all'URL, in questo modo: 'ftp://user:password@ftp.example.com/directory/del/file'. (Si può usare lo stesso tipo di sintassi per accedere a file via HTTP quando richiedono autenticazione Basic).
Esempio 39-2. Salvataggio di dati su server remoto
|
Nota: Le seguenti note si applicano a partire dalla versione 3.0.7.
Internamente il PHP mantiene lo stato della connessione. Si hanno 3 possibili stati:
0 - NORMAL
1 - ABORTED
2 - TIMEOUT
Quendo uno script PHP viene eseguito normalmente si trova nello stato NORMAL. Se il client remoto si disconnette viene attivato il flag ABORTED. La disconnessione di un client remoro è generalmente causata dalla pressione del tasto STOP da parte dell'utente. Se invece si raggiunge il limite di tempo imposto dal PHP (vedere set_time_limit()) si attiva lo stato TIMEOUT.
Si può decidere se la disconnessione del client debba fare abortire lo script o meno. In certi casi è più pratico lasciare finire lo script anche se non c'è più il browser remoto a ricevere i dati. Tuttavia il comportamento di default è di fare abortire lo script quando il client remoto si disconnette. Questo comportamento può essere impostato tramite la direttiva di php.ini ignore_user_abort oppure tramite la corrispondente direttiva "php_value ignore_user_abort" del file .conf di Apache oppure con la funzione ignore_user_abort(). Se non si segnala al PHP di ignorare la disconssessione dell'utente lo script sarà interrotto. Unica eccezione si ha con la registrazione di una funzione di chiusura utilizzando register_shutdown_function(). Con una funzione di shutdown, quando l'utente remoto preme il bottone di STOP, alla prima occasione in cui lo script tenterà di produrre un output, il PHP intercetterà che la connessione è interrotta e richiamerà la funzione di shutdown. Questa funzione sarà richiamata anche al normale termine dello script, pertanto per eseguire passi differenti in caso di disconnessione del client occorre utilizzare la funzione connection_aborted(). Questa funzione restituisce TRUE se la connessione è stata interrotta.
Uno script può essere fermato dal timer incorporato nel PHP. Per default il timeout è impostato a 30 secondi. Tale limite può essere variato agendo sulla direttiva max_execution_time nel php.ini o nel corrispondente parametro php_value max_execution_time nella configurazione di Apache, oppure con la funzione set_time_limit(). Quando termina il tempo impostato lo script viene interrotto, se è stata prevista una funzione di shutdown, questa verrà eseguita. All'interno di questa funzione si può discriminare se è stata attivata per lo scadere del timeout utilizzando la funzione connection_timeout(). Questa restituisce 2 se la funzione di shutdown è stata chiamata per lo scadere del tempo a disposizione.
Un aspetto che occorre notare sui stati ABORTED e TIMEOUT è che possono essere attivi contemporaneamente. Questo può accadere se si è impostato il PHP affinchè ignori le interruzioni da parte dell'utente. Infatti il PHP continua a tenere traccia della disconnessione dell'utente, ma, semplicemente, non viene interrotto lo script. Quindi, quando termina il tempo, lo script sarà interrotto e verrà richiamata la funzione di shutdown, se presente. In questa situazione si avrà che connection_status() restituirà 3.
Connessioni persistenti sono collegamenti che non vengono chiusi quando l'esecusione di uno script viene terminata. Quando è richiesta una connessione persistente, PHP controlla se esiste già una identica connessione persistente (che è rimasta aperta da prima) - e se esiste, la usa. Se non esiste, crea il collegamento. Una connessione 'identica' è una connessione aperta verso lo stesso host, con lo stesso username e la stessa password (dove applicabile).
Chi non ha molta familiarità con il modo in cui lavorano i server web e di come essi distribuiscano il carico potrebbero confondere le connessioni permanenti per ciò che esse non sono. In particolare, non danno la possibilità di aprire 'sessioni utente' sullo stesso collegamento, non danno la possibilità di gestire una transazione in maniera efficiente e sopratutto non fanno molte altre cose. Infatti, per essere molto chiari su questo punto, le connessioni persistenti non hanno nessuna funzionalià che non era disponibile con le loro omonime non-persistenti.
Perché?
Questo ha a che fare con il modo in cui i server web operano. Ci sono tre modi in cui un server web può utilizzare PHP per generare le pagine web.
Il primo metodo ` quello di usare il PHP come un "wrapper" (involucro) CGI. Quando viene eseguito in questa modalità, per ogni pagina che viene richiesta al server web che contenga del codice PHP, viene creata e, alla fine dell'esecuzione, distrutta, una istanza dell'interprete PHP. Poiché viene distrutta alla fine di ogni richiesta, qualunque risorsa abbia acquisito (come ad esempio un collegamento ad un server di database SQL) verrà anch'essa distrutta. In questo caso, non vi è nessun guadagno nell'usare le connessioni persistenti -- semplicemente esse non persistono.
Il secondo, e più popolare, metodo è quello di eseguire il programma PHP come modulo in un server web multiprocesso, cosa che attualmente include solo Apache. Un server multiprocesso ha tipicamente un processo (il padre) che coordina un insieme di processi (i suoi figli) che sono quelli che generano le pagine web. Quando arriva una richiesta da parte di un client, questa è passata ad uno dei figli che in quel momento non è già occupato a servire un altro client. Questo significa che quando lo stesso client effettua una seconda richiesta al server, esso potrà essere servito da un diverso processo figlio rispetto a quello della prima volta. Quando si aprono delle connessioni persistenti, ciascuna pagina successiva che richiede dei servizi SQL, può riutilizzare la connessione al server SQL precedente.
L'ultimo metodo è quello di usare il PHP come una plug-in per un server web multithread. Attualmente PHP 4 supporta ISAPI, WSAPI e NSAPI (su piattaforma Windows), i quali permettono di usare PHP come una plug-in sui server web multithread come FastTrack (iPlanet) di Netscape, Internet Information Server (IIS) di Microsoft e WebSite Pro di O'Reilly. Il comportamento è essenzialmente lo stesso che si ha nel modello multiprocesso descritto prima. Si noti che il supporto SAPI non è disponibile in PHP 3.
Se le connessioni persistenti non hanno nessuna funzionalità aggiuntiva, perch´ usarle?
La risposta, in questo caso è estremamente semplice: efficienza. Le connessioni persistenti sono utili se il carico di lavoro necessario per aprire una connessione al server SQL è alto. Che il carico sia molto alto o meno dipende da molti fattori. Quali, il tipo di database che si utilizza, il fatto che esso si trovi sulla stessa macchina sulla quale si trova il server web, quanto carico di lavoro ha la macchina sulla quale si trova il server SQL, e molte altre ragioni. Il fatto importante è che se il carico di lavoro necessario per aprire le connessioni è alto, le connessioni persistenti possono aiutare in maniera considerevole. Fanno in modo che il processo figlio si colleghi semplicemente una volta durante la sua intera vita, invece di collegarsi ogni volta che processa una pagina che richiede una connessione al server SQL. Questo significa che per ogni figlio che ha aperto una connessione persistente, si avrà una nuova connessione persistente aperta verso il server. Per esempio, se si hanno 20 diversi processi figlio che eseguono uno script che crea una connessione persistente al server SQL server, si avranno 20 diverse connessioni al server SQL, una per ogni figlio.
Si fa notare, tuttavia, che questo può avere degli svantaggi se si fa uso di un database che ha un limite al numero di connessioni, minore rispetto al numero delle connessioni persistenti dei procesi figlio. Se per esempio di usa un database con 16 connessioni simultanee, e durante un periodo di intensa attività del web server, 17 processi figlio cercano di collegarsi, uno non sarà in grado di farlo. Se nei vostri script ci sono bug che non permettono alle connessioni di chiudersi in maniera regolare (come ad esempio un loop infinito), un database con sole 16 connessioni diventerà rapidamente saturo. Fare riferimento alla documentazione del database per informazioni su come gestire connessioni abbandonate o inattive.
Avvertimento |
Ci sono un paio di altri caveat da tenere in considerazione quando si usano le connessioni persistenti. Uno è che quando si usa il table locking su una connessione persistente, se lo script, per una qualunque ragione non è in grado di rimuovere il blocco, allora i successivi script che useranno la stessa connessione rimarranno bloccati in maniera indefinita e potrebbe essre necessario riavviare il server httpd o il server database. Un altro è che quando si usano le transazioni, un transaction block verrà trasferito anche allo script successivo che usa la medesima connessione, se lo script in esecuzione termina prima che sia terminato il transaction block. In entrambi i casi, si può usare register_shutdown_function() per registrare una semplice funzione di pulizia per sbloccare le tabelle o effettuare il roll back delle transaczioni. Sarebbe meglio non dover affrontare il problema, semplicemente non usando le connessioni persistenti negli script che usano i lock delle tabelle o le transaczioni (si possono comunque usare in altre situazioni). |
Sommario importante. Le connessioni persistenti sono state pensate per avere una mappatura uno-a-uno con le connessioni di tipo normale. Ciò significa che si dovrebbe sempre essere in grado di cambiare una connessione persistente con una connessione non-persistente, e che questo non dovrebbe cambiare il modo in cui lo script si comporta. Può (e probabilmente succederà) cambiare l'efficienza dello script, ma non il suo comportamento!
Vedere anche fbsql_pconnect(), ibase_pconnect(), ifx_pconnect(), ingres_pconnect(), msql_pconnect(), mssql_pconnect(), mysql_pconnect(), ocipLogon(), odbc_pconnect(), ora_pLogon(), pfsockopen(), pg_pconnect() e sybase_pconnect().
La modalità Safe Mode è un tentativo di risolvere il problema di sicurezza derivante dalla condivisione del server. Dal punto di vista architetturale non è corretto cercare di risolvere questo problema al livello del PHP, ma poiché le alternative al livello del web server e del SO (Sistema Operativo) non sono realistiche, in molti, specialmente ISP (Internet Service Provider), utilizzano la modalità sicura.
Tabella 42-1. Direttive di configurazione della Modalità sicura e Sdella icurezza
Nome | Default | Changeable | Changelog |
---|---|---|---|
safe_mode | "0" | PHP_INI_SYSTEM | |
safe_mode_gid | "0" | PHP_INI_SYSTEM | Disponibile dal PHP 4.1.0. |
safe_mode_include_dir | NULL | PHP_INI_SYSTEM | Disponibile dal PHP 4.1.0. |
safe_mode_exec_dir | "" | PHP_INI_SYSTEM | |
safe_mode_allowed_env_vars | "PHP_" | PHP_INI_SYSTEM | |
safe_mode_protected_env_vars | "LD_LIBRARY_PATH" | PHP_INI_SYSTEM | |
open_basedir | NULL | PHP_INI_SYSTEM | |
disable_functions | "" | php.ini only | Disponibile dal PHP 4.0.1. |
disable_classes | "" | php.ini only | Disponibile dal PHP 4.3.2. |
Breve descrizione dei parametri di configurazione.
Abilita o disabilita la modalità sicura di PHP's. Leggere il capitolo Sicurezza per ulteriori informazioni.
Di default, Safe Mode does a UID compare check when opening files. If you want to relax this to a GID compare, then turn on safe_mode_gid. Whether to use UID (FALSE) or GID (TRUE) checking upon file access.
UID/GID checks are bypassed when including files from this directory and its subdirectories (directory must also be in include_path or full path must including).
As of PHP 4.2.0, this directive can take a colon (semi-colon on Windows) separated path in a fashion similar to the include_path directive, rather than just a single directory.
The restriction specified is actually a prefix, not a directory name. This means that "safe_mode_include_dir = /dir/incl" also allows access to "/dir/include" and "/dir/incls" if they exist. When you want to restrict access to only the specified directory, end with a slash. For example: "safe_mode_include_dir = /dir/incl/"
If PHP is used in safe mode, system() and the other functions executing system programs refuse to start programs that are not in this directory. You have to use / as directory separator on all environments including Windows.
Setting certain environment variables may be a potential security breach. This directive contains a comma-delimited list of prefixes. In Safe Mode, the user may only alter environment variables whose names begin with the prefixes supplied here. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR).
Nota: If this directive is empty, PHP will let the user modify ANY environment variable!
This directive contains a comma-delimited list of environment variables that the end user won't be able to change using putenv(). These variables will be protected even if safe_mode_allowed_env_vars is set to allow to change them.
Limit the files that can be opened by PHP to the specified directory-tree, including the file itself. This directive is NOT affected by whether Safe Mode is turned On or Off.
When a script tries to open a file with, for example, fopen() or gzopen(), the location of the file is checked. When the file is outside the specified directory-tree, PHP will refuse to open it. All symbolic links are resolved, so it's not possible to avoid this restriction with a symlink.
The special value . indicates that the working directory of the script will be used as the base-directory. This is, however, a little dangerous as the working directory of the script can easily be changed with chdir().
In httpd.conf, open_basedir can be turned off (e.g. for some virtual hosts) the same way as any other configuration directive with "php_admin_value open_basedir none".
Under Windows, separate the directories with a semicolon. On all other systems, separate the directories with a colon. As an Apache module, open_basedir paths from parent directories are now automatically inherited.
The restriction specified with open_basedir is actually a prefix, not a directory name. This means that "open_basedir = /dir/incl" also allows access to "/dir/include" and "/dir/incls" if they exist. When you want to restrict access to only the specified directory, end with a slash. For example: "open_basedir = /dir/incl/"
Nota: Support for multiple directories was added in 3.0.7.
The default is to allow all files to be opened.
This directive allows you to disable certain functions for security reasons. It takes on a comma-delimited list of function names. disable_functions is not affected by Safe Mode.
This directive must be set in php.ini For example, you cannot set this in httpd.conf.
This directive allows you to disable certain classes for security reasons. It takes on a comma-delimited list of class names. disable_classes is not affected by Safe Mode.
This directive must be set in php.ini For example, you cannot set this in httpd.conf.
Availability note: This directive became available in PHP 4.3.2
See also: register_globals, display_errors, and log_errors
Le direttive di configurazione che controllano la modalità sicura sono:
safe_mode = Off open_basedir = safe_mode_exec_dir = safe_mode_allowed_env_vars = PHP_ safe_mode_protected_env_vars = LD_LIBRARY_PATH disable_functions = |
Quando safe_mode è attiva (on), il PHP verifica se il proprietario dello script in esecuzione e il proprietario del file su cui si sta operando con una funzione sui file, coincidono. Per esempio:
-rw-rw-r-- 1 rasmus rasmus 33 Jul 1 19:20 script.php -rw-r--r-- 1 root root 1116 May 26 18:01 /etc/passwd |
<?php readfile('/etc/passwd'); ?> |
Warning: SAFE MODE Restriction in effect. The script whose uid is 500 is not allowed to access /etc/passwd owned by uid 0 in /docroot/script.php on line 2 |
Se, invece di safe_mode, viene definita una directory open_basedir allora tutte le operazioni sui file saranno limitate ai file sottostanti la directory specificata. Per esempio (nel file httpd.conf di Apache):
<Directory /docroot> php_admin_value open_basedir /docroot </Directory> |
Warning: open_basedir restriction in effect. File is in wrong directory in /docroot/script.php on line 2 |
È possibile inoltre disabilitare le singole funzioni. Se si aggiunge la seguente riga al file php.ini:
disable_functions readfile,system |
Warning: readfile() has been disabled for security reasons in /docroot/script.php on line 2 |
Questo è un elenco probabilmente ancora incompleto e forse non esatto delle funzioni limitate da Safe Mode.
Tabella 42-2. Funzioni limitate dalla modalità sicura
Funzioni | Limitazioni |
---|---|
dbmopen() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
dbase_open() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
filepro() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
filepro_rowcount() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
filepro_retrieve() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
ifx_*() | sql_safe_mode restrictions, (!= Safe Mode) |
ingres_*() | sql_safe_mode restrictions, (!= Safe Mode) |
mysql_*() | sql_safe_mode restrictions, (!= Safe Mode) |
pg_loimport() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
posix_mkfifo() | Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. |
putenv() | Obbedisce le direttive del file ini safe_mode_protected_env_vars e safe_mode_allowed_env_vars. Vedere la documentazione relativa on putenv() |
move_uploaded_file() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
chdir() | Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. |
dl() | Questa funzione è disabilitata nella modalitàsafe-mode |
backtick operator | Questa funzione è disabilitata nella modalitàsafe-mode |
shell_exec() (functional equivalent of backticks) | Questa funzione è disabilitata nella modalitàsafe-mode |
exec() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. |
system() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. |
passthru() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. |
popen() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. |
mkdir() | Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. |
rmdir() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
rename() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. |
unlink() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. |
copy() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. (on source and target) |
chgrp() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
chown() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
chmod() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. In addition, you cannot set the SUID, SGID and sticky bits |
touch() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. |
symlink() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. (note: only the target is checked) |
link() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. (note: only the target is checked) |
getallheaders() | In Safe Mode, headers beginning with 'authorization' (case-insensitive) will not be returned. Warning: this is broken with the aol-server implementation of getallheaders()! |
Qualsiasi funzione che utilizza php4/main/fopen_wrappers.c | ?? |
A partire dalla versione 4.3.0, il PHP supporta un nuovo tipo di SAPI (Server Application Programming Interface) chiamata CLI che significa Interfaccia per la Linea di Comando (Command Line Interface). Come il nome stesso suggerisce, questo tipo di SAPI è mirato allo sviluppo di applicazioni shell (o desktop) con PHP. Esistono alcune differenze tra la CLI SAPI e le altre SAPI; queste saranno illustrate nel corrente capitolo. Val la pena ricordare che CLI e CGI sono differenti SAPI sebbene condividano il medesimo comportamento in diverse situazioni.
La CLI SAPI è stata rilasciata per la prima volta con PHP 4.2.0, ma era ancora sperimentale e quindi doveva essere esplicitamente abilitata con --enable-cli nell'esecuzione di ./configure. A partire dal PHP 4.3.0 la CLI SAPI non viene più considerata sperimentale e quindi l'opzione --enable-cli è attivata per default. Vedere --disable-cli per disabilitare l'opzione.
Dal PHP 4.3.0, il nome, la posizione, e l'esistenza di eseguibili CLI/CGI differirà in base a come il PHP sarà installato sul sistema. Per default quando si esegue il make, si compila sia la versione CLI sia la versione CGI e saranno poste rispettivamente in sapi/cgi/php e sapi/cli/php a partire dalla directory dei sorgenti. Occorre notare che entrambi gli eseguibili sono chiamati php. Ciò che accade durante l'esecuzione di dipende dalla linea di configurazione. Se durante la configurazione si è scelto un modulo SAPI, tipo apxs, o si è attivato --disable-cgi, l'eseguibile CLI viene copiato in durante make install, altrimenti in questa cartella sarà posto l'eseguibile CGI. Così, per esempio, se si ha come parametro di configurazione --with--apxs allora l'eseguibile CLI sarà copiato in {PREFIX}/bin/php durante make install. Se si vuole evitare l'installazione dell'eseguibile CGI, utilizzare make install-cli dopo make install. In alternativa si può specificare --disable-cgi nella linea di configurazione.
Nota: Poichè sia --enable-cli sia --enable-cgi sono abilitati per default, avere semplicemente --enable-cli nella linea di configurazione non significa necessariamente che l'eseguibile CLI sia copiato come {PREFIX}/bin/php con l'esecuzione di make install.
Nel pacchetto per Windows, nelle versioni tra PHP 4.2.0 e PHP 4.2.3, l'eseguibile CLI era presente come php-cli.exe, nella medesima cartella della versione CGI php.exe. A partire dal PHP 4.3.0 nel pacchetto per Windows la versione CLI viene distribuita come php.exe in una cartella a parte chiamata cli, avendo perciò cli/php.exe. A partire dal PHP 5, la versione CLI viene inserita nella cartella principale, con il nome php.exe. La versione CGI sarà chiamata php-cgi.exe.
Sempre dal PHP 5, sarà introdotto un nuovo file chiamato php-win.exe. Questo è equivalente alla versione CLI, tranne che php-win non visualizzerà nulla e quindi non vi sarà la finestra di console (non compare la fienstra dos nello schermo). Questo comportamento è stato ripreso da php-gtk. Si dovrebbe configurare il PHP con --enable-cli-win32.
Quale SAPI ho?: Da shell, digitando php -v si avrà l'informazione di quale php si tratta, CGI o CLI. Vedere anche la funzione php_sapi_name()e la costante PHP_SAPI per dettagli.
Nota: Una pagina stile man di Unix è stata aggiunta in PHP 4.3.2. La si può visualizzare digitando man php da linea di comando.
Le principali differenze tra la CLI SAPI e le altre SAPI sono:
A differenza di CGI SAPI, non sono inviate in output delle intestazioni.
Mentre nella CGI SAPI esiste un modo per sopprimere le intestazioni, nella CLI SAPI non si ha una opzione per abilitare le intestazioni.
Per default CLI parte in modalità silenziosa, si è mantenuto, comunque, l'opzione -q e --no-header per motivi di compatibilità; in questo modo si possono utlizzare i vecchi script CGI.
Non cambia la directory di lavoro in quella dello script. (E' rimasta l'opzione -C e --no-chdir per compatibilità)
Messaggi di errore in formato testo (non formattati in HTML).
Esistono, inoltre, alcune direttive del php.ini che sono forzate nell'impostazione dalla CLI SAPI poichè non hanno senso nell'ambiente di shell:
Tabella 43-1. Direttive del php.ini forzate
Direttiva | CLI SAPI valore di default | Commento |
---|---|---|
html_errors | FALSE | E' difficile leggere i messaggi di errore nella shell quando sono affogati in tag HTML prive di significato; pertanto il default della direttiva è impostato a FALSE. |
implicit_flush | TRUE | E' desiderabile che ogni tipo di output proveniente da print(), echo() e simili sia scritto immediatamente e non venga bufferizzato. Tuttavia è ancora possibile utilizzare le funzioni di controllo dell'output se si desidera ritardare o manipolare lo standard output. |
max_execution_time | 0 (unlimited) | Considerate le svariate possibilità offerte da PHP nell'ambiente di shell, il tempo massimo di esecuzione è stato impostato a infinito. Mentre nelle applicazione scritte per il web i tempi di esecuzione sono rapidi, le applicazioni di shell tendono ad avere tempi di esecuzione molto più lunghi. |
register_argc_argv | TRUE |
Poichè è impostato a TRUE nella CLI SAPI si ha sempre la possibilità di accedere alla variabili argc (numero di argomenti passati all'applicazione) e argv (matrice degli argumenti). A partire da PHP 4.3.0, quando si utilizza la CLI SAPI le variabili PHP $argc e $argv sono sempre registrate e valorizzate in modo appropriato. Prima di questa versione la creazione di queste variabili era coerente con il comportamento delle versioni CGI e MODULO le quali richiedevano che la direttiva PHP register_globals fosse impostata a on. A prescindere dalla versione o dall'impostazione di register_globals si può sempre accedere alle variabili $_SERVER o $HTTP_SERVER_VARS. Esempio: $_SERVER['argv'] |
Nota: Queste direttive non possono essere inizializate con altri valori dal file di configurazione php.ini o da uno personalizzato (se specifictao). Questa è una limitazione perchè questi valori di default sono applicati dopo avere esaminato tutti i file di configurazione. Tuttavia i loro valori possono essere cambiati durante l'esecuzione (operazione che non ha senso per queste direttive, ad esempio register_argc_argv).
Per potere lavorare meglio con le shell, sono state definite le seguenti costanti:
Tabella 43-2. Costanti specifiche per CLI
Costante | Descrizione | ||
---|---|---|---|
STDIN |
Un flusso già aperto allo stdin. Questo evita di
aprirlo con
| ||
STDOUT |
Un flusso già aperto allo stdout. Questo evita di
aprirlo con
| ||
STDERR |
Un flusso già aperto allo stderr. Questo evita di
aprirlo con
|
Stante a quanto descritto non occorre più aprire in autonomia flussi per, ad esempio, lo stderr, ma semplicemente si può usare le costanti anzichè una nuova risorsa di flusso:
php -r 'fwrite(STDERR, "stderr\n");' |
La CLI SAPI non cambia la directory corrente in quella dello script eseguito!
Il seguente esempio illustra la diferenza rispetto alla CGI SAPI:
<?php // Semplice esempio di test chiamato test.php echo getcwd(), "\n"; ?> |
Quando si usa la versione CGI, si avrà il seguente output:
$ pwd /tmp $ php -q another_directory/test.php /tmp/another_directory |
Utilizzando la versione CLI SAPI abbiamo:
$ pwd /tmp $ php -f another_directory/test.php /tmp |
Nota: La CGI SAPI supporta il comportamento della CLI SAPI attivando l'opzione -C quando viene eseguito da linea di comando.
L'elenco completo delle opzioni del PHP disponibili da linea di comando può essere visualizzato in qualsiasi momento eseguendo il PHP con l'opzione -h:
Usage: php [options] [-f] <file> [--] [args...] php [options] -r <code> [--] [args...] php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...] php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...] php [options] -- [args...] -a Run interactively -c <path>|<file> Look for php.ini file in this directory -n No php.ini file will be used -d foo[=bar] Define INI entry foo with value 'bar' -e Generate extended information for debugger/profiler -f <file> Parse <file>. -h This help -i PHP information -l Syntax check only (lint) -m Show compiled in modules -r <code> Run PHP <code> without using script tags <?..?> -B <begin_code> Run PHP <begin_code> before processing input lines -R <code> Run PHP <code> for every input line -F <file> Parse and execute <file> for every input line -E <end_code> Run PHP <end_code> after processing all input lines -H Hide any passed arguments from external tools. -s Display colour syntax highlighted source. -v Version number -w Display source with stripped comments and whitespace. -z <file> Load Zend extension <file>. args... Arguments passed to script. Use -- args when first argument starts with - or script is read from stdin |
La vesione CLI SAPI ha tre differenti modi per eseguire il codice PHP:
Dire al PHP di eseguire certi file.
php my_script.php php -f my_script.php |
Passare il codice PHP da eseguire direttamente da linea di comando.
php -r 'print_r(get_defined_constants());' |
Nota: Osservando con attenzione l'esempio si nota l'assenza dei tag di inizio e fine! L'opzione -r non li richiede. L'uso dei tag genera un errore di parsing.
Si può passare il codice PHP da eseguire via standard input (stdin).
Questo da la possibilità di generare dinamicamente del codice PHP e passarlo all'eseguibile, come illustrato nel seguente esempio (fittizio):
$ some_application | some_filter | php | sort -u >final_output.txt |
Come qualsiasi applicazione di shell, anche l'eseguibile PHP accetta diversi argomenti, ma anche lo script PHP può ricevere argomenti. Il numero degli argomenti passabili allo script non è limitato dal PHP (si rammenta che la shell ha un limite nel numero di caratteri che possono essere passati; solitamente non si raggiunte questo limite). Gli argomenti passati allo script sono disponibili nell'array $argv. L'indice zero contiene sempre il nome dello script (che è - nel caso in cui il codice PHP provenda o dallo standard input o dalla linea di comando con l'opzione -r). La seconda variabile globale registrata è $argc la quale contiene il numero degli elementi nella matrice $argv (non è il numero degli argomenti passati allo script).
Fino a quando gli argomenti passati allo script non iniziano con il carattere - non si deve prestare alcuna cautela. Tuttavia se si passa allo script argomenti che iniziano con - si hanno dei problemi perchè lo stesso PHP ritiene di doverli gestire. Per evitare ciò occorre utilizzare il separatore di argomenti --. Dopo che il PHP ha incontrato questo separatore, ogni argomento verrà passato direttamente allo script.
# Questo non visualizzerà il codice passato, ma l'elenco delle opzioni $ php -r 'var_dump($argv);' -h Usage: php [options] [-f] <file> [args...] [...] # Questo passerà il '-h'allo script ed eviterà al PHP di visualizzare le opzioni $ php -r 'var_dump($argv);' -- -h array(2) { [0]=> string(1) "-" [1]=> string(2) "-h" } |
Tuttvia esiste un'altro modo per eseguire gli script PHP. Si può scrivere uno script la cui prima riga inizi con #!/usr/bin/php. Seguendo questa regola si può posizionare il normale codice PHP tra i tag di apertura e chiusura del PHP. Una volta impostati correttamente gli attributi del file (ad esempio chmod +x test) lo script può essere eseguito come una normale shell o script perl:
#!/usr/bin/php <?php var_dump($argv); ?> |
$ chmod +x test $ ./test -h -- foo array(4) { [0]=> string(6) "./test" [1]=> string(2) "-h" [2]=> string(2) "--" [3]=> string(3) "foo" } |
I parametro lunghi sono disponibili dal PHP 4.3.3.
Tabella 43-3. Opzioni della linea di comando,
Parametro | Parametro lungo | Descrizione | |||
---|---|---|---|---|---|
-a | --interactive |
Esegue il PHP in modo interattivo. | |||
-c | --php-ini |
Con questa opzione si può sia specificare la directory in cui cercare il php.ini o si può specificare un file INI personalizzato (che non deve necessariamente chiamarsi php.ini), ad esempio:
| |||
-n | --no-php-ini |
Ignora del tutto il php.ini. Opzione disponibile dal PHP 4.3.0. | |||
-d | --define |
Questa opzione permette di impostare valori personalizzati per qualsiasi delle direttive di configurazione previste in php.ini. La sintassi è:
Esempi (le linee vanno a capo per motivi di layout):
| |||
-e | --profile-info |
Genera informazioni estese per il debugger/profiler. | |||
-f | --file |
Analizza ed esegue il file passato con l'opzione -f. Questo parametro è opzionale e può essere omesso. Basta fornire il nome del file da eseguire. | |||
-h e -? | --help e --usage | Con questa opzione si ha l'elenco dei comandi di linea ed una breve descrizione di questi. | |||
-i | --info | Questa opzione della linea di comando richiama la funzione phpinfo(), e ne visualizza il risultato. Se il PHP non funziona correttamente, è opportuno utilizzare php -i per verificare se sono visualizzati messaggi di errore prima o al posto della tabella con le informazioni. Fare attenzione quando si usa la modalità CGI, l'output è in formato HTML e quindi abbastanza abbondante. | |||
-l | --syntax-check |
Questa opzione fornisce un metodo pratico per eseguire un controllo sintattico di un dato codice PHP. Se il controllo ha successo, verrà visualizzato il testo No syntax errors detected in <filename> e alla shell sarà restituito il codice 0. Se si rilevano errori si avrà il testo Errors parsing <filename>, inoltre si avranno anche i messaggi di errore del parser ed alla shell sarà restituito il codice 255. Questa opzione non rileva errori fatali (tipo funzioni non definite). Occorre utilizzare l'opzione -f se si desidera rilevare gli errori fatali.
| |||
-m | --modules |
Utilizzare questa opzione per visualizzare i moduli PHP e di Zend integrati (e quindi caricati):
| |||
-r | --run |
Questa opzione permette l'esecuzione di codice PHP direttamente da linea di comando. I tag PHP di apertura e di chiusura (<?php e ?>) non sono necessari anzi, se presenti, causano un errore del parser.
| |||
-B | --process-begin |
Codice PHP da eseguirsi prima di processare stdin. Aggiunto in PHP 5. | |||
-R | --process-code |
Esegue il codice PHP per ogni linea di input. Aggiunto in PHP 5. In questa modalità si hanno due variabili speciali: $argn ed $argi. $argn contiene la linea PHP in elaborazione al momento, mentre $argi contiene il numero di linea. | |||
-F | --process-file |
Esegue il file PHP per ogni linea di input. Aggiunto in PHP 5. | |||
-E | --process-end |
Codice PHP da eseguirsi dopo il processamento dell'input. Aggiunto in PHP 4. Esempio di utilizzo delle opzioni -B, -R e -E per contare il numero di linea di un progetto.
| |||
-s | --syntax-highlight e --syntax-highlighting |
Visualizza il sorgente con sintassi colorata. Questa opzione utilizza il meccanismo interno di parsing dei file e produce una versione HTML del sorgente e la dirige verso lo standard output. Occore notare che questa funzione genera dei blocchi di tag HTML <code> [...] </code> e non le intestazione HTML.
| |||
-v | --version |
Visualizza le versioni di PHP, PHP SAPI, e Zend nello standard output, ad esempio:
| |||
-w | --strip |
Visualizza il sorgente senza gli spazi e i commenti.
| |||
-z | --zend-extension |
Carica l'estensione Zend. Soltano se si fornisce un nome di file, il PHP tenta di caricare l'estensione dal corrente percorso di default delle librerie (solitamente, sui sistemi Linux, /etc/ld.so.conf). Se si fornisce un nome di file con percorso assoluto, ls libreria non sarà cercata nella directory di default. Un nome di file con percorso relativo indica al PHP di tentare di caricare l'estensione con percorso relativo alla directory corrente. |
L'eseguibile PHP può essere utilizzato per eseguire script PHP in modo indipendente dal server web. Se ci si trova su sistemi Unix, si può aggiungere una prima linea speciale allo script PHP e renderlo eseguibile, in questo modo il sistema sa quale programma deve interpretare lo script. Sui sistemi Windows si può associare php.exe all'estensione .php, o si può scrivere un batch per eseguire gli script tramite PHP. La prima riga inserita per i sistemi Unix non crea problemi in Windows, in questo modo si possono scrivere batch multi-piattaforma. Seguirà un semplice esempio di programma PHP da linea di comando.
Esempio 43-1. Script sviluppato per essere esguito da linea di comando (script.php)
|
Nello script precedente, abbiamo utilizzato la prima riga per indicare che questo file deve essere interpretato dal PHP. Poichè qui lavoriamo con la versione CLI non vengono prodotte intestazioni HTTP. Esistono due variabili che si possono utilizzare nelle applicazioni PHP da linea di comando: $argc e $argv. La prima è il numero di argomenti più uno (il nome dello script). La seconda è una matrice contenente gli argomenti, iniziando dal nome dello script all'indice zero ($argv[0]).
Nel programma precedente abbiamo verificato se i parametri passati erano di più o di meno di uno. Inoltre se l'argomento è --help, -help, -h oppure -?, si visualizza un messaggio di aiuto, visualizzando in modo dinamico il nome dello script. Se si riceve un argomento differente questo sarà visualizzato.
Se si desidera eseguire lo script precedente su Unix, occorre, per prima cosa, renderlo eseguibile, e quindi richiamarlo con script.php echothis oppure script.php -h. Su Windows occorre scrivere un batch per ottenere questo risultato:
Assumendo che programma precedente sia chiamato script.php, che la versione CLI di php.exe sia in c:\php\cli\php.exe questo batch eseguirà lo script con le opzioni passate: script.bat echothis oppure script.bat -h.
Vedere anche la documentazione del modulo Readline per informazioni su funzioni che possono essere utilizzate per migliorare le applicazioni da linea di comando.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Queste funzioni sono disponibili unicamente quando PHP è eseguito come modulo Apache.
Nota: A partire dal PHP 4.3.2, PATH_TRANSLATED non viene più impostata i mplicitamente sotto Apache 2 SAPI, diversamente da quanto accadeva in Apache 1, dove questa veniva impostata allo stesso valore di SCRIPT_FILENAME qualora non fosse già riempita. Questa modifica è stata fatta per adeguarsi allla specifica CGI che impone che PATH_TRANSLATED esista solo se PATH_INFO sia definita.
Gli utilizzatori di Apache 2 possono usare AcceptPathInfo = On in httpd.conf per definire PATH_INFO.
Il comportamento del modulo Apache per PHP è influenzato dalle impostazioni in php.ini. Le impostazioni di configurazione del php.ini possono essere scavalcate attraverso le impostazioni php_flag nel file di configurazione del server o nei file .htaccess locali.
Tabella 1. Opzioni di configurazione di Apache
Nome | Default | Modificabile | Funzione |
---|---|---|---|
engine | On | PHP_INI_ALL | accende o spegne l'interprete PHP |
child_terminate | Off | PHP_INI_ALL | decide se gli script PHP possono richiedere la terminazione dei processi figli alla fine della richiesta HTTP, vedere anche apache_child_terminate() |
last_modified | Off | PHP_INI_ALL | manda la data di modifica degli script nell'header Last-Modified: |
xbithack | Off | PHP_INI_ALL | interpreta i file con il bit di esecuzione impostato, a prescindere dalla loro estensione |
Breve descrizione dei parametri di configurazione.
Questa direttiva è utile solo nella versione di PHP compilata come modulo di Apache. Viene usata dai siti che vogliono spegnere e accendere il parsing PHP in base alla directory o al virtual server corrente. Inserendo engine off nel posto appropriato nel file httpd.conf, il PHP può essere abilitato o disabilitato.
(PHP 4 >= 4.0.5, PHP 5)
apache_child_terminate -- Interrompe il processo apache dopo la presente richiestaapache_child_terminate() informa il processo Apache che sta eseguendo la richiesta PHP corrente di terminare quando l'esecuzione del codice PHP è stata completata. Può essere usata per interrompere un processo dopo che sia stato eseguito uno script con alta occupazione di memoria dal momento che la memoria viene normalmente liberata internamente ma non restituita al sistema operativo.
Nota: La disponibilità di questa caratteristica è controllata dalal direttiva del php.ini child_terminate, che è impostata a off di default.
Questa caratteristica non è inoltre disponibile sulle versioni multithread di apache come, ad esempio, la versione win32.
Vedere anche exit().
Get an Apache environment variable as specified by variable.
This function requires Apache 2 otherwise it's undefined.
The Apache environment variable
Whether to get the top-level variable available to all Apache layers.
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
apache_lookup_uri -- Esegue una richiesta parziale della URI specificata e restituisce tutte le informazioniQuesta funzione esegue una richiesta parziale per una URI. Esegue l'operazione finché ottiene tutte le informazioni importanti sulla risorsa e restituisce queste informazioni in una classe. Le proprietà della classe restituita sono:
status |
the_request |
status_line |
method |
content_type |
handler |
uri |
filename |
path_info |
args |
boundary |
no_cache |
no_local_copy |
allowed |
send_bodyct |
bytes_sent |
byterange |
clength |
unparsed_uri |
mtime |
request_time |
Esempio 1. esempio di apache_lookup_uri()
Questo esempio produrrà un risultato simile al seguente:
|
Nota: apache_lookup_uri() funziona solo quando PHP è installato come modulo Apache.
(PHP 3 >= 3.0.2, PHP 4, PHP 5)
apache_note -- Ricava o imposta una variabile nella tabella notes di Apacheapache_note() è una funzione specifica di Apache che ricava o imposta un valore nella tabella notes di una richiesta HTTP. Se viene invocata con un solo argomento restituisce il valore della nota nome_nota. Se viene chiamata con due argomenti, imposta il valore della nota nome_nota a valore e restituisce il valore precedente della nota nome_nota.
apache_request_headers() restituisce un array associativo contenente tutti gli header HTTP nella richiesta corrente. Questa funzionalità è supportata solo quando PHP è un modulo di Apache.
Nota: Prima del PHP 4.3.0, apache_request_headers() si chiamava getallheaders(). Dopo il PHP 4.3.0, getallheaders() è un alias di apache_request_headers().
Nota: È possibile ottenere il valore delle variabili comuni CGI anche leggendole dalle variabili di ambiente; questo funziona indipendentemente dal fatto che si stia usando PHP come modulo Apache. Utilizzare phpinfo() per ottenere una lista di tutte le variabili d'ambiente disponibili.
Nota: Dal PHP 4.3.3 è possibile utilizzare questa funzione anche con il modulo server NSAPI dei server web Netscape/iPlanet/SunONE
Vedere anche apache_response_headers().
apache_reset_timeout() resets the Apache write timer, which defaults to 300 seconds. With set_time_limit(0); ignore_user_abort(true) and periodic apache_reset_timeout() calls, Apache can theoretically run forever.
This function requires Apache 1.
Restituisce un array contenente tutti gli header della risposta HTTP di Apache. Questa funzione è disponibile solo nel PHP 4.3.0 o successivi.
Nota: Dal PHP 4.3.3 è possibile utilizzare questa funzione anche con il modulo server NSAPI dei server web Netscape/iPlanet/SunONE
Vedere anche getallheaders() e headers_sent().
apache_setenv() imposta il valore della variabile di environment di Apache specificata da variabile.
Nota: Quando si imposta una variabile di environment di Apache, la corrispondente variabile $_SERVER non viene cambiata.
apache_setenv() può essere usata con apache_getenv() su pagine separate o impostare variabili da passare a Server Side Includes (.shtml) chr siano stati inclusi negli script PHP.
Vedere anche apache_getenv().
ascii2ebcdic() è una funzione Apache che è disponibile solo su sistemi operativi basati sull'EBCDIC (OS/390, BS2000). Traduce la stringa codificata in ASCII ascii_str nella sua rappresentazione equivalente EBCDIC (proteggendo i dati binari), e restituisce il risultato.
Vedere anche la funzione duale ebcdic2ascii()
ebcdic2ascii() è una funzione Apache che è disponibile solo su sistemi operativi basati su EBCDIC (OS/390, BS2000). Traduce la stringa codificata in EBCDIC ebcdic_str nella sua rappresentazione equivalente ASCII (proteggendo i dati binari), e restituisce il risultato.
Vedere anche la funzione duale ascii2ebcdic()
getallheaders() è un alias di apache_request_headers(). Restituisce un array associativo contenente tutti gli header HTTP nella richiesta corrente. Leggere la documentazione di apache_request_headers() per ulteriori informazioni sul funzionamento.
Nota: Nel PHP 4.3.0 getallheaders() è diventata un alias di apache_request_headers(). In breve, è stata rinominata. Ciò dipende dal fatto che questa funzione è disponibile soltanto quando PHP è compilato come modulo di Apache.
Nota: Dal PHP 4.3.3 è possibile utilizzare questa funzione anche con il modulo server NSAPI dei server web Netscape/iPlanet/SunONE
Vedere anche apache_request_headers().
virtual() è una funzione specifica Apache che è equivalente a <!--#include virtual...--> in mod_include. Esegue una sotto-richiesta Apache. È utile ad includere script CGI o file .shtml, o qualsiasi altra cosa si voglia fa analizzarea ad Apache. Si noti che per uno script CGI, questo deve generare degli header CGI validi. Quindi, Come minimo deve generare un header Content-type.
Al fine di eseguire la sotto-richiesta, tutti i buffer vengono chiusi e svuotati verso il browser, e anche gli header in attesa vengono inviati.
Dal PHP 4.0.6, è possibile utilizzare virtual() sui file PHP. Comunque è preferibile usare include() o require() se è necessarei includere un altro file PHP.
Nota: Dal PHP 4.3.3 è possibile utilizzare questa funzione anche con il modulo server NSAPI dei server web Netscape/iPlanet/SunONE
The Alternative PHP Cache (APC) is a free and open opcode cache for PHP. It was conceived of to provide a free, open, and robust framework for caching and optimizing PHP intermediate code.
This PECL extension is not bundled with PHP.
Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/apc.
You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Nota: On Windows, APC expects c:\tmp to exist, and be writable by the web server.
Nota: For more in-depth, highly technical documentation, see the developer-supplied TECHNOTES file .
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Although the default APC settings are fine for many installations, serious users should consider tuning the following parameters.
Tabella 1. APC configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
apc.enabled | 1 | PHP_INI_ALL | |
apc.shm_segments | 1 | PHP_INI_SYSTEM | |
apc.shm_size | 30 | PHP_INI_SYSTEM | |
apc.optimization | 0 | PHP_INI_ALL | |
apc.num_files_hint | 1000 | PHP_INI_SYSTEM | |
apc.ttl | 0 | PHP_INI_SYSTEM | |
apc.gc_ttl | 3600 | PHP_INI_SYSTEM | |
apc.cache_by_default | On | PHP_INI_SYSTEM | |
apc.filters | "" | PHP_INI_SYSTEM | |
apc.mmap_file_mask | "" | PHP_INI_SYSTEM | |
apc.slam_defense | 0 | PHP_INI_SYSTEM | |
apc.file_update_protection | 2 | PHP_INI_SYSTEM | |
apc.enable_cli | 0 | PHP_INI_SYSTEM | > APC 3.0.6 |
Breve descrizione dei parametri di configurazione.
apc.enabled can be set to 0 to disable APC. This is primarily useful when APC is statically compiled into PHP, since there is no other way to disable it (when compiled as a DSO, the extension line in php.ini can just be commented-out).
The number of shared memory segments to allocate for the compiler cache. If APC is running out of shared memory but you have already set apc.shm_size as high as your system allows, you can try raising this value.
The size of each shared memory segment in MB. By default, some systems (including most BSD variants) have very low limits on the size of a shared memory segment.
The optimization level. Zero disables the optimizer, and higher values use more aggressive optimizations. Expect very modest speed improvements. This is experimental.
A "hint" about the number of distinct source files that will be included or requested on your web server. Set to zero or omit if you're not sure; this setting is mainly useful for sites that have many thousands of source files.
The number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that your cache could potentially fill up with stale entries while newer entries won't be cached.
The number of seconds that a cache entry may remain on the garbage-collection list. This value provides a failsafe in the event that a server process dies while executing a cached source file; if that source file is modified, the memory allocated for the old version will not be reclaimed until this TTL reached. Set to zero to disable this feature.
On by default, but can be set to off and used in conjunction with positive apc.filters so that files are only cached if matched by a positive filter.
A comma-separated list of POSIX extended regular expressions. If any pattern matches the source filename, the file will not be cached. Note that the filename used for matching is the one passed to include/require, not the absolute path. If the first character of the expression is a + then the expression will be additive in the sense that any files matched by the expression will be cached, and if the first character is a - then anything matched will not be cached. The - case is the default, so it can be left off.
If compiled with MMAP support by using --enable-mmap this is the mktemp-style file_mask to pass to the mmap module for determing whether your mmap'ed memory region is going to be file-backed or shared memory backed. For straight file-backed mmap, set it to something like /tmp/apc.XXXXXX (exactly 6 Xs). To use POSIX-style shm_open/mmap put a .shm somewhere in your mask. e.g. /apc.shm.XXXXXX You can also set it to /dev/zero to use your kernel's /dev/zero interface to anonymous mmap'ed memory. Leaving it undefined will force an anonymous mmap.
On very busy servers whenever you start the server or modify files you can create a race of many processes all trying to cache the same file at the same time. This option sets the percentage of processes that will skip trying to cache an uncached file. Or think of it as the probability of a single process to skip caching. For example, setting apc.slam_defense to 75 would mean that there is a 75% chance that the process will not cache an uncached file. So, the higher the setting the greater the defense against cache slams. Setting this to 0 disables this feature.
When you modify a file on a live web server you really should do so in an atomic manner. That is, write to a temporary file and rename (mv) the file into its permanent position when it is ready. Many text editors, cp, tar and other such programs don't do this. This means that there is a chance that a file is accessed (and cached) while it is still being written to. This apc.file_update_protection setting puts a delay on caching brand new files. The default is 2 seconds which means that if the modification timestamp (mtime) on a file shows that it is less than 2 seconds old when it is accessed, it will not be cached. The unfortunate person who accessed this half-written file will still see weirdness, but at least it won't persist. If you are certain you always atomically update your files by using something like rsync which does this correctly, you can turn this protection off by setting it to 0. If you have a system that is flooded with io causing some update procedure to take longer than 2 seconds, you may want to increase this a bit.
Mostly for testing and debugging. Setting this enables APC for the CLI version of PHP. Normally you wouldn't want to create, populate and tear down the APC cache on every CLI request, but for various test scenarios it is handy to be able to enable APC for the CLI version of APC easily.
Array of cached data (and meta-data), or FALSE on failure
Nota: apc_cache_info() will raise a warning if it is unable to retrieve APC cache data. This typically occurs when APC is not enabled.
Esempio 1. A apc_cache_info() example
Il precedente esempio visualizzerà qualcosa simile a:
|
define() is notoriously slow. Since the main benefit of APC is to increase the performance of scripts/applications, this mechanism is provided to streamline the process of mass constant definition.
Nota: To remove a set of stored constants (without clearing the entire cache), an empty array may be passed as the constants parameter, effectively clearing the stored value(s).
The key serves as the name of the constant set being stored. This key is used to retrieve the stored constants in apc_load_constants().
An associative array of constant_name => value pairs. The constant_name must follow the normal constant naming rules. value must evaluate to a scalar value.
The default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.
The name of the constant set (that was stored with apc_define_constants()) to be retrieved.
The default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.
Nota: Unlike many other mechanisms in PHP, variables stored using apc_store() will persist between requests (until the value is removed from the cache).
Store the variable using this name. keys are cache-unique, so storing a second value with the same key will overwrite the original value.
The variable to store
Time To Live; store var in the cache for ttl seconds. After the ttl has passed, the stored variable will be expunged from the cache (on the next request). If no ttl is supplied (or if the ttl is 0), the value will persist until it is removed from the cache manually, or otherwise fails to exist in the cache (clear, restart, etc.).
APD is the Advanced PHP Debugger. It was written to provide profiling and debugging capabilities for PHP code, as well as to provide the ability to print out a full stack backtrace. APD supports interactive debugging, but by default it writes data to trace files. It also offers event based logging so that varying levels of information (including function calls, arguments passed, timings, etc.) can be turned on or off for individual scripts.
Attenzione |
APD is a Zend Extension, modifying the way the internals of PHP handle function calls, and thus may or may not be compatible with other Zend Extensions (for example Zend Optimizer). |
APD is currently available as a PECL extension from http://pecl.php.net/package/apd. Make sure you have installed the CGI version of PHP and it is available in your current path along with the phpize script.
Run the following command to download, build, and install the latest stable version of APD:
pear install apd |
This automatically installs the APD Zend module into your PHP extensions directory. It is not mandatory to keep it there; you can store the module in any directory PHP can read as long as you set the zend_extension parameter accordingly.
Windows users can download the extension dll php_apd.dll from http://snaps.php.net/win32/PECL_STABLE/.
In your INI file, add the following lines:
zend_extension = /absolute/path/to/apd.so apd.dumpdir = /absolute/path/to/trace/directory apd.statement_tracing = 0 |
Depending on your PHP build, the zend_extension directive can be one of the following:
zend_extension (non ZTS, non debug build) zend_extension_ts ( ZTS, non debug build) zend_extension_debug (non ZTS, debug build) zend_extension_debug_ts ( ZTS, debug build) |
To build APD under Windows you need a working PHP compilation environment as described on http://php.net/ -- basically, it requires you to have Microsoft Visual C++, win32build.zip, bison/flex, and some know how to get it to work. Also ensure that adp.dsp has DOS line endings; if it has unix line endings, Microsoft Visual C++ will complain about it.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. APD Configuration Options
Name | Default | Changeable | Changelog |
---|---|---|---|
apd.dumpdir | NULL | PHP_INI_ALL | |
apd.statement_tracing | "0" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
Sets the directory in which APD writes profile dump files. You can specify an absolute path or a relative path.
You can specify a different directory as an argument to apd_set_pprof_trace().
Specfies whether or not to do per-line tracings. Turning this on (1) will impact the performance of your application.
As the first line of your PHP script, call the apd_set_pprof_trace() function to start the trace:
apd_set_pprof_trace(); |
You can insert the line anywhere in your script, but if you do not start tracing at the beginning of your script you discard profile data that might otherwise lead you to a performance bottleneck.
Now run your script. The dump output will be written to apd.dumpdir/pprof_pid.ext.
Suggerimento: If you're running the CGI version of PHP, you will need to add the '-e' flag to enable extended information for apd to work properly. For example: php -e -f script.php
To display formatted profile data, issue the pprofp command with the sort and display options of your choice. The formatted output will look something like:
bash-2.05b$ pprofp -R /tmp/pprof.22141.0 Trace for /home/dan/testapd.php Total Elapsed Time = 0.00 Total System Time = 0.00 Total User Time = 0.00 Real User System secs/ cumm %Time (excl/cumm) (excl/cumm) (excl/cumm) Calls call s/call Memory Usage Name -------------------------------------------------------------------------------------- 100.0 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0000 0.0009 0 main 56.9 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0005 0.0005 0 apd_set_pprof_trace 28.0 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 preg_replace 14.3 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 str_replace |
The -R option used in this example sorts the profile table by the amount of real time the script spent executing a given function. The "cumm call" column reveals how many times each function was called, and the "s/call" column reveals how many seconds each call to the function required, on average.
To generate a calltree file that you can import into the KCacheGrind profile analysis application, issue the pprof2calltree comand.
If you have comments, bugfixes, enhancements or want to help developing this beast, you can send an mail to apd@mail.communityconnect.com. Any help is very welcome.
This can be used to stop the running of your script, and await responses on the connected socket. To step the program, just send enter (a blank line), or enter a php command to be executed. A typical session using tcplisten would look like this.
bash#tcplisten localhost 7777 APD - Advanced PHP Debugger Trace File --------------------------------------------------------------------------- Process Pid (6118) Trace Begun at Sun Mar 10 23:13:12 2002 --------------------------------------------------------------------------- ( 0.000000): apd_set_session_trace called at /home/alan/Projects/project2/test. php:5 ( 0.074824): apd_set_session_trace_socket() at /home/alan/Projects/project2/tes t.php:5 returned. Elapsed (0.074824) ( 0.074918): apd_breakpoint() /home/alan/Projects/project2/test.php:7 ++ argv[0] $(??) = 9 apd_breakpoint() at /home/alan/Projects/project2/test.php:7 returned. Elapsed ( -2089521468.1073275368) >\n statement: /home/alan/Projects/project2/test.php:8 >\n statement: /home/alan/Projects/project2/test.php:8 >\n statement: /home/alan/Projects/project2/test.php:10 >apd_echo($i); EXEC: apd_echo($i); 0 >apd_echo(serialize(apd_get_active_symbols())); EXEC: apd_echo(serialize(apd_get_active_symbols())); a:47:{i:0;s:4:"PWD";i:1;s:10:"COLORFGBG";i:2;s:11:"XAUTHORITY";i:3;s:14:" COLORTERM_BCE";i:4;s:9:"WINDOWID";i:5;s:14:"ETERM_VERSION";i:6;s:16:"SE SSION_MANAGER";i:7;s:4:"PS1";i:8;s:11:"GDMSESSION";i:9;s:5:"USER";i:10;s:5:" MAIL";i:11;s:7:"OLDPWD";i:12;s:5:"LANG";i:13;s:10:"COLORTERM";i:14;s:8:"DISP LAY";i:15;s:8:"LOGNAME";i:16;s:6:" >apd_echo(system('ls /home/mydir')); ........ >apd_continue(0); |
(no version information, might be only in CVS)
apd_callstack -- Returns the current call stack as an arrayBehaves like perl's Carp::cluck. Throw a warning and a callstack. The default line delimiter is "<BR />\n".
Usually sent via the socket to restart the interpreter.
(no version information, might be only in CVS)
apd_croak -- Throw an error, a callstack and then exitBehaves like perl's Carp::croak. Throw an error, a callstack and then exit. The default line delimiter is "<BR />\n".
(no version information, might be only in CVS)
apd_dump_function_table -- Outputs the current function table(no version information, might be only in CVS)
apd_dump_persistent_resources -- Return all persistent resources as an arrayReturn all persistent resources as an array.
(no version information, might be only in CVS)
apd_dump_regular_resources -- Return all current regular resources as an arrayReturn all current regular resources as an array.
Usually sent via the socket to request information about the running script.
(no version information, might be only in CVS)
apd_get_active_symbols -- Get an array of the current variables names in the local scopeReturns the names of all the variables defined in the active scope, (not their values)
Starts debugging to {dump_directory}/pprof_{process_id}, if dump_directory is not set, then the apd.dumpdir setting from the php.ini file is used.
Starts debugging to {dump_directory}/apd_dump_{process_id}, if dump_directory is not set, then the apd.dumpdir setting from the php.ini file is used.
debug_level is an integer which is formed by adding together the following values:
FUNCTION_TRACE 1 ARGS_TRACE 2 ASSIGNMENT_TRACE 4 STATEMENT_TRACE 8 MEMORY_TRACE 16 TIMING_TRACE 32 SUMMARY_TRACE 64 |
I would seriously not recommend using MEMORY_TRACE. It is very slow and does not appear to be accurate (great, huh?) also ASSIGNMENT_TRACE is not implemented. So, to turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99
(no version information, might be only in CVS)
apd_set_session -- Changes or sets the current debugging levelThis can be used to increase or decrease debugging in a different area of your application,.debug_level is an integer which is formed by adding together the following values:
FUNCTION_TRACE 1 ARGS_TRACE 2 ASSIGNMENT_TRACE 4 STATEMENT_TRACE 8 MEMORY_TRACE 16 TIMING_TRACE 32 SUMMARY_TRACE 64 |
(no version information, might be only in CVS)
apd_set_socket_session_trace -- Starts the remote session debuggingConnects to the tcp server (eg. tcplisten) specified IP or Unix Domain socket (like a file), and sends debugging data to the socket. You can use any port, but higher numbers are better as most of the lower numbers may be used by other system services.
the socket_type can be APD_AF_UNIX (for file based sockets) or APD_AF_INET (for standard tcp/ip)
debug_level is an integer which is formed by adding together the following values:
FUNCTION_TRACE 1 ARGS_TRACE 2 ASSIGNMENT_TRACE 4 STATEMENT_TRACE 8 MEMORY_TRACE 16 TIMING_TRACE 32 SUMMARY_TRACE 64 |
I would seriously not recommend setting the value to 'zero' to start with, and use the breakpoint methods to start debugging at a specific place in the file.
Syntax similar to create_function(). Overrides built-in functions (replaces them in the symbol table).
Queste funzioni permettono di manipolare e interagire con gli array in vari modi. Gli array sono indispensabili per immagazzinare, mantenere e operare su gruppi di variabili.
Sono supportati sia array semplici che multi-dimensionali, che possono essere sia creati dall'utente che da funzioni. Ci sono specifiche funzioni di database per riempire gli array a partire da interrogazioni sui dati, e parecchie funzioni restituiscono array.
Vedere la sezione Array del manuale per una spiegazione dettagliata di come gli array siano implementati ed usati in PHP. Vedere anche per altri modi di manipolazione degli array.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Le costanti qui elencate sono sempre disponibili in quanto parte del core di PHP.
CASE_LOWER è usata con array_change_key_case() per convertire le chiavi degli array in minuscolo. Questo è il valore di default per array_change_key_case().
CASE_UPPER è usata con array_change_key_case() per convertire le chiavi degli array in maiuscolo.
flag per l'ordinamento:
SORT_ASC è usata con array_multisort() per ordinare in senso crescente.
SORT_DESC è usata con array_multisort() per ordinare in senso decrescente.
flag per il tipo di ordinamento: usati da varie funzioni di ordinamento
SORT_REGULAR è usata per comparare gli oggetti in modo normale.
SORT_NUMERIC è usata per comparare gli oggetti in modo numerico.
SORT_STRING è usata per comparare gli oggetti come se fossero stringhe.
SORT_LOCALE_STRING è utilizzata per confrontare gli oggetti come stringhe, basandosi sul locale corrente. Aggiunto nel PHP 4.3.12 e 5.0.2.
(PHP 4 >= 4.2.0, PHP 5)
array_change_key_case -- Restituisce un array con tutte le chiavi cambiate in maiuscolo o in minuscoloarray_change_key_case() cambia le chiavi nell'array input in modo che siano tutte minuscole o maiuscole. Il tipo di cambiamento dipende dal parametro opzionale case. Si possono usare due costanti, CASE_UPPER per le maiuscole e CASE_LOWER per le minuscole. Il default è CASE_LOWER. La funzione non modifica le chiavi numeriche.
Se un array ha degli indici che risulteranno identici dopo l'esecuzione di questa funzione (es. "keY" e "kEY") il valore dell'ultimo indice sovrascrivera' gli altri.
array_chunk() spezza l'array in più array di dimensione dimensione. L'ultimo array potrebbe ovviamente avere una dimensione inferiore. Gli array sono restituiti in un array multidimensionale indicizzato con chiavi che partono da zero.
Impostando il parametro opzionale preserve_keys a TRUE, si forza PHP a mantenere le chiavi originarie dell'array di input. Se si imposta a FALSE come chiavi verranno usati in ogni array dei numeri crescenti a partire da zero. Il default è FALSE.
Esempio 1. esempio di array_chunk()
Il precedente esempio visualizzerà:
|
(PHP 5)
array_combine -- Crea un'array utilizzando un'array per le chiavi e un'altro per i suoi valoriRestituisce un'array utilizzando i valori dell'array keys come chiavi e i valori dall' array values come valori corrispondenti.
Restituisce FALSE se il numero degli elementi in ogni array non è uguale o se gli array sono vuoti.
Vedere anche array_merge(), array_walk() e array_values().
array_count_values() restituisce un array che ha i valori dell'array input per chiavi e la loro frequenza in input come valori.
Vedere anche count(), array_unique(), array_values() e count_chars().
(PHP 4 >= 4.3.0, PHP 5)
array_diff_assoc -- Calcola la differenza tra due o più array con un ulteriore controllo sull'indicearray_diff_assoc() restituisce un array contenente tutti i valori di array1 che non sono presenti in alcuno degli altri array. Si noti che le chiavi sono utilizzate nel confronto, diversamente da array_diff().
Esempio 1. esempio di array_diff_assoc()
Il risultato è:
|
Nell'esempio si vede che la coppia "a" => "verde" è presente in entrambi gli array e quindi non è nel risultato della funzione. Invece, la coppia 0 => "rosso" è nel risultato perché nel secondo argomento "red" cha come chiave 1.
Due valori delle coppie chiave => valore sono considerati uguali solo se (string) $elem1 === (string) $elem2 . In altre parole c'è un controllo stringente che si accerta che le rappresentazioni sotto forma di stringa siano uguali.
Nota: Si noti che questa funzione controlla solo una dimensione di un array n-dimensionale. Ovviamente è possibile controllare le altre dimensioni usando array_diff_assoc($array1[0], $array2[0]);.
Vedere anche array_diff(), array_intersect(), and array_intersect_assoc().
array_diff_key() returns an array containing all the values of array1 that have keys that are not present in any of the other arguments. Note that the associativity is preserved. This function is like array_diff() except the comparison is done on the keys instead of the values.
Esempio 1. array_diff_key() example
Il precedente esempio visualizzerà:
|
The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same.
Nota: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_key($array1[0], $array2[0]);.
See also array_diff(), array_udiff() array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_diff_ukey(), array_intersect(), array_intersect_assoc(), array_intersect_uassoc(), array_intersect_key() and array_intersect_ukey().
(PHP 5)
array_diff_uassoc -- Computes the difference of arrays with additional index check which is performed by a user supplied callback functionarray_diff_uassoc() returns an array containing all the values from array1 that are not present in any of the other arguments. Note that the keys are used in the comparison unlike array_diff().
This comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. This is unlike array_diff_assoc() where an internal function for comparing the indices is used.
Esempio 1. array_diff_uassoc() example
Il precedente esempio visualizzerà:
|
In our example above you see the "a" => "green" pair is present in both arrays and thus it is not in the ouput from the function. Unlike this, the pair 0 => "red" is in the ouput because in the second argument "red" has key which is 1.
The equality of 2 indices is checked by the user supplied callback function.
Nota: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_diff_uassoc($array1[0], $array2[0], "key_compare_func");.
See also array_diff(), array_diff_assoc(), array_udiff(), array_udiff_assoc(), array_udiff_uassoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().
(PHP 5 >= 5.1.0RC1)
array_diff_ukey -- Computes the difference of arrays using a callback function on the keys for comparisonarray_diff_ukey() returns an array containing all the values of array1 that have keys that are not present in any of the other arguments. Note that the associativity is preserved. This function is like array_diff() except the comparison is done on the keys instead of the values.
This comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first key is considered to be respectively less than, equal to, or greater than the second.
Esempio 1. array_diff_ukey() example
Il precedente esempio visualizzerà:
|
Nota: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_ukey($array1[0], $array2[0], 'callback_func');.
See also array_diff(), array_udiff() array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_diff_key(), array_intersect(), array_intersect_assoc(), array_intersect_uassoc(), array_intersect_key() and array_intersect_ukey().
array_diff() restituisce un array contenente tutti i valori di array1 che non sono presenti in alcuno degli altri array. Si noti che le associazioni con le chiavi vengono mantenute.
Esempio 1. Esempio di array_diff()
Occorrenze multiple in $array1 sono tutte trattate nello stesso modo. Questo codice mostrerà:
|
Nota: Due elementi sono considerati uguali se e solo se (string) $elem1 === (string) $elem2. Ovvero: quando la rappresentazione sotto forma di stringa è la stessa.
Nota: Si noti che questa funzione controlla solo una dimensione di un array n-dimensionale. Ovviamente è possibile controllare le altre dimensioni usando array_diff($array1[0], $array2[0]);.
Avvertimento |
Questa funzione era errata nel PHP 4.0.4! |
Vedere anche array_diff_assoc(), array_intersect() e array_intersect_assoc().
array_fill() riempie un array con num elementi inizializzati con il valore del parametro valore, e con le chiavi che partono dal valore del parametro start_index. Si noti che num deve essere un valore maggiore di zero, altrimenti PHP mostrerà un avvertimento.
Vedere anche str_repeat() e range().
array_filter() esegue un'iterazione su ogni valore nell' array input passandolo alla funzione. Se funzione restituisce TRUE, il valore corrente di input viene restituito nell'array risultato. Le chiavi sono mantenute.
Esempio 1. Esempio di array_filter()
Il precedente esempio visualizzerà:
|
Gli utenti non possono modificare l'array attraverso la funzione di callback, ad esempio aggiungere/togliere un elemento, o cancellare l'array su cui array_filter() è applicata. Se l'array viene cambiato, il comportamento di questa funzione non è definito.
Se la funzione callback non viene indicata, array_filter() rimuoverà tutti gli elementi di input che siano uguali a FALSE. Vedere conversione a boolean per ulteriori informazioni.
Vedere anche array_map() e array_reduce().
array_flip() restituisce un array scambiato, ovvero le chiavi di trans diventano valori e i valori di trans diventano chiavi.
Si noti che i valori di trans devono poter diventare chiavi valide, ovvero devo essere di tipo integer o string. Un errore verrà segnalato se un valore ha il tipo errato, e la coppia chiave/valore in questione non verrà scambiata.
Se un valore ha più di una occorrenza, L'ultima chiave verrà usata come valore, e tutte le altre verranno perse.
array_flip() restituisce FALSE se fallisce.
Vedere anche array_values(), array_keys() e array_reverse().
(PHP 4 >= 4.3.0, PHP 5)
array_intersect_assoc -- Calcola l'intersezione degli array con un ulteriore controllo sugli indiciarray_intersect_assoc() restituisce un array contenente tutti i valori di array1 che siano presenti in tutti gli array passati come argomento. Si noti che le chiavi sono utilizzate nel confronto, diversamente da array_intersect().
Nell'esempio si vede che solo la coppia "a" => "verde" è presente in entrambi gli array e quindi viene restituita. Il valore "rosso" non viene restituito perché in $array1 la sua chiave è 0 mentre la chiave di "rosso" in $array2 è 1.
I due valori delle coppie chiave => valore sono considerati uguali solo se (string) $elem1 === (string) $elem2 . In altre parole viene eseguito un controllo stringente che si accerta che le rappresentazioni sotto forma di stringa siano uguali.
Vedere anche array_intersect(), array_uintersect_assoc(), array_intersect_uassoc(), array_uintersect_uassoc(), array_diff() e array_diff_assoc().
(PHP 5 >= 5.1.0RC1)
array_intersect_key -- Computes the intersection of arrays using keys for comparisonarray_intersect_key() returns an array containing all the values of array1 which have matching keys that are present in all the arguments.
Esempio 1. array_intersect_key() example
Il precedente esempio visualizzerà:
|
In our example you see that only the keys 'blue' and 'green' are present in both arrays and thus returned. Also notice that the values for the keys 'blue' and 'green' differ between the two arrays. A match still occurs because only the keys are checked. The values returned are those of array1.
The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same.
See also array_diff(), array_udiff() array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_diff_key(), array_diff_ukey(), array_intersect(), array_intersect_assoc(), array_intersect_uassoc() and array_intersect_ukey().
(PHP 5)
array_intersect_uassoc -- Computes the intersection of arrays with additional index check, compares indexes by a callback functionarray_intersect_uassoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are used in the comparison unlike in array_intersect().
The index comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
Esempio 1. array_intersect_uassoc() example
Il precedente esempio visualizzerà:
|
See also array_intersect(), array_intersect_assoc(), array_uintersect_assoc(), array_uintersect_uassoc(), array_intersect_key() and array_intersect_ukey().
(PHP 5 >= 5.1.0RC1)
array_intersect_ukey -- Computes the intersection of arrays using a callback function on the keys for comparisonarray_intersect_ukey() returns an array containing all the values of array1 which have matching keys that are present in all the arguments.
This comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first key is considered to be respectively less than, equal to, or greater than the second.
Esempio 1. array_intersect_ukey() example
Il precedente esempio visualizzerà:
|
In our example you see that only the keys 'blue' and 'green' are present in both arrays and thus returned. Also notice that the values for the keys 'blue' and 'green' differ between the two arrays. A match still occurs because only the keys are checked. The values returned are those of array1.
See also array_diff(), array_udiff() array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_diff_key(), array_diff_ukey(), array_intersect(), array_intersect_assoc(), array_intersect_uassoc() and array_intersect_key().
array_intersect() restituisce un array contenente tutti i valori di array1 che siano presenti in tutti gli array passati come argomento. Si noti che le associazioni con le chiavi sono mantenute.
Nota: Due elementi sono considerati uguali solo e solo se (string) $elem1 === (string) $elem2. Ovvero: quando la rappresentazione sotto forma di stringa è la stessa.
Vedere anche array_intersect_assoc(), array_diff() e array_diff_assoc().
(PHP 4 >= 4.1.0, PHP 5)
array_key_exists -- Controlla se l'indice (o chiave) specificato esiste nell'arrayarray_key_exists() restituisce TRUE se il parametro chiave esiste nell'array. chiave può essere qualsiasi valore accettabile per un indice di array.
Nota: Il nome di questa funzione è key_exists() nel PHP 4.0.6.
Vedere anche isset(), array_keys() e in_array().
array_keys() rstituisce le chiavi, numeriche e stringa, dell'array input.
Se il parametro opzionale valore_ricerca è specificato, solo le chiavi che corrispondono a quel valore vengono restituite. Altrimenti, vengono restituite tutte le chiavi dell'array input.
Esempio 1. Esempio di array_keys()
Il risultato di questo programma sarà:
|
Vedere anche array_values() e array_key_exists().
(PHP 4 >= 4.0.6, PHP 5)
array_map -- Applica la funzione callback a tutti gli elementi dell'array datoarray_map() restituisce un array contenente tutti gli elementi di arr1 dopo che è stata loro applicata la funzione callback. Il numero di parametri che la funzione callback accetta deve corrispondere al numero di array passati alla funzione array_map()
Esempio 2. array_map() - usare più array
Il precedente esempio visualizzerà:
|
Generalmente, quando si usano due o più array, questi devono avere eguale lunghezza in quanto la funzione callback viene applicata in parallelo agli elementi corrispondenti. Se gli array sono di lunghezza diversa, il più corto verrà esteso con elementi vuoti.
Un uso interessante di questa funzione è quello di costruire un array di array, cosa che può essere facilmente ottenuta usando NULL come nome della funzione callback
Esempio 3. Creare un array di array
Il precedente esempio visualizzerà:
|
Vedere anche array_filter(), array_reduce(), array_walk() e information about the callback type.
Array_merge_recursive() fonde gli elementi di due o più array in modo tale che i valori di un array siano accodati all'array precedente. Restituisce l'array risultante.
Se gli array in input hanno le stesse chiavi stringa, i valori di queste chiavi vengono fusi in un array, e questo è fatto in modo ricorsivo, cio` se uno dei valori è un array, la funzione lo fonder%agrave; con una voce corrispondente in un altro array Comunque, se gli array hanno la stessa chiave numerica, l'ultimo valore non sovrascriver` il valore originale, bensì verrà accodato.
Esempio 1. Esempio di array_merge_recursive()
La variabile $risultato sarà:
|
Vedere anche array_merge().
array_merge() fonde gli elementi di uno o più array in modo che i valori di un array siano accodati a quelli dell'array precedente. Restituisce l'array risultante.
Se gli array in input hanno le stesse chiavi stringa, l'ultimo valore di quella chiave sovrascriverà i precedenti. Comunque, se gli array hanno le stesse chiavi numeriche, l'ultimo valore non sovrascriverà quello originale, bensì sarà accodato.
Se viene fornito un solo array, e questo è indicizzato numericamente, le chiavi vengono reindicizzate in una sequenza continua. Nel caso di array associativi, delle chiavi duplicate rimane solo l'ultima. Vedere l'esempio tre per ulteriori dettagli.
Esempio 1. Esempio di array_merge()
La variabile $risultato sarà:
|
Esempio 2. Esempio di array_merge()
Non dimenticarsi che le chiavi numeriche saranno rinumerate!
Se si vogliono preservare gli array e li si vuole solo concatenare, usare l'operatore +:
La chiave numerica sarà preservata e così pure l'associazione.
|
Esempio 3. esempio di array_merge()
Il risultato sarà:
|
Nota: Le chiavi condivise verranno sovrascritte dalla prima chiave processata.
Vedere anche array_merge_recursive() e array_combine() e operatori sugli array.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Array_multisort() Può essere usata per ordinare parecchi array allo stesso tempo, oppure un array multidimensionale, rispetto a una o più dimensioni.
Mantiene le chiavi associative (tipo string), mentre le chiavi numeriche vengono reindicizzate.
Gli array in input sono trattati come campi di una tabella che vengano ordinati per righe - questo assomiglia alla funzionalità della clausola SQL ORDER BY Il primo array è quello primario, rispetto a cui ordinare. Le righe (valori) in questo array that siano uguali vengono ordinate secondo l'array successivo, e così via.
La struttura degli argomenti di questa funzione è un po' inusuale, ma flessibile. Il primo argomento deve essere un array. In seguito, ogni argomento può essere sia un array che un flag di ordinamento, selezionabile dalla seguente lista.
Flag di ordinamento:
SORT_ASC - ordinamento crescente
SORT_DESC - ordinamento decrescente
Flag di tipo:
SORT_REGULAR - confronta gli elementi in modo normale
SORT_NUMERIC - confronta gli elementi numericamente
SORT_STRING - confronta gli elementi come stringhe
Dopo ogni array, non si possono specificare due flag dello stesso tipo. I flag specificati dopo un array si applicano solo a quell'array - sono reimpostati ai default SORT_ASC e SORT_REGULAR prima di ogni nuovo array passato come argomento.
Esempio 1. Ordinamre più array
In questo esempio, dopo l'ordinamento, il primo array conterrà "10", "a", 100, 100. Il secondo array conterrà 1, 1, "2", 3. Gli elementi del secondo array corrispondenti a quelli, identici, del primo array (100 e 100), vengono pure ordinati.
|
Esempio 2. Ordinamento di array multidimensionali
In questo esempio, dopo l'ordinamento, il primo array conterrà "10", 100, 100, 11, "a" (ordinato come stringhe ordine crescente), e il secondo conterrà 1, 3, "2", 2, 1 (ordinati come numeri, in ordine decrescente).
|
Esempio 3. Ordinamento dei risultati di un database In questo esempio, ogni elemento nell'array data rappresenta un record della tabella. Questo genere di dato è tipico dei record di database. Esempio di dati:
I dati sono in un array, chiamato data. Di solito questo si ottiene ciclando, ad esempio, con mysql_fetch_assoc().
In questo esempio ordineremo volume in senso discendente, edition in senso ascendente. Abbiamo un array di record, ma array_multisort() richiede un array di colonne, quindi usiamo il codice qui sotto per ottenerlo, quindi eseguiremo l'ordinamento.
Il set di dati è ora ordinato, e apparirà così:
|
Esempio 4. Ordinamento senza distinzione tra maiuscole e minuscole Sia SORT_STRING che SORT_REGULAR tengono conto delle maiuscole, le stringhe che iniziano con una maiuscola vengono prima di quelle che iniziano con una minuscola. Per ottenere un ordinamento che ignori le maiuscole, forzarlo in modo che sia determnato da una copia dell'array originale formata da sole minuscole.
Il precedente esempio visualizzerà:
|
array_pad() restituisce una copia di input allungato alla dimensione sepcificata da pad_size con il valore pad_value. Se pad_size è positivo l'array è riempito sulla destra, se è negativo sulla sinistra. Se il valore assoluto di pad_size è minore o uguale alla lunghezza di input non viene effettuata alcuna modifica.
Esempio 1. esempio di array_pad()
|
Vedere anche array_fill() e range().
array_pop() estrae e restituisce l'ultimo valore di array, accorciando array di un elemento. Se array è vuoto (o non è un array), viene restituito NULL.
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
Vedere anche array_push(), array_shift() e array_unshift().
array_product() returns the product of values in an array as an integer or float.
array_push() tratta array come una pila, e accoda le variabili date alla fine di array. La lunghezza di array aumenta del numero di variabili accodate. Ha lo stesso effetto di:
<?php $array[] = $var; ?> |
Restituisce il nuovo numero di elementi nell'array.
Nota: Se si utilizza array_push() per aggiungere un elemento all'array, è preferibile piuttosto utilizzare $array[] = poiché in questo modo non c'è il tempo d'attesa per la chiamata di funzione.
Vedere anche array_pop(), array_shift() e array_unshift().
array_rand() è piuttosto utile quando si vuole estrarre a caso uno o più elementi da un array. Prende un array (input) e un argomento ozpionale (num_req) che specifica quanti elementi estrarre - se non è specificato, è 1 per default.
Se si sta estraendo solo un elemento, array_rand() restituisce la chiave di un elemento. Altrimenti, restituisce un array di chiavi. Questo viene fatto in modo da permettere di estrarre dall'array sia le chiavi che i valori.
Nota: Come in PHP 4.2.0, non vi è necessità di inizializzare il generatore di numeri casuali con srand() oppure con mt_srand() poichè viene eseguito in modo automatico.
Vedere anche shuffle().
(PHP 4 >= 4.0.5, PHP 5)
array_reduce -- Riduce iterativamente l'array a un singolo valore utilizzando una funzione callbackarray_reduce() applica iterativamente la funzione callback agli elementi dell'array input, riducendo l'array a un singolo valore. Seil parametro opzionale intial è specificato, viene usato come valore iniziale all'inizio del processo, o come risultato finale nel caso l'array sia vuoto.
In questo modo $b conterrà 15, $c conterrà 1200 (= 1*2*3*4*5*10) e $d conterrà 1.
Vedere anche array_filter() e array_map(), array_unique() e array_count_values().
array_reverse() prende array e restituisce un nuovo array con l'ordine degli elementi invertito, mantenendo le chiavi sie mantieni_chiavi è TRUE.
Esempio 1. esempio di array_reverse()
Questo fa sì che sia $risultato che $risultato_chiavi abbiano gli stessi elementi, ma si noti la differenza tra le chiavi. La stampa di $risultato e $risultato_chiavi sarà:
|
Nota: Il secondo parametro è stato aggiunto in PHP 4.0.3.
Vedere anche array_flip().
(PHP 4 >= 4.0.5, PHP 5)
array_search -- Ricerca un dato valore in un array e ne restituisce la chiave corrispondente, se la ricerca ha successo.Cerca in pagliaio per trovare ago e restituisce la chiave se viene trovato nell'array, FALSE altrimenti.
Nota: Se ago è una stringa, il confronto è fatto tenendo conto delle maiuscole/minuscole.
Nota: Nelle versioni di PHP antecedenti la 4.2.0, array_search() restituisce NULL invece di FALSE in caso di fallimento.
Se il terzo parametro opzionale strict è impostato a TRUE la funzione array_search() controllerà anche il tipo di ago nell'array pagliaio.
Se ago viene ritrovato in pagliaio più di una nolta, viene restituita la prima chiave trovata. Per restituire le chiavi di tutti i valori, utilizzare array_keys() con il parametro opzionale valore_ricerca.
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
Vedere anche array_keys(), array_values(), array_key_exists() e in_array().
array_shift() estrae il primo elemento di array e lo restituisce, accorciando array di un elemento e spostando tutti gli altri all'indietro. Tutte le chiavi numeriche verranno modificate al fine di iniziare il conteggio da zero, mentre gli indici alfabetici non verranno modificati. Se array è vuoto (o non è un array), viene restituito NULL.
Vedere anche array_unshift(), array_push() e array_pop().
array_slice() restituisce la sequenza di elementi dell'array array come specificato dai parametri offset e length .
Se offset è positivo, la sequenza comincerà da quell'offset in array. Se offset è negativo, la sequenza comincerà alla distanza offset dalla fine di array.
Se length è specificata ed è positiva, la sequenza conterrà quel numero di elementi. Se length è specificata ed è negativa la sequenza si fermerà a quel numero di elementi dalla fine dell'array. Se viene omessa, la sequenza conterrà tutto da offset fino alla fine di array.
Si noti che array_slice() ignorerà le chiavi dell'array, e calcolerè gli spiazzamenti e le lunghezze basandosi sulle posizioni correnti degli elementi nell'array.
Esempio 1. esempi di array_slice()
|
Vedere anche array_splice() e unset().
array_splice() rimuove gli elementi specificati da offset e length dall'array input, e li sostituisce con gli elementi dell'array replacement, se fornito. Restituisce un array contenente gli elementi estratti.
Se offset è positivo l'inizio della porzione rimossa è a quella distanza dall'inizio dell'array input. Se offset è negativo inizia a quella distanza dalla fine dell'array input.
Se length è omessa, rimuove tutti gli elementi da offset alla fine dell'array. Se length è specificata a positiva, quel numero di elementi vengono rimossi. Se length è specificata e negativa la porzione da rimuovere terminerà a length elementi dalla fine dell'array. Suggerimento: per rimuovere tutti gli elementi tra offset e la fine dell'array quando è specificato pure replacement, usare count($input) nel parametro length.
Se l'array replacement è specificato, gli elementi rimossi sono sostituiti dagli elementi di questo array. Se offset e length sono tali per cui niente viene rimosso, gli elementi dell'array replacement sono inseriti nella posizione specificata da offset. Si noti che le chiavi nell'array replacement non sono conservate. Se replacement è composto solo da un elemento non è necessario porlo nel costrutto array(), a meno che l'elemento stesso non sia un array.
Le seguenti espressione cambiano i valori di $input nello stesso modo:
Tabella 1. array_splice() equivalents
array_push($input, $x, $y) | array_splice($input, count($input), 0, array($x, $y)) |
array_pop($input) | array_splice($input, -1) |
array_shift($input) | array_splice($input, 0, 1) |
array_unshift($input, $x, $y) | array_splice($input, 0, 0, array($x, $y)) |
$input[$x] = $y // negli array in cui la chiave è uguale alla posizione | array_splice($input, $x, 1, $y) |
Restituisce un array contenente gli elementi rimossi.
Esempio 1. esempi di array_splice()
|
Vedere anche array_slice()i, unset() e array_merge().
array_sum() restituisce la somma dei valori dell'array sotto forma di integer o float.
Nota: Le versioni di PHP antecedenti alla 4.2.1 modificavano l'array stesso e convertivano le stringhe in numeri (le quali erano convertite in zeri la maggior parte delle volte, a seconda dal valore).
(PHP 5)
array_udiff_assoc -- Computes the difference of arrays with additional index check, compares data by a callback functionarray_udiff_assoc() returns an array containing all the values from array1 that are not present in any of the other arguments. Note that the keys are used in the comparison unlike array_diff() and array_udiff(). The comparison of arrays' data is performed by using an user-supplied callback. In this aspect the behaviour is opposite to the behaviour of array_diff_assoc() which uses internal function for comparison.
Esempio 1. array_udiff_assoc() example
Il precedente esempio visualizzerà:
|
In our example above you see the "1" => new cr(4) pair is present in both arrays and thus it is not in the ouput from the function.
For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
Nota: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_udiff_assoc($array1[0], $array2[0], "some_comparison_func");.
See also array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff(), array_udiff_uassoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().
(PHP 5)
array_udiff_uassoc -- Computes the difference of arrays with additional index check, compares data and indexes by a callback functionarray_udiff_uassoc() returns an array containing all the values from array1 that are not present in any of the other arguments. Note that the keys are used in the comparison unlike array_diff() and array_udiff(). The comparison of arrays' data is performed by using an user-supplied callback : data_compare_func. In this aspect the behaviour is opposite to the behaviour of array_diff_assoc() which uses internal function for comparison. The comparison of keys (indices) is done also by the callback function key_compare_func. This behaviour is unlike what array_udiff_assoc() does, since the latter compares the indices by using an internal function.
Esempio 1. array_udiff_uassoc() example
Il precedente esempio visualizzerà:
|
In our example above you see the "1" => new cr(4) pair is present in both arrays and thus it is not in the ouput from the function. Keep in mind that you have to supply 2 callback functions.
For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
Nota: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_udiff_uassoc($array1[0], $array2[0], "data_compare_func", "key_compare_func");.
See also array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff(), array_udiff_assoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().
(PHP 5)
array_udiff -- Computes the difference of arrays by using a callback function for data comparisonarray_udiff() returns an array containing all the values of array1 that are not present in any of the other arguments. Note that keys are preserved. For the comparison of the data data_compare_func is used. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. This is unlike array_diff() which uses an internal function for comparing the data.
Esempio 1. array_udiff() example
Il precedente esempio visualizzerà:
|
Nota: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_udiff($array1[0], $array2[0], "data_compare_func");.
See also array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().
(PHP 5)
array_uintersect_assoc -- Computes the intersection of arrays with additional index check, compares data by a callback functionarray_uintersect_assoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are used in the comparison unlike in array_uintersect(). The data is compared by using a callback function.
Esempio 1. array_uintersect_assoc() example
Il precedente esempio visualizzerà:
|
For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
See also array_uintersect(), array_intersect_assoc(), array_intersect_uassoc() and array_uintersect_uassoc().
(PHP 5)
array_uintersect_uassoc -- Computes the intersection of arrays with additional index check, compares data and indexes by a callback functionsarray_uintersect_uassoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are used in the comparison unlike in array_uintersect(). Both the data and the indexes are compared by using a callback functions.
Esempio 1. array_uintersect_uassoc() example
Il precedente esempio visualizzerà:
|
For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
See also array_uintersect(), array_intersect_assoc(), array_intersect_uassoc() and array_uintersect_assoc().
(PHP 5)
array_uintersect -- Computes the intersection of arrays, compares data by a callback functionarray_uintersect() returns an array containing all the values of array1 that are present in all the arguments. The data is compared by using a callback function.
Esempio 1. array_uintersect() example
Il precedente esempio visualizzerà:
|
For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
See also array_intersect(), array_uintersect_assoc(), array_intersect_uassoc() and array_uintersect_uassoc().
array_unique() prende array e restituisce un nuovo array senza i valori duplicati.
Si noti che le chiavi sono mantenute. array_unique() ordina i valori trattandoli come stringhe, quindi mantiene la prima chiave trovata per ogni valore, e ignorerà tutte le altre chiavi. Questo non significa che la chiave del primo valore dell'array non ancora ordinato verrà mantenuta.
Nota: Due elementi sono considerati uguali se e solo se (string) $elem1 === (string) $elem2. Ovvero: quando la rappresentazione sotto forma di stringa è la stessa.
Verrà usato il primo elemento.
array_unshift() aggiunge gli elementi specificati in testa ad array. Si noti che la lista di elementi è aggiunta in blocco, in modo tale che gli elementi rimangano nello stesso ordine. Tutte le chiavi numeriche vengono modificate per iniziare da zero mentre le chiavi alfabetiche non sono modificate.
Restituisce il nuovo numero di elementi in array.
Vedere anche array_shift(), array_push() e array_pop().
array_values() restituisce tutti i valori dell'array input e indicizza numericamente l'array.
Vedere anche array_keys().
Applies the user-defined function funcname to each element of the input array. This function will recur into deeper arrays. Typically, funcname takes on two parameters. The input parameter's value being the first, and the key/index second. If the optional userdata parameter is supplied, it will be passed as the third parameter to the callback funcname.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference. Then, any changes made to those elements will be made in the original array itself.
Esempio 1. array_walk_recursive() example
Il precedente esempio visualizzerà:
You may notice that the key 'sweet' is never displayed. Any key that holds an array will not be passed to the function. |
See also array_walk(), and information about the callback type.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esegue la funzione definita dall'utente identificata da funzione su ogni elemento di array. Normalmente funzione accetta due parametri. Il valore del parametro array viene passato per primo, la chiave/indice per secondo. Se il parametro datiutente è specificato, verrà passato come terzo parametro alla funzione callback.
Se funzione richiede più parametri di quanti gliene vengono passati, un errore di livello E_WARNING verrà generato ogni volta che array_walk() la chiama. Questi avvertimenti possono essere soppressi apponendo l'operatore d'errore @ alla chiamata di array_walk(), oppure usando error_reporting().
Nota: Se funzione deve lavorare con i reali valori dell'array, specificare che il primo parametro di funzione deve essere passato come riferimento. A qesto punto ogni modifica a questi elementi verrà effettuata sull'array stesso.
Nota: Il passaggio della chiave e di datiutente a func è stato aggiunto nella versione 4.0.
array_walk() non è influenzato dal puntatore interno dell'array array. array_walk() percorrerà l'intero array indipendentemente dalla posizione del puntatore. Per reinizializzare il puntatore, utilizzare reset(). In PHP 3, array_walk() reinizializza il puntatore.
Gli utenti non possono modificare l'array attraverso la funzione di callback, ad esempio aggiungere/togliere un elemento, o cancellare l'array su cui array_walk() è applicata. Se l'array viene cambiato, il comportamento di questa funzione non è definito ed è imprevedibile.
Esempio 1. esempio di array_walk()
Il risultato del programma sarà:
|
Vedere anche array_walk_recursive(), create_function(), list(), foreach, each(), call_user_func_array() e array_map()
Restituisce un array contenente i parametri. Ai parametri si può dare un indice con l'operatore =>. Leggere la sezione relativa ai tipi per ulteriori informazioni sugli array.
Nota: array() è un costrutto del linguaggio usato per rappresentare array letterali, e non una normale funzione.
La sintassi "indice => valori", separati da virgole, definisce indici e valori. indice può essere di tipo string o numerico. Quando l'indice è omesso, viene generato automaticamente un indice intero, a partire da 0. Se l'indice è un intero, il successivo indice generato sarà l'indice intero più grande + 1. Si noti che quando due indici identici vengono definiti, l'ultimo sovrascrive il primo.
L'esempio seguente dimostra come creare un array bidimensionale, come specificare le chiavi per gli array associativi, e come modificare la serie degli indici numerici negli array normali.
Si noti che l'indice '3' è definito due volte, e che mantiene il valore finale 13. L'indice 4 è definito dopo l'indice 8, e il successivo indice generato (valore 19) è 9, dal momento che l'indice più grande era 8.
Questo esempio crea un array che parte da 1 (1-based).
Vedere anche array_pad(), list(), foreach e range().
(PHP 3, PHP 4, PHP 5)
arsort -- Ordina un array in ordine decrescente e mantiene le associazioni degli indiciQuesta funzione ordina un array in modo tale che i suoi indici mantengano la loro correlazione con gli elementi ai quali sono associati. Viene usata principalmente nell'ordinamento degli array associativi, quando la disposizione originaria degli elementi è importante.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. esempio di arsort()
Questo esempio mostrerà:
|
I frutti sono ordinati in ordine alfabetico decrescente, e l'indice associato a ogni elemento è stato mantenuto.
È possibile modificare il comportamento dell'ordinamento usando il parametro opzionale sort_flags, per maggiori dettagli vedere sort().
Questa funzione ordina un array in modo tale che i suoi indici mantengano la loro correlazione con gli elementi ai quali sono associati. Viene usata principalmente nell'ordinamento degli array associativi, quando la disposizione originaria degli elementi è importante.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
I frutti sono ordinati in ordine alfabetico, e l'indice associato ad ogni elemento è stato mantenuto.
È possibile modificare il comportamento dell'ordinamento usando il parametro opzionale sort_flags, per maggiori dettagli vedere sort().
compact() accetta un numero variabile di parametri. Ogni parametro può essere una stringa contenente il nome della variabile, o un array di nomi di variabile. L'array può contenere altri array di nomi di variabile; compact() se ne occupa in modo ricorsivo.
Per ognuno di questi, compact() cerca la variabile con quel nome nella tabella dei simboli corrente, e la aggiunge all'array di output in modo tale che il nome della variabile diventi la chiave e i contenuti della variabile diventino il valore associato a quella chiave. In breve, compact() è l'opposto di extract(). Restituisce l'array di output con tutte le variabili aggiunte a quest'ultimo.
Qualsiasi stringa non valorizzata verrà semplicemente ignorata.
Gotcha: Dal momento che le variabili variabili non posso essere utilizzate con gli array Superglobal di PHP nelle funzioni, gli array Superglobal non possono essere passati alla funzione compact().
Vedere anche extract().
Restituisce il numero di elementi in var, la quale è di norma un array, dal momento che qualsiasi altro oggetto avrà un elemento.
Per gli oggetti, se SPL è installato, è possibile agganciarsi a count() implementando l'interfaccia Countable. L'interfaccia ha esattamente un metodo, count(), che ritorna il valore restituito dalla funzione count().
Se var non è un array o un oggetto con l'interfaccia Countable implementata, verrà restituito 1 C'è una eccezione, se var è NULL, verrà restituito 0.
Nota: Il parametro opzionale mode è disponibile da PHP 4.2.0.
Se il parametro opzionale mode è impostato a COUNT_RECURSIVE (o 1), count() conterà ricorsivamente l'array. Questo è utile in particolare per contare tutti gli elementi di un array multidimensionale. Il valore di default per mode è 0. count() non identifica le ricorsioni infinite.
Attenzione |
count() può restituire 0 per una variabile che non è impostata, ma può anche restituire 0 per una variabile che è stata inizializzata con un array vuoto. Usare isset() per verificare se una variabile è impostata. |
Vedere la sezione Array nel manuale per una spiegazione dettagliata di come gli array siano implementati ed usati in PHP.
Esempio 2. esempio di count() ricorsiva (PHP >= 4.2.0)
|
Vedere anche is_array(), isset() e strlen().
Ogni array ha un puntatore interno all'elemento "corrente", che è inizializzato al primo elemento inserito nell'array.
La funzione current() restituisce il valore dell'elemento che è attualmente puntato dal puntatore interno. In ogni caso non muove il puntatore. Se il puntatore interno punta oltre la fine della lista di elementi, current() restituisce FALSE.
Avvertimento |
Se l'array contiene elementi vuoti (0 o "", la stringa vuota) la funzione restituirà FALSE pure per questi elementi. Questo rende impossibile stabilire se si è veramente alla fine della lista in un array di questo tipo usando current(). Per attraversare in modo corretto un array che può contenere elementi vuoti, usare la funzione each(). |
Esempio 1. Esempio di current() e funzioni relative
|
(PHP 3, PHP 4, PHP 5)
each -- Restituisce la corrente coppia chiave/valore di un array e incrementa il puntatore dell'arrayRestituisce la corrente coppia chiave/valore corrente di array e incrementa il puntatore interno dell'array. Questa coppia è restituita in un array di quattro elementi, con le chiavi 0, 1, key, and value. Gli elementi 0 e key contengono il nome della chiave dell'elemento dell'array, mentre 1 e value contengono i dati.
Se il puntatore interno dell'array punta oltre la fine dei contenuti dell'array, each() restituisce FALSE.
<?php $foo = array("Robert" => "Bob", "Seppo" => "Sepi"); $bar = each($foo); print_r($bar); ?> |
$bar ora contiene la seguente coppia chiave/valore:
Array ( [1] => Bob [value] => Bob [0] => Robert [key] => Robert ) |
each() viene normalmente usata in congiunzione con list() nell'attraversamento di un array; ecco un esempio:
Dopo l'esecuzione di each(), il puntatore dell'array viene lasciato sull'elemento successivo, o sull'ultimo elemento se si è alla fine dell'array. Si deve utilizzare reset() se si vuole riattraversare l'array usando each().
Attenzione |
Poiché assegnare un array ad un'altra variabile reimposta il puntatore, il nostro esempio diventerebbe un loop infinito se assegnassimo $frutta ad un'altra variabile all'interno del ciclo. |
Vedere anche key(), list(), current(), reset(), next(), prev() e foreach.
end() fa avanzare il puntatore di array all'ultimo elemento, e restituisce il suo valore.
Questa funzione viene usata per importare delle variabili da un array nella tabella dei simbloi corrente. Riceve un array associativo var_array e interpreta le chiavi come nomi di variabile e i valori come valori di variabile. Per ogni coppia chiave/valore verrà creata una variabile nella tabella dei simboli corrente, coerentemente con i parametri extract_type e prefix.
Nota: Dalla versione 4.0.5 questa funzione restituisce il numero di variabili estratte.
Nota: EXTR_IF_EXISTS e EXTR_PREFIX_IF_EXISTS sono stati introdotti nella versione 4.2.0.
Nota: EXTR_REFS è stata introdotta nella versione 4.3.0.
extract() controlla ogni chiave per stabilire se costituisce un nome valido di variabile e se ci sono collisioni con variabili già esistenti nella tabella dei simboli. Il modo in cui vengono trattate le chiavi invalide/numeriche e le collisioni è determinato da extract_type. Può essere uno dei seguenti valori:
Se avviene una collisione, sovrascrive la variabile esistente.
Se avviene una collisione, non sovrascrive la variabile esistente.
Se avviene una collisione, mette come prefisso al nome della variabile il parametro prefix.
Mette come prefisso di tutte le variabili il parametro prefix. Dal PHP 4.0.5 questo avviene anche per i valori numerici.
Mette come prefisso, solo per i nomi di variabili invalidi/numerici, il parametro prefix. Questa opzione è stata aggiunta in PHP 4.0.5.
Sovrascrive la variabile solo se già esiste nella tabella dei simboli, altrimenti non fa nulla. Questo è utile per definire una lista di variabili valide e quindi estrarre solo quelle variabili definite in $_REQUEST, per esempio. Questa opzione è stata aggiunta in PHP 4.2.0.
Crea nomi di variabili con il prefisso solo se la versione senza prefisso della stessa variable esiste nella tabella dei simboli. Questa opzione è stata aggiunta in PHP 4.2.0.
Estrae le variabili come riferimenti. Questo in effetti significa che i valori delle variabili importate referenziano i valori del parametro var_array. Si può usare questo flag da solo o combinarlo con gli altri mediante un OR nel parametro extract_type. Questo flag è stato aggiunto nel PHP 4.3.0.
Se extract_type non è specificato, si assume che sia EXTR_OVERWRITE.
Si noti che prefix è richiesto solo se extract_type è EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID o EXTR_PREFIX_IF_EXISTS. Se il risultato non è un nome di variabile valido, non viene importato nella tabella dei simboli.
extract() restituisce il numero di variabili importate con successo nella tabella dei simboli.
Avvertimento |
Non utilizzare extract() su dati non convalidati, come gli input degli utenti ($_GET, ...). Se lo si deve fare, ad esempio per eseguire temporaneamente vecchio codice basato su register_globals, sincerarsi di utilizzare uno dei valori di extract_type come EXTR_SKIP e ricordarsi che occorre estrarre $_SERVER, $_SESSION, $_COOKIE, $_POST e $_GET in questo ordine. |
Un possibile uso di extract() è quello di importare nella tabella dei simboli variabili contenute in un array associativo restituito da wddx_deserialize().
Esempio 1. esempio diextract()
L'esempio mostrerà:
|
La variabile $dimensione non è stata sovrascritta, in quanto è specificato EXTR_PREFIX_SAME, che ha portato alla creazione di $wddx_dimensione. Se fosse stato specificato EXTR_SKIP, $wddx_dimensione non sarebbe stata creata. EXTR_OVERWRITE avrebbe portato $dimensione ad assumere il valore "medio", e EXTR_PREFIX_ALL avrebbe fatto creare nuove variabili chiamate $wddx_colore, $wddx_dimensione e $wddx_forma.
Si deve usare un array associativo, un array indicizzato numericamente non produce risultati a meno di non usare EXTR_PREFIX_ALL o EXTR_PREFIX_INVALID.
Vedere anche compact().
Cerca in pagliaio per trovare ago e restituisce TRUE se viene trovato nell'array, FALSE altrimenti.
Se il terzo parametro strict è TRUE la funzione in_array() controllerà anche il tipo di ago nell'array haystack.
Nota: Se ago è una stringa, il confronto è effettuato tenendo conto delle maiuscole/minuscole.
Nota: Nelle versioni di PHP precedenti la 4.2.0. ago non poteva essere un array.
Esempio 1. esempio di in_array()
La seconda condizione fallisce perché in_array() tiene conto di maiuscole e minuscole, quindi il programma mostrerà:
|
Esempio 3. in_array() con un array come ago
Questo ritornerà:
|
Vedere anche array_search(), array_key_exists() e isset().
key() restituisce la chiave corrispondente all'attuale posizione del puntatore interno all'array.
Esempio 1. esempio di key()
|
Ordina un array rispetto alle sue chiavi, in ordine inverso, mantenendo le associazioni. Questa funzione è utile con gli array associativi.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Si può modificare il comportamento dell'ordinamento usando il parametro opzionale sort_flags, per ulteriori dettagli vedere sort().
Vedere anche asort(), arsort(), ksort(), sort(), natsort() e rsort().
Ordina un array rispetto alle sue chiavi, mantenendo le associazioni. Questa funzione è utile con gli array associativi.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Si può modificare il comportamento dell'ordinamento usando il parametro opzionale sort_flags, per ulteriori dettagli vedere sort().
Vedere anche asort(), arsort(), krsort(), uksort(), sort(), natsort() e rsort().
Nota: Il secondo parametro è stato aggiunto in PHP 4.
Come array(), questa non è in realtà una funzione, bensì un costrutto del linguaggio. list() è usata per assegnare valori ad una lista di variabili in una sola operazione.
Nota: list() funziona solo su array numerici e si aspetta che gli indici numerici partano da 0.
Esempio 1. esempio di list()
|
Esempio 2. Esempio di uso di list()
|
Avvertimento |
list() assegna i valori cominciando dal parametro più a destra. Se si stanno usando variabili semplici, non ci si deve preoccupare di questo fatto. Ma se si stanno usando array con indici di solito ci si aspetta che l'ordine degli indici negli array sia quello scritto negli argomenti della funzione list(), da sinistra a destra; non è così. L'ordine è invertito. |
Esempio 3. Utilizzo di list() con gli indici
Restituisce il segente risultato (si noti l'ordine degli elementi rispetto all'ordine con cui sono stati scritti nella sintassi di list()).
|
(PHP 4, PHP 5)
natcasesort -- Ordina un array usando un algoritmo di "ordine naturale" non sensibile alle maiuscole/minuscoleQuesta funziona implementa un algoritmo di ordinamento che ordina le stringhe alfanumeriche come lo farebbe un essere umano, mantenendo le associazioni chiavi/valori. Questo è chiamato "ordine naturale".
natcasesort() è una versione, non sensibile alle maiuscole/minuscole, di natsort().
Esempio 1. esempio di natcasesort()
Questo codice genererà il seguente risultato:
Per maggiori informazioni vedere la pagina di Martin Pool Natural Order String Comparison . |
Vedere anche sort(), natsort(), strnatcmp() e strnatcasecmp().
Questa funzione implementa un algoritmo di ordinamento che ordina le stringhe alfanumeriche come lo farebbe un essere umano, mantenendo l'associazione chiavi/valori. Questo è chiamato "ordine naturale". Un esempio della differenza tra questo algoritmo e quello normalmente usato dai computer (usato in sort()) è dato qui sotto:
Esempio 1. esempio di natsort()
Questo codice genererà il seguente risultato:
Per ulteriori informazioni vedere la pagina di Martin Pool Natural Order String Comparison . |
Vedere anche natcasesort(), strnatcmp() e strnatcasecmp().
Restituisce l'elemento dell'array che sta nella posizione successiva a quella attuale indicata dal puntatore interno, oppure FALSE se non ci sono altri elementi.
next() si comporta come current(), con una differenza. Incrementa il puntatore interno dell'array di una posizione, prima di restituire il valore dell'elemento. Ciò significa che restituisce l'elemento successivo e incrementa il puntatore di una posizione. Se l'incremento fa sì che il puntatore vada oltre la fine della lista di elementi, next() restituisce FALSE.
Avvertimento |
Se l'array contiene elementi vuoti, o elementi che hanno il valore chiave uguale a 0 allora questa funzione restituisce FALSE anche per questi elementi. Per esplorare correttamente un array che può contenere elementi vuoti o con chiave uguale a 0 vedere la funzione each(). |
Esempio 1. Esempio di next() e funzioni relative
|
Restituisce l'elemento dell'array che sta nella posizione precedente a quella attuale indicata dal puntatore interno, oppure FALSE se non ci sono altri elementi.
Avvertimento |
Se l'array contiene degli elementi vuoti la funzione restituirà FALSE per questi valori. Per esplorare correttamente un array che può contenere elementi vuoti vedere la funzione each(). |
prev() si comporta come next(), tranne per il fatto di decrementare il puntatore interno di una posizione, invece che incrementarlo.
Esempio 1. Esempio di prev() e funzioni relative
|
range() restituisce una serie di elementi da min a max, inclusiva. Se min > max, la sequenza sarà decrescente.
Nuovo parametro: Il parametro opzionale step è stato aggiunto nel PHP 5.0.0.
Se il valore step è specificato, verrà utilizzato come incremento tra gli elementi della sequenza. step deve essere un numero positivo. Se non specificato, il valore predefinito per step è 1.
Esempio 1. esempi di range()
|
Nota: Prima della versione 4.1.0 la funzione range() generava solo array crescenti di interi. Il supporto per le sequenze di caratteri e array decrescenti è stata aggiunta nella 4.1.0. I valori delle sequenze di caratteri sono limitati alla lunghezza di 1 carattere. Se viene inserito un valore con una lunghezza maggiore, viene utilizzato solo il primo carattere.
Attenzione |
Nel PHP dalla versione 4.1.0 alla 4.3.2, range() vede le stringhe numeriche come stringhe e non come interi. Quindi, verranno utilizzate come sequenze di caratteri. Per esempio, "4242" viene trattato come "4". |
Vedere shuffle(), array_fill() e foreach.
reset() riporta il puntatore di array sul primo elemento e ne restituisce il valore.
Esempio 1. esempio di reset()
|
Questa funzione ordina un array in ordine decrescente.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
I frutti sono stati ordinati in ordine alfabetico decrescente.
Si può modificare il comportamento dell'ordinamento usando il parametro opzionale sort_flags, per maggiori dettagli vedere sort().
Questa funzione mescola un array (rende casuale l'ordine degli elementi).
Nota: Come in PHP 4.2.0, non vi è necessità di inizializzare il generatore di numeri casuali con srand() oppure con mt_srand() poichè viene eseguito in modo automatico.
Vedere anche arsort(), asort(), ksort(), rsort(), sort() e usort().
Questa funzione ordina un array. Gli elementi vengono disposti dal più piccolo al più grande.
Nota: Questa funzione assegna nuove chiavi agli elementi di array. Quindi non si limita a riordinare le chiavi, ma rimuove tutte le chiavi che siano state assegnate.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. esempio di sort()
Questo esempio mostrerà:
|
I frutti sono stati ordinati in ordine alfabetico.
Il secondo parametro opzionale sort_flags può essere usato per modificare il comportamento dell'ordinamento, usando i seguenti valori:
flag d'ordinamento:
SORT_REGULAR - compara gli elementi in modo normale
SORT_NUMERIC - compara gli elementi numericamente
SORT_STRING - compara gli elementi convertiti in stringa
Nota: Il secondo parametro è stato aggiunto in PHP 4.
Vedere anche arsort(), asort(), ksort(), natsort(), natcasesort(), rsort(), usort(), array_multisort() e uksort().
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
uasort -- Ordina un array mediante una funzione definita dall'utente e mantiene le associazioniQuesta funzione ordina un array in modo tale che le chiavi mantengano la loro correlazione con gli elementi dell'array a cui sono associate. Questo è utile quando si ordinano array associativi in cui l'ordine degli elementi è importante. La funzione di comparazione deve essere fornita dall'utente.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche usort(), uksort(), sort(), asort(), arsort(), ksort() e rsort().
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
uksort -- Ordina rispetto alle chiavi di un array mediante una funzione definita dall'utenteuksort() ordina rispetto alle chiavi di un array mediante una funzione di comparazione definita dall'utente. Se si vuole ordinare un array con dei criteri non usuali, si deve usare questa funzione.
La funzione cmp_function deve accettare due parametri che saranno valorizzati con coppie di chiavi di array. La funzione di confronto deve restituire un intero minore, uguale o maggiore di zero se il primo argomento è considerato minore, uguale o maggiore del secondo.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. esempio di uksort()
Questo esempio mostrerà:
|
Vedere anche usort(), uasort(), sort(), asort(), arsort(), ksort(), natsort() e rsort().
Ordina i valori di un array mediante una funzione di comparazione definita dall'utente. Se si vuole ordinare un array con dei criteri non usuali, si deve usare questa funzione.
La funzione di comparazione deve restituire un intero minore, uguale o superiore a zero se il primo elemento è da considerarsi rispettivamente minore, uguale o maggiore del secondo.
Nota: Se due parametri vengono valutati come uguali, il loro ordinamento nell'array ordinato è indefinito. Fino al PHP 4.0.6 le funzioni definite dall'utente mantenevano l'ordine originario per questi elementi, ma con il nuovo algoritmo di ordinamento introdotto con la versione 4.1.0 questo non succede più dal momento che non c'è un modo per ottenerlo in maniera efficiente.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Ovviamente, in questo caso banale di ordinamento decrescente la funzione sort() sarebbe stata più appropriata.
Esempio 2. esempio di usort() con un array multidimensionale
Quando si ordina un array multidimensionale, $a e $b contengono riferimenti al primo indice dell'array. Questo esempio mostrerà:
|
Esempio 3. esempio di usort() usando una funzione membro di un oggetto
Questo esempio mostrerà:
|
Vedere anche uasort(), uksort(), sort(), asort(), arsort(),ksort(), natsort() e rsort().
Le funzioni aspell() permettono di controllare la correttezza di una parola e di offrire suggerimenti.
Nota: Questa estensione è stata rimossa da PHP e non è più disponibile dal PHP 4.3.0. Se si desidera utilizzare le funzioni di correzione ortografica in PHP, utilizzare pspell, che utilizza la libreria pspell e funziona anche con le nuove versioni di aspell.
aspell funziona solo con versioni molto vecchie (più o meno fino alla .27.*) della libreria aspell. Né il presente modulo, né quelle versioni della libreria sono più supportate. Necessita della libreria aspell, disponibile da: http://aspell.sourceforge.net/.
In PHP 4, these functions are only available if PHP was configured with --with-aspell=[DIR].
(PHP 3 >= 3.0.7, PHP 4 <= 4.2.3)
aspell_check_raw -- Controlla una parola senza togliere le maiuscole o cercare di eliminare gli spazi inutili [deprecated]aspell_check_raw() controlla la correttezza di una parola, senza modificare le maiuscole/minusciole o cercare di eliminare gli spazi inutili e restituisce TRUE se è corretta, FALSE altrimenti.
aspell_check() controlla la compitazione di una parola e restituisce TRUE se è corretta, FALSE altrimenti.
aspell_new() apre un nuovo dizionario e restituisce un puntatore (link) identificatore del dizionario, da utilizzare in altre funzioni aspell. Restituisce FALSE in caso di errore.
Per la matematica a precisione arbitraria PHP offre il Binary Calculator che supporta numeri di qualsiasi dimensione e precisione, rappresentati da stringhe;
Dalla versione 4.0.4 del PHP, libbcmath è inclusa nella distribuzione. Non c'è bisogno di altre librerie esterne per questa estensione.
Queste funzioni sono disponibili solo se PHP è stato configurato con --enable-bcmath. Nel PHP 3, queste funzioni sono disponibili solo se PHP NON è stato configurato con --disable-bcmath.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Per ulteriori dettagli e definizioni delle costanti PHP_INI_* vedere ini_set().
Breve descrizione dei parametri di configurazione.
Somma il primo operando con il secondo operando e restituisce la somma sotto forma di stringa. Il parametro opzionale precisione è utilizzato per impostare il numero di cifre dopo il punto decimale nel risultato.
Confronta il primo_operando e il secondo_operando e restituisce il risultato sotto forma di intero. Il parametro opzionale precisione è utilizzato per impostare il numero di cifre dopo il punto decimale che verranno usate nel confronto. Il valore restituito è 0 se i due operandi sono uguali. Se il primo_operando è più grande del secondo_operando il valore restituito è +1 e se il primo_operando è minore del secondo_operando il valore restituito è -1.
Divide il primo operando per il secondo operando e restituisce il risultato. Il parametro opzionale precisione imposta il numero di cifre dopo il punto decimale nel risultato.
Ricava il modulo di operando usando modulo.
Moltiplica il primo operando per il secondo operando e restituisce il risultato. Il parametro opzionale precisione imposta il numero di cifre dopo il punto decimale nel risultato.
Eleva x alla potenza y. Il parametro opzionale precisione può essere usato per impostare il numero di cifre dopo il punto decimale nel risultato.
Utilizza il metodo di esponenziazione veloce per elevare x alla potenza y rispetto al modulo modulo. Il parametro opzionale precisione può essere utilizzato per impostare il numero di cifre dopo il punto decimale.
Nota: Dal momento che questo metodo utilizza l'operatore modulo, numeri non naturali possono dare risultati inattesi. Un numero naturale è un qualsiasi numero positivo intero diverso da zero.
Le seguenti istruzioni sono funzionalmente identiche. La versione bcpowmod(), comunque, esegue in meno tempo e può accettare parametri più grandi.
(PHP 3, PHP 4, PHP 5)
bcscale -- Imposta il valore di precisione di default per tutte le funzioni matematich BCMathQuesta funzione imposta il valore di default del parametro precisione per tutte le funzioni BCMath susseguenti, che non specifichino esplicitamente un parametro di precisione numerica. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Restituisce la radice quadrata di operando. Il parametro opzionale precisione imposta il numero di cifre dopo il punto decimale nel risultato.
Sottrae il primo operando dal secondo operando e retituisce il risultato in una stringa. Il parametro opzionale scale è usato per impostare il numero di cifre dopo il punto decimale nel risultato.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
Bcompiler was written for two reasons:
To encode entire script in a proprietary PHP application |
To encode some classes and/or functions in a proprietary PHP application |
To enable the production of php-gtk applications that could be used on client desktops, without the need for a php.exe. |
To do the feasibility study for a PHP to C converter |
The second of these goals is achieved using the bcompiler_write_header(), bcompiler_write_class(), bcompiler_write_footer(), bcompiler_read(), and bcompiler_load() functions. The bytecode files can be written as either uncompressed or plain. The bcompiler_load() reads a bzip compressed bytecode file, which tends to be 1/3 of the size of the original file.
To create EXE type files, bcompiler has to be used with a modified sapi file or a version of PHP which has been compiled as a shared library. In this scenario, bcompiler reads the compressed bytecode from the end of the exe file.
bcompiler can improve performance by about 30% when used with uncompressed bytecodes only. But keep in mind that uncompressed bytecode can be up to 5 times larger than the original source code. Using bytecode compression can save your space, but decompression requires much more time than parsing a source. bcompiler also does not do any bytecode optimization, this could be added in the future...
In terms of code protection, it is safe to say that it would be impossible to recreate the exact source code that it was built from, and without the accompanying source code comments. It would effectively be useless to use the bcompiler bytecodes to recreate and modify a class. However it is possible to retrieve data from a bcompiled bytecode file - so don't put your private passwords or anything in it.
short installation note:
You need at least PHP 4.3. for the compression to work
To install on PHP 4.3 and later at the unix command prompt type pear install bcompiler
To install on Windows, until the binary package distribution mechanism is finished please search the archives of the pear-general mailing list for pre-built packages. (or send an email to it if you could not find a reference)
To install on older versions you need to make some slight changes to the build.
untar the bcompiler.tgz archive into php4/ext.(Get it directly from PECL http://pecl.php.net/get/bcompiler)
If the new directory is now called something like bcompiler-0.x, then you should rename it to bcompiler (except you only want to build it as self-contained php-module).
If you are using versions before PHP 4.3, the you will need to copy the Makefile.in.old to Makefile.in and config.m4.old to config.m4.
run phpize in ext/bcompiler
run ./buildconf in php4
run configure with --enable-bcompiler (and your other options)
make; make install
that's it.
If you have comments, bugfixes, enhancements or want to help developing this beast, you can drop me a mail at alan_k@php.net. Any help is very welcome.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Reads data from a bcompiler exe file and creates classes from the bytecodes.
Esempio 1. bcompiler_load() example
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Nota: Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.
Reads data from a bzcompressed file and creates classes from the bytecodes. Please note that this function won't execute script body code contained in the bytecode file.
Nota: This function has been removed from bcompiler and is no longer available as of bcompiler 0.5.
Reads the bytecodes of a class and calls back to a user function.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Nota: Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.
Reads data from a open file handle and creates classes from the bytecodes. Please note that this function won't execute script body code contained in the bytecode file.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
This reads the bytecodes from PHP for an existing class, and writes them to the open file handle, It does not perform dependency checking, so make sure you write the classes in an order that will not result in an 'undefined class' occurring when you load it.
Esempio 1. bcompiler_write_class() example
|
See also bcompiler_write_header(), and bcompiler_write_footer().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
This function reads the bytecodes from PHP for an existing constant, and writes them to the open file handle.
See also bcompiler_write_header(), and bcompiler_write_footer().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
An EXE (or self executable) file consists of 3 parts,
The stub (executable code, e.g. a compiled C program) that loads PHP interpreter, bcompiler extension, stored Bytecodes and initiates a call for the specified function (e.g. main) or class method (e.g. main::main) |
The Bytecodes (uncompressed only for the moment) |
The bcompiler EXE footer |
To obtain a suitable stub you can compile php_embed-based stub phpe.c located in the examples/embed directory on bcompiler's CVS.
Esempio 1. bcompiler_write_footer() example
|
See also bcompiler_write_header(), bcompiler_write_class(), and bcompiler_write_footer().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
This function complies specified source file into bytecodes, and writes them to the open file handle.
See also bcompiler_write_header(), and bcompiler_write_footer().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Writes the single character \x00 to indicate End of compiled data.
See also bcompiler_write_header(), and bcompiler_write_header().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
This reads the bytecodes from PHP for an existing function, and writes them to the open file handle. Order is not important, (eg. if function b uses function a, and you compile it like the example below, it will work perfectly OK).
See also bcompiler_write_header(), and bcompiler_write_footer().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
This function searches for all functions declared in the given file, and writes their correspondent bytecodes to the open file handle. Always remember to include/require the file you intend to compile.
See also bcompiler_write_header(), and bcompiler_write_footer().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Writes the header part of a bcompiler file. Optional second parameter can be used to write bytecode in a previously used format, so that you can use it with older versions of bcompiler.
See also bcompiler_write_file(), bcompiler_write_class(), bcompiler_write_function(), and bcompiler_write_footer().
Le funzioni bzip2 sono utilizzate per leggere e scrivere in modo trasparente i file compressi con bzip2 (.bz2).
Questo modulo tuilizza le funzioni della libreria bzip2 di Julian Seward. Questo modulo richiede che la versione di bzip2/libbzip2 sia >= 1.0.x.
Il supporto di bzip2 in PHP non è abilitato di default. Si deve utilizzare l'opzione --with-bz2[=DIR] quando si compila PHP, per abilitare il supporto bzip2.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Questa estensione definisce un tipo di risorsa: un puntatore a file che identifica il file bz2 su cui lavorare.
Questo esempio apre un file temporaneo e scrive una stringa di prova su di esso, quindi stampa il contenuto del file.
Esempio 1. breve esempio di bzip2
|
Chiude il file bzip2 referenziato dal puntatore bz.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il puntatore al file deve essere valido, e deve puntare a un file gi$agrave; aperto con bzopen().
Vedere anche bzopen().
bzcompress() comprime la stringa sorgente e la restituisce come dati codificati in bzip2.
Il parametro opzionale dimblocco specifica la dimensione del blocco usato durante la compressione e dovrebbe essere un numero tra 1 e 9 dove 9 dà la compressione migliore, ma usando più risorse. dimblocco ha come valore predefinito 4.
Il parametro opzionale workfactor controlla il comportamento della fase di compressione quando deve trattare col caso peggiore, ovvero dati in ingresso molto ripetitivi. Il valore può variare tra 0 e 250, dove 0 è un caso speciale e 30 è il valore di default. Indipendentemente dal parametro workfactor, i dat generati sono gli stessi.
See also bzdecompress().
bzdecompress() decomprime la stringa sorgente contenente dati codificati in bzip2 e li restituisce. Se il parametro opzionale small è TRUE, verrà usato un algoritmo di decompressione alternativo che richiede meno memoria (la maximum quantità massima di memoria richiesta scende a 2300K) ma funziona a circa la metà della velocità. Vedere la documentazione di bzip2 per maggiori informazioni su questa funzionalità.
See also bzcompress().
Restituisce il codice di un qualsiasi errore bzip2 restituito dal puntatore al file bz.
Vedere anche bzerror() e bzerrstr().
(PHP 4 >= 4.3.3, PHP 5)
bzerror -- Restituisce il codice d'errore bzip2 e la stringa corrispondente in un arrayRestituisce il codice e la stringa di errore, sotto forma di array associativo, di un errore bzip2 restituito dal puntatore bz.
Vedere anche bzerrno() e bzerrstr().
Resituisce la stringa di errore bzip2 restituito dal puntatore bz.
Forza la scrittura di tutti i dati che sono nel buffer del puntatore bz.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Apre un file bzip2 (.bz2) in lettura o scrittura. nomefile è il nome del file da aprire. Il parametro modo è simile a quello della funzione fopen() (`r' per lettura, `w' per scrittura, ecc.).
Se l'operazione fallisce, la funzione restituisce FALSE, altrimenti restituisce un puntatore al file appena aperto.
Vedere anche bzclose().
bzread() legge fino a lunghezza byte dal puntatore bzip2 specificato da bz. La pettura termina quando lunghezza byte (decompressi) sono stati letti o quando viene raggiunto l'EOF. Se il parametro opzionale lunghezza è omesso, bzread() leggerà 1024 byte (decompressi) ogni volta.
bzwrite() scrie il contenuto della stringa dati nel file bzip2 puntato da bz. Se il parametro opzionale lunghezza è specificato, la scrittura si fermerà dopo che siano stati scritti lunghezza byte (decompressi) o al raggiungimento della fine della stringa.
L'estensione calendar presenta una serie di funzioni che semplificano la conversione tra differenti formati di calendario. Il formato intermedio o standard è basato sul Conteggio del Giorno Giuliano. Il Conteggio Giuliano è un conteggio di giorni che parte molto prima di qualsiasi data la maggior parte della gente potrebbe usare (circa il 4000 a.C.). Per convertire tra i sistemi di calendario, si deve prima convertire nel sistema del Giorno Giuliano, poi nel sistema di calendario scelto. Il Conteggio del Giorno Giuliano è molto diverso dal Calendario Giulano! Per maggiori informazioni sui sistemi di calendario vedere http://www.boogle.com/info/cal-overview.html. Parti di questa pagina sono inclusi in queste istruzioni, citate tra virgolette.
Affinché queste funzioni siano disponibili, occorre compilare PHP con l'opzione --enable-calendar.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Le seguenti costanti sono disponibili dal PHP 4.3.0 :
Le seguenti costanti sono disponibili dal PHP 5.0.0 :
(PHP 4 >= 4.1.0, PHP 5)
cal_days_in_month -- Restituisce il numero di giorni di un mese per un dato anno e calendarioQuesta funzione restituisce il numero di giorni che compongono il mese dell'anno nel calendar specificato.
Vedere anche jdtounix().
cal_from_jd() converte il Giorno Giuliano specificato in giornogiuliano in una data del calendario specificato. I valori ammessi di calendario sono CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH e CAL_FRENCH.
Esempio 1. esempio di cal_from_jd()
Questo mostrerà:
|
Vedere anche cal_to_jd().
cal_info() restituisce informazioni sullo specifico calendario o su tutti i calendari supportati se il parametro calendario non è specificato.
Lei informazioni sul calendario sono restituite in un array contenente gli elementi calname, calsymbol, month, abbrevmonth e maxdaysinmonth.
Se calendario non è specificato, le informazioni su tutti i calendari supportati sono restituite nell'array. Questa funzionalità sarà disponibile dal PHP 5.
cal_to_jd() calcola il Giorno Giuliano per una data del calendario specificato. I valori supportati per calendario sono CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH e CAL_FRENCH.
Vedere anche cal_to_jd().
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
easter_date -- Restituisce un timestamp Unix della mezzanotte del giorno di Pasqua di un dato annoRestituisce il timestamp Unix corrispondente alla mezzanotte del giorno di Pasqua dell'anno specificato.
Dal PHP 4.3.0, il parametro anno è opzionale e ha come default l'anno corrente, se omesso.
Avvertimento |
Questa funzione gerererà un allarme (warning) se l'anno è fuori dall'escursione di validità dei timestamp UNIX (cioè prima del 1970 o dopo il 2037). |
La data della Pasqua fu definita dal Concilio di Nicea nel 325 d.C. come la Domenica successiva alla prima luna piena dopo l'Equinozio di Primavera. Si assume che l'Equinozio cada sempre il 21 Marzo, quindi il calcolo si riduce alla determinazione della data della luna piena e la data della Domenica seguente. L'algoritmo qui usato fu proposto attorno all'anno 532 d.C. da Dionysius Exiguus (Dionigi il Piccolo). Nel Calendario Giuliano (for years before 1753) un semplice ciclo di 19 anni è usato per tracciare le fasi della Luna. Nel Calendario Gregoriano (per gli anni dopo il 1753 - ideato da Clavius e Lilius, e introdotto da Papa Gregorio XIII nell'Ottobre 1582, e in Gran Bretagna e nelle sue colonie nel Settembre 1752) due fattori correttivi sono aggiunti per rendere più accurato il ciclo.
(Il codice è basato su un programma in C di Simon Kershaw, <webmaster at ely.anglican dot org>)
Vedere easter_days() per il calcolo della Pasqua prima del 1970 o dopo il 2037.
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
easter_days -- Restituisce il numero di giorni tra il 21 Marzo e Pasqua, dato un annoRestituisce il numero di giorni tra il 21 Marzo e Pasqua per un dato anno. Se l'anno non è specificato, si assume l'anno corrente.
Dal PHP 4.3.0, il parametro anno è opzionale e ha come default l'anno corrente, se omesso.
Anche il parametro metodo è stato introdotto nel PHP 4.3.0 e permette di calcolare la data della Pasqua basata sul calendario Gregoriano durante gli anni 1582 - 1752 quando è impostato a CAL_EASTER_ROMAN, vedere le costanti di calendario per altre costanti valide.
Questa funzione può essere usata al posto di easter_date() per calcolare la Pasqua per gli anni che cadono fuori dalla gamma di validità dei timestamp Unix (cioè prima del 1970 o dopo il 2037).
La data della Pasqua fu definita dal Concilio di Nicea nel 325 d.C. come la Domenica successiva alla prima luna piena dopo l'Equinozio di Primavera. Si assume che l'Equinozio cada sempre il 21 Marzo, quindi il calcolo si riduce alla determinazione della data della luna piena e la data della Domenica seguente. L'algoritmo qui usato fu proposto attorno all'anno 532 d.C. da Dionysius Exiguus (Dionigi il Piccolo). Nel Calendario Giuliano (for years before 1753) un semplice ciclo di 19 anni è usato per traciare le fasi della Luna. Nel Calendario Gregoriano (per gli anni dopo il 1753 - ideato da Clavius e Lilius, e introdotto da Papa Gregorio XIII nell'Ottobre 1582, e in Gran Bretagna e nelle sue colonie nel Settembre 1752) due fattori correttivi sono aggiunti per rendere più accurato il ciclo.
(Il codice è basato su un programma in C di Simon Kershaw, <webmaster at ely.anglican dot org>)
Vedere anche easter_date().
(PHP 3, PHP 4, PHP 5)
FrenchToJD -- Converte una data del Calendario Repubblicano Francese in un Giorno GiulianoConverte una data del Calendario Repubblicano Francese in un Giorno Giuliano.
Queste funzioni convertono solo le date con gli anni dal 1 al 14 (date Gregoriane dal 22 Settmbre 1792 al 22 Settembre 1806). Questo copre più del periodo in cui fu in uso il calendario.
L'intervallo valido per il Calendario Gregoriano è dal 4714 a.C. al 9999 d.C.
Anche se questa funzione può gestire date fino al 4714 a.C., qusto utilizzo potrebbe non avere senso. Il calendario Gregoriano fu istituito il 15 Ottobre 1582 (o 5 Ottobre 1582 nel calendario Giuliano). Alcune nazioni non lo accettarono per un lungo periodo. Per esempio, il Regno Unito si convertì nel 1752, L'Unione Sovietica nel in 1918 e la Grecia nel 1923. La maggior parte delle nazioni Europee usavano il calendario Giuliano prima del Gregoriano.
Restituisce il giorno della settimana. Può restituire una stringa o un intero a seconda del modo.
Restituisce una stringa contenente il nome di un mese. modo dice alla funzione verso quale calendario convertire il giorno Giuliano, e che tipo di nome di mese restituire.
Tabella 1. Modi del Calendario
Modo | Significato | Valori |
---|---|---|
0 | Gregoriano abbreviato | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec |
1 | Gregoriano | January, February, March, April, May, June, July, August, September, October, November, December |
2 | Giuliano abbreviato | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec |
3 | Giuliano | January, February, March, April, May, June, July, August, September, October, November, December |
4 | Giudeo | Tishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul |
5 | Repubblicano Francese | Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra |
(PHP 3, PHP 4, PHP 5)
JDToFrench -- Converte un Giorno Giuliano in una data del Calendario Repubblicano FranceseConverte un Giorno Giuliano in una data del calendario Repubblicano Francese.
Converte il Giorno Giuliano in una stringa contenente la data Gregoriana nel formato "mese/giorno/anno".
Converte un Giorno Giuliano nel Calendario Giudeo.
I parametri opzionali ebraico e fl sono disponibili dal PHP 5.0.0
Se il parametro ebraico è TRUE, il parametro fl è usato per il formato di output Ebraico. I formati disponibili sono: CAL_JEWISH_ADD_ALAFIM_GERESH, CAL_JEWISH_ADD_ALAFIM, CAL_JEWISH_ADD_GERESHAYIM.
Converte un Giorno Giuliano in una stringa contenente la data del calendario Giuliano nel formato "mese/giorno/anno".
Questa funzione restituisce un timestamp Unix corrispondente al Giorno Giuliano giornogiuliano o FALSE se giornogiuliano non è all'interno della gamma Unix (anni Gregoriani tra il 1970 e il 2037 o 2440588 <= giornogiuliano <= 2465342 ). L'ora restituita è locale (e non GMT).
See also unixtojd().
Anche se questa funzione può gestire date fino all'anno 1 (3761 B.C.), questo utilizzo potrebbe non avere senso. Il calendario Giudeo è usato da parecchie migliaia di anni, ma nei primi tempi non c'era una formula per stabilire l'inizio del mese. Il nuovo mese iniziava quando si vedeva la prima volta la luna.
L'intervallo valido per il Calendario Giuliano è dal 4713 a.C. al 9999 d.C.
Anche se questa funzione può gestire date fino al 4713 a.C., questo utilizzo potrebbe non avere senso. Il calendario fu creato nel 46 a.C., ma i dettagli non furono perfezionati fino almeno al 8 d.C., e forse anche fino al quarto secolo. Inoltre, l'inizio dell'anno variava da una cultura all'altra - non tutti accettavano Gennaio come primo mese.
Attenzione |
Il calendario attuale, utilizzato in tutto il mondo, è il calendario Gregoriano. gregoriantojd() può essere utilizzata per convertire queste date nel corrispondente Giorno Giuliano. |
Restituisce il Giorno Giuliano di un timestamp Unix (secondi dal 1/1/1970), o del giorno corrente se timestamp non è specificato.
Vedere anche jdtounix().
Queste funzioni si interfacciano con le API CCVS, permettendo di lavorare direttamente con CCVS dagli script PHP. CCVS è la soluzione di RedHat per il "mediatore" nella gestione dei pagamenti con carta di credito. Permette di comunicare direttamente con le società di autorizzazione di transazione attraverso una *nix box e un modem. Usando il modulo CCVS per PHP, è possibile procesare direttamente le carte di credito attraverso gli script PHP. Le seguenti informazioni esemplificheranno il processo.
Nota: CCVS è stato abbandonato da Red Hat e non c'è l'intenzione di fornire altre chiavi o contratti di assistenza. Chi cerca un sostituto può considerare MCVE della Main Street Softworks come una possibile alternativa. Il prodotto è simile nella struttura ed ha un supporto documentato per PHP!
Questa estensione è stata rimossa dal PHP e non è più disponibile dal PHP 4.3.0. Se si vogliono utilizzare delle funzioni di processamento delle carte di credito, utilizzare piuttosto MCVE.
To enable CCVS Support in PHP, first verify your CCVS installation directory. You will then need to configure PHP with the --with-ccvs option. If you use this option without specifying the path to your CCVS installation, PHP will attempt to look in the default CCVS Install location (/usr/local/ccvs). If CCVS is in a non-standard location, run configure with: --with-ccvs=[DIR], where DIR is the path to your CCVS installation. Please note that CCVS support requires that DIR/lib and DIR/include exist, and include cv_api.h under the include directory and libccvs.a under the lib directory.
Additionally, a ccvsd process will need to be running for the configurations you intend to use in your PHP scripts. You will also need to make sure the PHP Processes are running under the same user as your CCVS was installed as (e.g. if you installed CCVS as user 'ccvs', your PHP processes must run as 'ccvs' as well.)
RedHat non supporta più CCVS; comunque una documentazione leggermente datata è ancora disponibile presso http://www.redhat.com/docs/manuals/ccvs/.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.0.2 - 4.2.3 only)
ccvs_command -- Esegue un comando caratteristico di un particolare protocollo, quindi non disponibile nelle API di CCVS
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.0.2 - 4.2.3 only)
ccvs_count -- Conta quante transazioni di un dato tipo sono archiviate nel sistema
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.0.2 - 4.2.3 only)
ccvs_return -- Trasferisce fondi dal merchant al titolare della carta di credito
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.0.2 - 4.2.3 only)
ccvs_textvalue -- Restuisce il valore testuale reso dalla precedente chiamata di funzione
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Queste funzioni permettono di ottenere informazioni sulle classi e sulle istanze degli oggetti. Si può ricavare il nome della classe da cui deriva un dato oggetto, come le sue proprietà e i suoi metodi. Utilizzando queste funzioni si ottiene, non solo a quale classe appartiene un dato oggetto, ma anche i suoi "padri" (ad esempio da quale classe è derivata la classe dell'oggetto).
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
In questo esempio, prima si definisce una classe base, quindi una seconda che deriva dalla prima. La classe base descrive gli aspetti generali degli ortaggi, se è commestibile e quale sia il colore. La classe derivata Spinaci aggiunge i metodi di cottura e di verifica della completa cottura.
Esempio 1. classi.inc
|
A questo punto si istanziano 2 oggetti a partire da queste classi e si visualizzeranno le informazioni relative a questi oggetti, compresi i loro padri. Verranno anche inserite funzioni di utilità principalmente con lo scopo di rendere chiara la visualizzazione delle variabili.
Esempio 2. test_script.php
Un aspetto da notare nell'esempio precedente è che l'oggetto $frondoso è un'istanza della classe Spinaci che a sua volta è una sottoclasse di Ortaggio, quindi l'ultima parte dell'esempio visualizzerà:
|
(PHP 4 >= 4.0.5, PHP 5)
call_user_method_array -- Richiama il metodo dato con un array di parametri [deprecated]Avvertimento |
A partire dalla versione 4.1.0 è sconsigliato l'uso di call_user_method_array(); in sostituzione utilizzare la serie di funzioni call_user_func_array() con sintassi array(&$obj, "method_name"). |
Richiama il metodo indicato da nome_metodo dell'oggetto oggetto, utilizzando i parametri forniti in array_parametri.
Vedere anche: call_user_func_array() e call_user_func().
(PHP 3 >= 3.0.3, PHP 4, PHP 5)
call_user_method -- Chiama un metodo dell'oggetto indicato [deprecated]Avvertimento |
A partire dalla versione 4.1.0 l'uso della funzione call_user_method() è sconsigliato; in sostituzione utilizzare la serie call_user_func() con la sintassi array(&$obj, "method_name"). |
Richiama il metodo indicato da nome_metodo dell'oggetto oggetto. Di seguito si fornisce un esempio di utilizzo. Qui si definisce una classe, si istanzia un oggetto, e si utilizza call_user_method() per richiamare il metodo stampa_info
<?php class Stato { var $NOME; var $TLD; function Stato($nome, $tld) { $this->NOME = $nome; $this->TLD = $tld; } function stampa_info($prestr = "") { echo $prestr . "Stato: " . $this->NOME . "\n"; echo $prestr . "Dominio di primo livello: " . $this->TLD . "\n"; } } $paese = new Stato("Peru", "pe"); echo "* Richiamo il metodo direttamente\n"; $paese->stampa_info(); echo "\n* utilizzo dello stesso metodo in modo indiretto\n"; call_user_method("stampa_info", $paese, "\t"); ?> |
Vedere anche call_user_func_array() e call_user_func().
Questa funzione restituisce TRUE se la classe indicata dal parametro nome_classe è stata definita, altrimenti restituisce FALSE .
class_exists(), per default, tenta di eseguire __autoload, se non si desidera che class_exists() esegua __autoload(), impostare il parametro autoload a FALSE.
Esempio 2. Esempio di uso di autoload
|
Nota: Il parametro autoload è stato aggiunto in PHP 5
Vedere anche interface_exists() e get_declared_classes().
Questa funzione restituisce un array contenente i nomi dei metodi definiti per la classe specificata da nome_classe.
Nota: Dalla versione 4.0.6 di PHP, si può specificare direttamente l'oggetto anziché la classe nel parametro nome_classe. Ad esempio:
Esempio 1. Esempio di get_class_methods()
Il precedente esempio visualizzerà:
|
Avvertimento |
Dal PHP 5, questa funzione restituisce il nome dei metodi così come sono dichiarati (sensibile alle maiuscole). In PHP 4 erano restituiti in minuscolo. |
Vedere anche get_class_vars() e get_object_vars()
Questa funzione restituisce un array associativo contenente le proprietà di default pubbliche della classe. Gli elementi dell'array prodotto sono nel formato nomevariabile => valore.
Nota: Nelle verioni di PHP precedenti alla 4.2.0, le variabili della classe non inizializzate non sono elencate da get_class_vars().
Esempio 1. get_class_vars() esempio
Il precedente esempio visualizzerà:
|
Vedere anche get_class_methods() e get_object_vars()
Questa funzione restituisce il nome della classe di cui l'oggetto oggetto è un'istanza. Restituisce FALSE se oggetto non è un oggetto.
Nota: Le classi definite nei moduli di PHP sono restituite nella notazione originale. In PHP 4, get_class() restituisce il nome delle classi definite dagli utenti in minuscolo, mentre in PHP 5 i nomi delle classi saranno restituiti nella notazione originale, come i nomi delle classi nei moduli.
Esempio 1. Utilizzo di get_class()
Il precedente esempio visualizzerà:
|
Vedere anche get_parent_class(), gettype() e is_subclass_of()
Questa funzione restituisce un array con i nomi delle classi definite all'interno dello script corrente.
Nota: Nella versione 4.0.1pl2 di PHP, in testa all'array erano indicate tre ulteriori classi: stdClass (definita in Zend/zend.c), OverloadedTestClass (definita in ext/standard/basic_functions.c) e Directory (definita in ext/standard/dir.c).
Occorre notare che, in base a quali librerie sono state compilate in PHP, possono essere rilevate ulteriori classi. Questo significa, anche, che non si potranno definire delle classi con questi nomi. Un'elenco delle classi predefinite è nella sezione Predefined Classes dell'appendice.
Vedere anche class_exists() e get_declared_interfaces().
This function returns an array of the names of the declared interfaces in the current script.
See also get_declared_classes().
Questa funzione restituisce un array associativo con le proprietà definite nell'oggetto passato nel parametro oggetto .
Nota: Nelle versioni di PHP precedenti la 4.2.0, le eventuali variabili dichiarate in nella classe oggetto ma non ancora valorizzate non saranno restituite nell'array. Nelle versioni successive alla 4.2.0, saranno restituite nell'array con valore NULL.
Esempio 1. Utilizzo di get_object_vars()
Il precedente esempio visualizzerà:
|
Vedere anche get_class_methods() e get_class_vars().
(PHP 4, PHP 5)
get_parent_class -- Restituisce il nome della classe genitrice di un oggetto o di una classeSe oggetto è un oggetto, la funzione restituisce il nome del genitore della classe di cui oggetto è un'istanza.
Se oggetto è una stringa, la funzione restituisce il nome della classe genitrice della classe di cui oggetto indica il nome. Questa funzionalità è stata aggiunta nella versione 4.0.5 di PHP.
Esempio 1. Utilizzo di get_parent_class()
Il precedente esempio visualizzerà:
|
Vedere anche get_class(), is_subclass_of()
This function returns TRUE if the interface given by interface_name has been defined, FALSE otherwise.
interface_exists() will attempt to call __autoload by default, if you don't want interface_exists() to call __autoload, you can set the parameter autoload to FALSE.
See also class_exists().
(PHP 4 >= 4.2.0, PHP 5)
is_a -- Restituisce TRUE se l'oggetto appartiene a questa classe o se ha questa classe tra i suoi genitoriQuesta funzione restituisce TRUE appartiene a questa classe oppure ha questa classe tra i suoi genitori, FALSE in caso diverso.
In PHP 5 la funzione is_a() è sconsigliata in favore di instanceof. L'esempio precedente, in PHP 5, può essere riscritto come:
Vedere anche get_class(), get_parent_class() e is_subclass_of().
(PHP 4, PHP 5)
is_subclass_of -- Restituisce TRUE se l'oggetto ha questa classe come uno dei suoi genitoriQuesta funzione restituisce TRUE se obj, appartiene ad una sottoclasse di nome_classe, altrimenti FALSE.
Nota: Dal PHP 5.0.3 si può specificare il parametro oggetto come stringa (il nome della classe).
Esempio 1. Esempio di uso di is_subclass_of()
Il precedente esempio visualizzerà:
|
Vedere anche get_class(), get_parent_class() e is_a().
Questa funzione restituisce TRUE se il metodo indicato dal parametro nome_metodo è stato nell'oggetto indicato da oggetto, altrimenti FALSE.
This function checks if the given property exists in the specified class (and if it was declared as public).
Nota: As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.
A string with the class name or an object of the class to test for
The name of the property
These functions allow the dynamic manipulation of PHP classes, at runtime.
Nota: This extension has been replaced by runkit, which is not limited to class manipulation but has function manipulation, as well.
This PECL extension is not bundled with PHP.
Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/classkit.
You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Nota: This function cannot be used to manipulate the currently running (or chained) method.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Esempio 1. classkit_import() example
Il precedente esempio visualizzerà:
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The class to which this method will be added
The name of the method to add
Comma-delimited list of arguments for the newly-created method
The code to be evaluated when methodname is called
The type of method to create, can be CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED or CLASSKIT_ACC_PRIVATE
Nota: This parameter is only used as of PHP 5, because, prior to this, all methods were public.
Esempio 1. classkit_method_add() example
Il precedente esempio visualizzerà:
|
classkit_method_copy() |
classkit_method_redefine() |
classkit_method_remove() |
classkit_method_rename() |
create_function() |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Destination class for copied method
Destination method name
Source class of the method to copy
Name of the method to copy from the source class. If this parameter is omitted, the value of dMethod is assumed.
Esempio 1. classkit_method_copy() example
Il precedente esempio visualizzerà:
|
classkit_method_add() |
classkit_method_redefine() |
classkit_method_remove() |
classkit_method_rename() |
Nota: This function cannot be used to manipulate the currently running (or chained) method.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The class in which to redefine the method
The name of the method to redefine
Comma-delimited list of arguments for the redefined method
The new code to be evaluated when methodname is called
The redefined method can be CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED or CLASSKIT_ACC_PRIVATE
Nota: This parameter is only used as of PHP 5, because, prior to this, all methods were public.
Esempio 1. classkit_method_redefine() example
Il precedente esempio visualizzerà:
|
classkit_method_add() |
classkit_method_copy() |
classkit_method_remove() |
classkit_method_rename() |
Nota: This function cannot be used to manipulate the currently running (or chained) method.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The class in which to remove the method
The name of the method to remove
classkit_method_add() |
classkit_method_copy() |
classkit_method_redefine() |
classkit_method_rename() |
Nota: This function cannot be used to manipulate the currently running (or chained) method.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The class in which to rename the method
The name of the method to rename
The new name to give to the renamed method
ClibPDF permette di creare documenti PDF utilizzando PHP. La funzionalità e l' API di ClibPDF sono simili a quelle di PDFlib. Questa documentazione dovrebbe essere letta insieme al manuale di ClibPDF poichè entra maggiormente nel dettaglio della libreria.
Molte funzioni nella ClibPDF nativa e nel modulo PHP , così come nella PDFlib hanno lo stesso nome. Tutte le funzioni ad eccezione di cpdf_open() hanno l'identificatore del documento come loro primo parametro.
Attualmente questo identificatore non è usato internamente dato che ClibPDF non supporta la creazione di svariati documenti PDF contemporaneamente. Attualmente non bisognerebbe provare a farlo, dato che i risultati sono imprevedibili. Non è possibile controllare quali siano le conseguenze in un ambiente multi processo. Secondo l'autore di ClibPDF questo cambierà in una delle prossime release (la versione corrente quando questo è stato scritto è la 1.10). Se si ha bisogno di questa funzionalità utilizzare il modulo pdflib.
Un'interessante caratteristica di ClibPDF (e PDFlib) è l'abilità di creare il documento PDF completamente in memoria senza utilizzare file temporanei. Inoltre fornisce l'abilità di passare le coordinare in un'unità di lunghezza predefinita. (Questa caratteristica puo'essere simulata da pdf_translate() quando si utilizzano le funzioni PDFlib.)
Un'altra interessante caratteristica di ClibPDF è il fatto che ogni pagina può essere modificata in qualsiasi momento anche se è già stata aperta una nuova pagina. La funzione cpdf_set_current_page() permette di lasciare la pagina corrente e modificare un'altra pagina.
La maggioranza delle funzioni sono abbastanza facili da usare. La parte più difficile è probabilmente creare un simplice documento PDF. L'esempio seguente dovrebbe essere utile per cominciare. Crea un documento con una pagina. La pagina contiene il testo "Times-Roman" con un font di 30pt. Il testo è sottolineato.
Nota: Se si è interessati ad alternativi generatori PDF free non utilizzare le librerie PDF esterne, vedere questa FAQ per dettagli.
Per potere utilizzare le funzioni ClibPDF occorre installare il modulo ClibPDF. Questo è disponibile in FastIO, ma richiede l'acquisto di una licenza per uso commerciale. Il PHP richiede la libreria cpdflib >= 2.
Per avere disponibili queste funzionalità occorre compilare il PHP con --with-cpdflib[=DIR]. Dove DIR indica la directory in cui è installato cpdflib, per default /usr. In aggiunta si può specificare le librerie jpeg e tiff da utilizzare. Per fare ciò aggiungere alla linea di configurazione le opzioni --with-jpeg-dir[=DIR] e --with-tiff-dir[=DIR].
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Esempio 1. Semplice esempio ClibPDF
|
La distribuzione pdflib contiene un esempio più complicato che crea una serie di pagine con un orologio analogico. Di seguito si trova questo esempio convertito in PHP utilizzando l'estensione ClibPDF:
Esempio 2. esempio pdfclock dalla distribuzione pdflib 2.0
|
La cpdf_add_annotation() aggiunge una nota con l'angolo in basso a sinistra in (llx, lly) e l'angolo in alto a destra in (urx, ury). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)
cpdf_add_outline -- Aggiunge un segnalibro per la pagina correnteLa funzione cpdf_add_outline() aggiunge un segnalibro con il testo testo che punta alla pagina corrente.
Esempio 1. Aggiungere il contorno alla pagina
|
La funzione cpdf_arc() disegna un arco con centro nel punto (x-coor, y-coor) e raggio radius, che comincia all'angolo inizio e che termina all'angolo fine. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Vedere anche cpdf_circle().
La funzione cpdf_begin_text() avvia una sezione di testo. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. La sezione creata deve essere terminata con cpdf_end_text().
Vedere anche cpdf_end_text().
La funzione cpdf_circle() disegna un cerchio con centro nel punto (x-coor, y-coor) e raggio raggio. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Vedere anche cpdf_arc().
La funzione cpdf_clip() taglia tutti i disegni dal path corrente. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione cpdf_close() chiude il documento pdf. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. Questa dovrebbe essere l'ultima funzione dopo persino cpdf_finalize(), cpdf_output_buffer() e cpdf_save_to_file().
Vedere anche cpdf_open().
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_closepath_fill_stroke -- Close, fill and stroke current pathThe cpdf_closepath_fill_stroke() function closes, fills the interior of the current path with the current fill color and draws current path. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also cpdf_closepath(), cpdf_stroke(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_closepath_stroke -- Chiude il path e disegna una linea lungo il pathLa funzione cpdf_closepath_stroke() è una combinazione di cpdf_closepath() e cpdf_stroke(). Dopo libera il path. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_closepath() e cpdf_stroke().
La funzione cpdf_closepath() chiude la path corrente. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione cpdf_continue_text() scrive la stringa testo nella riga seguente. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_show_xy(), cpdf_text(), cpdf_set_leading() e cpdf_set_text_pos().
La funzione cpdf_curveto() disegna una curva di Bezier dal punto corrente al punto (x3, y3) utilizzando (x1, y1) e (x2, y2) come punti di controllo. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Vedere anche cpdf_moveto(), cpdf_rmoveto(), cpdf_rlineto() e cpdf_lineto().
La funzione cpdf_end_text() termina una sezione di testo cominciata con cpdf_begin_text(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_begin_text().
The cpdf_fill_stroke() function fills the interior of the current path with the current fill color and draws current path. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also cpdf_closepath(), cpdf_stroke(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().
La funzione cpdf_fill() riempie l'interno del path corrente con il colore di riempimento corrente. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_closepath(), cpdf_stroke(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill() e cpdf_setrgbcolor().
La funzione cpdf_finalize_page() chiude la pagina numero numero della pagina. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Questa funzione serve solo a preservare la memoria. Una pagina chiusa occupa meno memoria ma non può più essere modificata.
Vedere anche cpdf_page_init().
La funzione cpdf_finalize() chiude il documento. Bisogna comunque richiamare cpdf_close(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_close().
The cpdf_global_set_document_limits() function sets several document limits. This function has to be called before cpdf_open() to take effect. It sets the limits for any document open afterwards. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also cpdf_open().
La funzione cpdf_import_jpeg() apre un'immagine contenuta nel file con nome nome del file. Il formato dell'immagine deve essere jpeg. L' immagine viene inserita nella pagina corrente alla posizione (x-coor, y-coor). L'immagine è ruotata di angolo gradi. Il parametro gsave dovrebbe essere diverso da zero affinchè questa funzione operi correttamente.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Vedere anche cpdf_place_inline_image().
La funzione cpdf_lineto() disegna una linea dal punto corrente al punto con coordinate (x-coor, y-coor). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Vedere anche cpdf_moveto(), cpdf_rmoveto() e cpdf_curveto().
La funzione cpdf_moveto() setta il punto corrente alle coordinate x-coor e y-coor. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
La funzione cpdf_newpath() inizia un nuovo path sul documento indicato dal parametro documento pdf. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione cpdf_open() apre un nuovo documento pdf. Il primo parametro setta il fattore di compressione del documento se è diverso da 0. Il secondo parametro, opzionale, setta il file in cui il documento viene scritto. Se è omesso il documento è creato in memoria e può essere scritto su un file con cpdf_save_to_file() oppure scritto sullo standard output con cpdf_output_buffer().
Nota: Il valore di ritorno sarà necessario nelle future versione di ClibPDF come primo parametro di tutte le altre funzioni che scrivono sul documento PDF.
La libreria ClibPDF considera il nome del file "-" come sinonimo di stdout. Se il PHP è compilato come modulo di apache questo però non funziona perchè il modo in cui ClibPDF scrive sullo stdout non funziona con apache. Si può risolvere questo problema saltando il nome del file e utilizzando cpdf_output_buffer() per scrivere il documento pdf.
Vedere anche cpdf_close() e cpdf_output_buffer().
(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)
cpdf_output_buffer -- Scrive il documento pdf nel buffer di memoriaLa funzione cpdf_output_buffer() scrive il documento pdf nello stdout. Il documento deve essere creato in memoria, cosa che si verifica se cpdf_open() è richiamata senza il nome di un file come parametro. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_open().
La funzione cpdf_page_init() inizia una nuova pagina con altezza height e larghezza width. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. La pagina ha numero numero di pagina e orientamento orientamento. orientamento può essere 0 per l'orientamento verticale e 1 per l'orizzontale. L'ultimo parametro facoltativo unità setta le unità per il sistema di coordinate. Il valore deve essere il numero di punti postscript per unità. Dato che un pollice corrisponde a 72 punti, un valore di 72 setterà l'unità ad un pollice. Il valore di default è sempre 72.
Vedere cpdf_set_current_page().
(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)
cpdf_place_inline_image -- Inserisce un'immagine nella paginaLa funzione cpdf_place_inline_image() inserisce un'immagine creata con le funzioni per le immagini di PHP nella pagina alla posizione (x-coor, y-coor). L'immagine può essere ridimensionata nello stesso tempo. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Vedere anche cpdf_import_jpeg().
La funzione cpdf_rect() disegna un rettangolo con l'angolo in basso a sinistra nel punto (x-coor, y-coor). La larghezza è settata a larghezza. L'altezza è settata a altezza. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Esempio 1. Traccia un rettangolo
|
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_restore -- Ristabilisce le impostazioni salvate in precedenzaLa funzione cpdf_restore() ristabilisce le impostazioni salvate con cpdf_save(). Funziona come il comando postscript grestore. Molto utile se si vuole traslare o ruotare un oggetto senza intaccare gli altri oggetti. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_save().
La funzione cpdf_rlineto() disegna una linea dal punto corrente al punto con coordinate relative (x-coor, y-coor). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Vedere anche: cpdf_moveto(), cpdf_rmoveto() e cpdf_curveto().
La funzione cpdf_rmoveto() setta il punto corrente alle coordinate relative x-coor e y-coor. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Vedere anche cpdf_moveto().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione cpdf_rotate() effettua una rotazione di angolo gradi. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione cpdf_save_to_file() salva il documento pdf in un file se è stato creato in memoria. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Questa funzione non è necessaria se il documento pdf è stato aperto specificando un nome di un file come parametro di cpdf_open().
Vedere anche: cpdf_output_buffer() e cpdf_open().
La funzione cpdf_save() salva le impostazioni correnti. Funziona come il comando postscript gsave. Molto utile se si vuole traslare o ruotare un oggetto senza intaccare gli altri oggetti. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_restore().
La funzione cpdf_scale() applica il coefficiente di scala in entrambe le direzioni. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione cpdf_set_char_spacing() imposta la spaziatura fra caratteri. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_set_word_spacing() e cpdf_set_leading().
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_creator -- Imposta il campo creatore nel documento pdfLa funzione cpdf_set_creator() imposta il creatore del documento pdf. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche: cpdf_set_subject(), cpdf_set_title() e cpdf_set_keywords().
La funzione cpdf_set_current_page() imposta la pagina sulla quale vengono eseguite tute le operazioni. Ci si può spostare sulle pagine finchè una pagina non è chiusa con cpdf_finalize_page(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_finalize_page().
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)
cpdf_set_font_directories -- Imposta le directory in cui cercare quando si utilizzano font esterni
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)
cpdf_set_font_map_file -- Imposta la tabella di associazione tra nome di file e nome di font, quando si usano font esterni
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_font -- Seleziona l'aspetto e la dimensione del font correnteLa funzione cpdf_set_font() imposta l'aspetto, la dimensione e la codifica del font corrente. Attualmente solo i font standard postscript sono supportati. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
L'ultimo parametro codifica può assumere i seguenti valori: "MacRomanEncoding", "MacExpertEncoding", "WinAnsiEncoding", e "NULL". "NULL" rappresenta la codifica incorporata del font.
Vedere il manuale di ClibPDF per maggiori informazioni, specialmente su come supportare font asiatici.
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_horiz_scaling -- Imposta il fattore di scala orizzontale del testoLa funzione cpdf_set_horiz_scaling() imposta il fattore di scala orizzontale a scala percento. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_keywords -- Imposta i campi chiave del documento pdfLa funzione cpdf_set_keywords() imposta le parole chiave di un documento pdf. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche: cpdf_set_title(), cpdf_set_creator() e cpdf_set_subject().
La funzione cpdf_set_leading() imposta la distanza fra righe di testo. Verrà utilizzata se il testo viene scritto con cpdf_continue_text(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere cpdf_continue_text().
The cpdf_set_page_animation() function set the transition between following pages. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The value of transition can be
0 for none, |
1 for two lines sweeping across the screen reveal the page, |
2 for multiple lines sweeping across the screen reveal the page, |
3 for a box reveals the page, |
4 for a single line sweeping across the screen reveals the page, |
5 for the old page dissolves to reveal the page, |
6 for the dissolve effect moves from one screen edge to another, |
7 for the old page is simply replaced by the new page (default) |
The value of duration is the number of seconds between page flipping.
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_subject -- Imposta il campo soggetto del documento pdfLa funzione cpdf_set_subject() imposta il soggetto del documento pdf. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_set_title(), cpdf_set_creator() e cpdf_set_keywords().
La funzione cpdf_set_text_matrix() imposta una matrmatriceice che descrive una trasformazione applicata sul font corrente. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione cpdf_set_text_pos() imposta la posizione del testo per la prossima chiamata della funzione cpdf_show(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Vedere anche: cpdf_show() e cpdf_text().
The cpdf_set_text_rendering() function determines how text is rendered. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The possible values for rendermode are 0=fill text, 1=stroke text, 2=fill and stroke text, 3=invisible, 4=fill text and add it to clipping path, 5=stroke text and add it to clipping path, 6=fill and stroke text and add it to clipping path, 7=add it to clipping path.
The cpdf_set_text_rise() function sets the text rising to value units. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione cpdf_set_title() imposta il titolo di un documento pdf. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche: cpdf_set_subject(), cpdf_set_creator() e cpdf_set_keywords().
(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_viewer_preferences -- How to show the document in the viewer
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione cpdf_set_word_spacing() imposta la spaziatura fra parole. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche: cpdf_set_char_spacing() e cpdf_set_leading().
The cpdf_setdash() function set the dash pattern white white units and black black units. If both are 0 a solid line is set. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The cpdf_setflat() function set the flatness to a value between 0 and 100. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_setgray_fill -- Imposta il grigio come colore per il riempimentoLa funzione cpdf_setgray_fill() imposta il valore corrente di grigio come riempimento del path. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_setrgbcolor_fill().
The cpdf_setgray_stroke() function sets the current drawing color to the given gray value. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also cpdf_setrgbcolor_stroke().
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_setgray -- Imposta il grigio come colore per il disegno e il riempimentoLa funzione cpdf_setgray() imposta come colore per il disegno e il riempimento il valore di grigio passato. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche: cpdf_setrgbcolor_stroke() e cpdf_setrgbcolor_fill().
The cpdf_setlinecap() function set the linecap parameter between a value of 0 and 2. 0 = butt end, 1 = round, 2 = projecting square. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The cpdf_setlinejoin() function set the linejoin parameter between a value of 0 and 2. 0 = miter, 1 = round, 2 = bevel. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione cpdf_setlinewidth() imposta la larghezza delle linee a larghezza. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The cpdf_setmiterlimit() function set the miter limit to a value greater or equal than 1. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_setrgbcolor_fill -- Sets filling color to rgb color valueThe cpdf_setrgbcolor_fill() function sets the current rgb color value to fill a path.
Nota: The values are expected to be floating point values between 0.0 and 1.0. (i.e black is (0.0, 0.0, 0.0) and white is (1.0, 1.0, 1.0)).
See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor().
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_setrgbcolor_stroke -- Sets drawing color to rgb color valueThe cpdf_setrgbcolor_stroke() function sets the current drawing color to the given rgb color value. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: The values are expected to be floating point values between 0.0 and 1.0. (i.e black is (0.0, 0.0, 0.0) and white is (1.0, 1.0, 1.0)).
See also cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_setrgbcolor -- Imposta il valore del colore rgb come colore per il disegno e il riempimentoLa funzione cpdf_setrgbcolor() imposta il colore corrente per il disegno e il riempimento al valore del colore rgb dato. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: The values are expected to be floating point values between 0.0 and 1.0. (i.e black is (0.0, 0.0, 0.0) and white is (1.0, 1.0, 1.0)).
Vedere anche: cpdf_setrgbcolor_stroke() e cpdf_setrgbcolor_fill().
The cpdf_show_xy() function outputs the string text at position with coordinates (x-coor, y-coor). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Nota: The function cpdf_show_xy() is identical to cpdf_text() without the optional parameters.
See also cpdf_text().
La funzione cpdf_show() scrive la stringa in testo alla posizione corrente. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche: cpdf_text(), cpdf_begin_text() e cpdf_end_text().
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_stringwidth -- Restituisce la larghezza del testo nel font correnteLa funzione cpdf_stringwidth() restituisce la larghezza della stringa in testo. Richiede che un font sia settato in precedenza.
Vedere anche cpdf_set_font().
La funzione cpdf_stroke() disegna una linea lungo il path corrente. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche: cpdf_closepath() e cpdf_closepath_stroke().
La funzione cpdf_text() scrive la stringa testo alla posizione con coordinate (x-coor, y-coor). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Il parametro facoltativo orientamento è la rotazione del testo in gradi.
Il parametro facoltativo allineamento determina come viene allineato il testo.
Vedere la documentazione ClibPDF per i possibili valori.
Vedere anche cpdf_show_xy().
The cpdf_translate() function set the origin of coordinate system to the point (x-coor, y-coor). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
COM è una tecnologia che permette il riutilizzo del codice scritto in un qualsiasi linguaggio utilizzando una convenzione standard di chiamate e nascondendo dietro a delle API i dettagli di implementazione quali la macchina su cui il Componente è conservato e il file eseguibile che lo ospita. Si può pernsare a COM com a un meccanismo avanzato di Remote Procedure Call (RPC) con alcune basi di programmazione ad oggetti. COM separa l'implementazione dall'interfaccia.
COM incoraggia il versioning, la separazione tra interfaccia e implementazione e l'occultamento dei dettagli dell'implementazione, come la posizione dell'eseguibile e il linguaggio di programmazione.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. opzioni di configurazione Com
Nome | Default | Modificabile in | Log variazioni |
---|---|---|---|
com.allow_dcom | "0" | PHP_INI_SYSTEM | Disponibile dal PHP 4.0.5. |
com.autoregister_typelib | "0" | PHP_INI_SYSTEM | PHP_INI_SYSTEM in PHP 4. Disponibile in PHP 4.1.0. |
com.autoregister_verbose | "0" | PHP_INI_SYSTEM | PHP_INI_SYSTEM in PHP 4. Disponibile dal PHP 4.1.0. |
com.autoregister_casesensitive | "1" | PHP_INI_SYSTEM | PHP_INI_SYSTEM in PHP 4. Disponibile dal PHP 4.1.0. |
com.code_page | "" | PHP_INI_ALL | Disponibile dal PHP 5.0.0. |
com.typelib_file | "" | PHP_INI_SYSTEM | Disponibile dal PHP 4.0.5. |
Breve descrizione dei parametri di configurazione.
Quando è impostato a on, il PHP è abilitao ad operare come client D-COM (COM distribuito) e permette agli script PHP di istanziare oggetti COM su un server remoto.
Quando questo parametro è impostato a on il PHP tenta di registrare costanti dalla libreria dei tipi dell'oggetto che istanzia, se l'pggetto implementa l'interfaccia richiesta per ottenere le informazioni in oggetto. Se distinguere tra nomi dlle costanti maiuscoli e minuscoli è controllato dal parametro com.autoregister_casesensitive .
When this is turned on, any problems with loading a typelibrary during object instantiation will be reported using the PHP error mechanism. The default is off, which does not emit any indication if there was an error finding or loading the type library.
When this is turned on (the default), constants found in auto-loaded type libraries will be registered case sensitively. See com_load_typelib() for more details.
It controls the default character set code-page to use when passing strings to and from COM objects. If set to an empty string, PHP will assume that you want CP_ACP, which is the default system ANSI code page.
If the text in your scripts is encoded using a different encoding/character set by default, setting this directive will save you from having to pass the code page as a parameter to the COM class constructor. Please note that by using this directive (as with any PHP configuration directive), your PHP script becomes less portable; you should use the COM constructor parameter whenever possible.
Nota: This configuration directive was introduced with PHP 5.
When set, this should hold the path to a file that contains a list of typelibraries that should be loaded on startup. Each line of the file will be treated as the type library name and loaded as though you had called com_load_typelib(). The constants will be registered persistently, so that the library only needs to be loaded once. If a type library name ends with the string #cis or #case_insensitive, then the constants from that library will be registered case insensitively.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Per maggiori informazioni su COM si leggano le specifiche COM o si guardi anche la documentazione di Don Box su Yet Another COM Library (YACL)
costruttore della classe COM. Parametri:
nome o class-id del componente desiderato.
nome del server DCOM dal quale deve essere richiamato il componente. Se NULL, si assume localhost. Per permettere l'uso di DCOM il parametro com.allow_dcom deve essere impostato a TRUE in php.ini.
specifica la codepage che verrà usata per convertire le stringhe di PHP in stringhe Unicode e viceversa. I valori possibili sono CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 e CP_UTF8.
Esempio 1. esempio di COM (1)
|
Esempio 2. esempio di COM (2)
|
The DOTNET class allows you to instantiate a class from a .Net assembly and call its methods and access its properties.
DOTNET class constructor. assembly_name specifies which assembly should be loaded, and class_name specifices which class in that assembly to instantiate. You may optionally specify a codepage to use for unicode string transformations; see the COM class for more details on code pages.
The returned object is an overloaded object, which means that PHP does not see any fixed methods as it does with regular classes; instead, any property or method accesses are passed through to COM and from there to DOTNET. In other words, the .Net object is mapped through the COM interoperability layer provided by the .Net runtime.
Once you have created a DOTNET object, PHP treats it identically to any other COM object; all the same rules apply.
Nota: You need to install the .Net runtime on your web server to take advantage of this feature.
costruttore della classe VARIANT. Parametri:
valore iniziale. se omesso viene creato un oggetto VT_EMPTY.
specifica il tipo di contenuto dell'oggetto VARIANT. I valori possibili sono VT_UI1, VT_UI2, VT_UI4, VT_I1, VT_I2, VT_I4, VT_R4, VT_R8, VT_INT, VT_UINT, VT_BOOL, VT_ERROR, VT_CY, VT_DATE, VT_BSTR, VT_DECIMAL, VT_UNKNOWN, VT_DISPATCH e VT_VARIANT. Questi valori sono mutuallmente esclusivi, ma possono essere combinati con VT_BYREF per specificare che è un valore. Se omesso, viene usato il tipo di valore. Consultare la libreria MSDN per ulteriori informazioni.
specifica la codepage che è usata per convertire le stringhe PHP in stringhe unicode e viceversa. I valori possibili sono CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 e CP_UTF8.
Generates a Globally Unique Identifier (GUID) and returns it as a string. A GUID is generated in the same way as DCE UUID's, except that the Microsoft convention is to enclose a GUID in curly braces.
See also uuid_create() in the PECL uuid extension.
Instructs COM to sink events generated by comobject into the PHP object sinkobject. PHP will attempt to use the default dispinterface type specified by the typelibrary associated with comobject, but you may override this choice by setting sinkinterface to the name of the dispinterface that you want to use.
sinkobject should be an instance of a class with methods named after those of the desired dispinterface; you may use com_print_typeinfo() to help generate a template class for this purpose.
Be careful how you use this feature; if you are doing something similar to the example below, then it doesn't really make sense to run it in a web server context.
Esempio 1. COM event sink example
|
See also com_print_typeinfo(), com_message_pump().
com_get_active_object() is similar to creating a new instance of a COM object, except that it will only return an object to your script if the object is already running. OLE applications use something known as the Running Object Table to allow well-known applications to be launched only once; this function exposes the COM library function GetActiveObject() to get a handle on a running instance.
progid must be either the ProgID or CLSID for the object that you want to access (for example Word.Application). code_page acts in precisely the same way that it does for the COM class.
If the requested object is running, it will be returned to your script just like any other COM object. Otherwise a com_exception will be raised. There are a variety of reasons why this function might fail, the most common being that the object is not already running. In that situation, the exception error code will be MK_E_UNAVAILABLE; you can use the getCode method of the exception object to check the exception code.
Avvertimento |
Using com_get_active_object() in a web server context is not always a smart idea. Most COM/OLE applications are not designed to handle more than one client concurrently, even (or especially!) Microsoft Office. You should read Considerations for Server-Side Automation of Office for more information on the general issues involved. |
Restituisce il valore della proprietà nome_prop del componente COM referenziato da oggetto_com. Restituisce FALSE in caso di errore.
com_invoke() chiama un metodo del componente COM referenziato da oggetto_com. Restituisce FALSE in caso di errore, altrimenti restituisce il valore di ritorno di nome_funzione.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
com_load() crea un nuovo componente COM e ne restituisce un riferimento. Restituisce FALSE in caso di errore. I possibili valori per codepage sono CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 e CP_UTF8.
(PHP 4 >= 4.2.3, PHP 5)
com_message_pump -- Process COM messages, sleeping for up to timeoutms millisecondsThis function will sleep for up to timeoutms milliseconds, or until a message arrives in the queue. If a message or messages arrives before the timeout, they will be dispatched, and the function will return TRUE. If the timeout occurs and no messages were processed, the return value will be FALSE. If you do not specify a value for timeoutms, then 0 will be assumed. A 0 value means that no waiting will be performed; if there are messages pending they will be dispatched as before; if there are no messages pending, the function will return FALSE immediately without sleeping.
The purpose of this function is to route COM calls between apartments and handle various synchronization issues. This allows your script to wait efficiently for events to be triggered, while still handling other events or running other code in the background. You should use it in a loop, as demonstrated by the example in the com_event_sink() function, until you are finished using event bound COM objects.
(PHP 4 >= 4.2.3, PHP 5)
com_print_typeinfo -- Print out a PHP class definition for a dispatchable interfaceThe purpose of this function is to help generate a skeleton class for use as an event sink. You may also use it to generate a dump of any COM object, provided that it supports enough of the introspection interfaces, and that you know the name of the interface you want to display.
comobject should be either an instance of a COM object, or be the name of a typelibrary (which will be resolved according to the rules set out in com_load_typelib()). dispinterface is the name of an IDispatch descendant interface that you want to display. If wantsink is TRUE, the corresponding sink interface will be displayed instead.
See also com_event_sink(), com_load_typelib().
Imposta il valore della proprietà nome_prop del componente COM referenziato da oggetto_com. Restituisce il valore appena impostato in caso di successo,, FALSE altrimenti.
Returns the absolute value of val.
See also abs().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Adds left to right using the following rules (taken from the MSDN library), which correspond to those of Visual Basic:
Tabella 1. Variant Addition Rules
If | Then |
---|---|
Both expressions are of the string type | Concatenation |
One expression is a string type and the other a character | Addition |
One expression is numeric and the other is a string | Addition |
Both expressions are numeric | Addition |
Either expression is NULL | NULL is returned |
Both expressions are empty | Integer subtype is returned |
See also variant_sub().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs a bitwise AND operation, according to the following truth table; note that this is slightly different from a regular AND operation.
Tabella 1. Variant AND Rules
If left is | If right is | then the result is |
---|---|---|
TRUE | TRUE | TRUE |
TRUE | FALSE | FALSE |
TRUE | NULL | NULL |
FALSE | TRUE | FALSE |
FALSE | FALSE | FALSE |
FALSE | NULL | FALSE |
NULL | TRUE | NULL |
NULL | FALSE | FALSE |
NULL | NULL | NULL |
See also variant_or().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
This function makes a copy of variant and then performs a variant cast operation to force the copy to have the type given by type. type should be one of the VT_XXX constants.
This function wraps VariantChangeType() in the COM library; consult MSDN for more information.
See also variant_set_type().
Concatenates left with right and returns the result.
See also la Sezione Operatori di stringa nel Capitolo 15 for the string concatenation operator; this function is notionally equivalent to $left . $right.
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Compares left with right and returns one of the following values:
Tabella 1. Variant Comparision Results
value | meaning |
---|---|
VARCMP_LT | left is less than right |
VARCMP_EQ | left is equal to right |
VARCMP_GT | left is greater than right |
VARCMP_NULL | Either left, right or both are NULL |
This function will only compare scalar values, not arrays or variant records.
lcid is a valid Locale Identifier to use when comparing strings (this affects string collation). flags can be one or more of the following values OR'd together, and affects string comparisons:
Tabella 2. Variant Comparision Flags
value | meaning |
---|---|
NORM_IGNORECASE | Compare case insensitively |
NORM_IGNORENONSPACE | Ignore nonspacing characters |
NORM_IGNORESYMBOLS | Ignore symbols |
NORM_IGNOREWIDTH | Ignore string width |
NORM_IGNOREKANATYPE | Ignore Kana type |
NORM_IGNOREKASHIDA | Ignore Arabic kashida characters |
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Converts timestamp from a unix timestamp value into a variant of type VT_DATE. This allows easier interopability between the unix-ish parts of PHP and COM.
See also variant_date_to_timestamp() for the inverse of this operation, mktime(), time().
Converts variant from a VT_DATE (or similar) value into a unix timestamp. This allows easier interopability between the unix-ish parts of PHP and COM.
See also variant_date_from_timestamp() for the inverse of this operation, date(), strftime().
Divides left by right and returns the result, subject to the following rules:
Tabella 1. Variant Division Rules
If | Then |
---|---|
Both expressions are of the string, date, character, boolean type | Double is returned |
One expression is a string type and the other a character | Division and a double is returned |
One expression is numeric and the other is a string | Division and a double is returned. |
Both expressions are numeric | Division and a double is returned |
Either expression is NULL | NULL is returned |
right is empty and left is anything but empty | A com_exception with code DISP_E_DIVBYZERO is thrown |
left is empty and right is anything but empty. | 0 as type double is returned |
Both expressions are empty | A com_exception with code DISP_E_OVERFLOW is thrown |
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
If each bit in left is equal to the corresponding bit in right then TRUE is returned, otherwise FALSE is returned.
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
If variant is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of variant.
See also variant_int(), variant_round(), floor(), ceil(), round().
Avvertimento |
This documentation is based on the MSDN documentation; it appears that this function is either the same as variant_int(), or that there is an error in the MSDN documentation. |
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
This function returns an integer value that indicates the type of variant, which can be an instance of COM, DOTNET or VARIANT classes. The return value can be compared to one of the VT_XXX constants.
The return value for COM and DOTNET objects will usually be VT_DISPATCH; the only reason this function works for those classes is because COM and DOTNET are descendants of VARIANT.
In PHP versions prior to 5, you could obtain this information from instances of the VARIANT class ONLY, by reading a fake type property. See the VARIANT class for more information on this.
Converts left and right to integer values, and then performs integer division according the following rules:
Tabella 1. Variant Integer Division Rules
If | Then |
---|---|
Both expressions are of the string, date, character, boolean type | Division and integer is returned |
One expression is a string type and the other a character | Division |
One expression is numeric and the other is a string | Division |
Both expressions are numeric | Division |
Either expression is NULL | NULL is returned |
Both expressions are empty | A com_exception with code DISP_E_DIVBYZERO is thrown |
See also variant_div().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs a bitwise implication operation, according to the following truth table:
Tabella 1. Variant Implication Table
If left is | If right is | then the result is |
---|---|---|
TRUE | TRUE | TRUE |
TRUE | FALSE | TRUE |
TRUE | NULL | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | TRUE |
FALSE | NULL | TRUE |
NULL | TRUE | TRUE |
NULL | FALSE | NULL |
NULL | NULL | NULL |
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
If variant is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of variant.
See also variant_fix(), variant_round(), floor(), ceil(), round().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Divides left by right and returns the remainder.
See also variant_div(), variant_idiv().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Multiplies left by right and returns the result, subject to the following rules:
Tabella 1. Variant Multiplication Rules
If | Then |
---|---|
Both expressions are of the string, date, character, boolean type | Multiplication |
One expression is a string type and the other a character | Multiplication |
One expression is numeric and the other is a string | Multiplication |
Both expressions are numeric | Multiplication |
Either expression is NULL | NULL is returned |
Both expressions are empty | Empty string is returned |
Boolean values are converted to -1 for FALSE and 0 for TRUE.
See also variant_div(), variant_idiv().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs logical negation of variant and returns the result.
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs bitwise not negation on variant and returns the result. If variant is NULL, the result will also be NULL.
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs a bitwise OR operation, according to the following truth table; note that this is slightly different from a regular OR operation.
Tabella 1. Variant OR Rules
If left is | If right is | then the result is |
---|---|---|
TRUE | TRUE | TRUE |
TRUE | FALSE | TRUE |
TRUE | NULL | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | FALSE |
FALSE | NULL | NULL |
NULL | TRUE | TRUE |
NULL | FALSE | NULL |
NULL | NULL | NULL |
See also variant_and(), variant_xor().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Returns the result of left to the power of right.
See also pow().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Returns the value of variant rounded to decimals decimal places.
See also round().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
This function is similar to variant_cast() except that the variant is modified "in-place"; no new variant is created. The parameters for this function have identical meaning to those of variant_cast().
See also variant_cast().
Converts value to a variant and assigns it to the variant object; no new variant object is created, and the old value of variant is freed/released.
(PHP 5)
variant_sub -- subtracts the value of the right variant from the left variant value and returns the resultSubtracts right from left using the following rules:
Tabella 1. Variant Subtraction Rules
If | Then |
---|---|
Both expressions are of the string type | Subtraction |
One expression is a string type and the other a character | Subtraction |
One expression is numeric and the other is a string | Subtraction. |
Both expressions are numeric | Subtraction |
Either expression is NULL | NULL is returned |
Both expressions are empty | Empty string is returned |
See also variant_add().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs a logical exclusion, according to the following truth table:
Tabella 1. Variant XOR Rules
If left is | If right is | then the result is |
---|---|---|
TRUE | TRUE | FALSE |
TRUE | FALSE | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | FALSE |
NULL | NULL | NULL |
See also variant_and(), variant_or().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Queste funzioni permettono di usare la libreria CrackLib per testare la 'forza' di una password. La 'forza' di una password è testata attraverso un controllo sulla lunghezza, sull'uso di maiuscole e minuscole ed un controllo attraverso lo specifico dizionario di CrackLib. CrackLib darà anche utili messaggi diagnostici che aiuteranno nel 'rafforzare' la password.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.0.0.
Maggiori informazioni riguardo CrackLib possono essere trovate, insieme alla libreria, a http://www.crypticide.com/users/alecm/.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/crack.
In PHP 4 this PECL extensions source can be found in the ext/ directory within the PHP source or at the PECL link above. Per potere utilizzare queste funzioni, occorre compilare il PHP con il supporto per Crack utilizzando --with-crack[=DIR] option.
Gli utenti di Windows dovranno abilitare php_crack.dll nel php.ini per potere utilizzare queste funzioni. In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Opzioni di configurazione per Crack
Nome | Default | Modificabile | Log modifiche |
---|---|---|---|
crack.default_dictionary | NULL | PHP_INI_SYSTEM | Disponibile da PHP 4.0.5. |
Questo esempio mostra come aprire un dizionario di CrackLib, testare una determinata password, recuperare ogni messaggio diagnostico e chiudere il dizionario.
Esempio 1. Esempio di CrackLib
|
Nota: Se crack_check() restituisce TRUE, crack_getlastmessage() restituirà 'password forte'.
Restituisce TRUE se password è forte, altrimenti FALSE.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
crack_check() effettua un controllo nascosto della password data nel dizionario specificato. Se dizionario non è specificato viene utilizzato l'ultimo dizionario aperto.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
crack_closedict() chiude l'identificatore del dizionario specificato. Se dizionario non è specificato, verrà chiuso il dizionario corrente.
(PHP 4 >= 4.0.5, PECL)
crack_getlastmessage -- Restituisce il messaggio dell'ultimo controllo nascostoAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
crack_getlastmessage() restituisce il messaggio dell'ultimo controllo nascosto.
Restituisce un identificatore di risorsa dizionario in caso di successo, o FALSE in caso di fallimento.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
crack_opendict() apre il dizionario specificato di CrackLib per usarlo con crack_check().
Nota: Può essere aperto solo un dizionario alla volta.
Vedere anche: crack_check() e crack_closedict().
Le funzioni fornite da questa estensione controllano se un carattere o una stringa rientrano in una classe di caratteri in accordo con l'ambiente corrente (vedere anche setlocale()).
Quando vengono chiamate con un numero intero come argomento queste funzioni si comportano esattamente come il loro equivalente in C presente in ctype.h.
Quando vengono chiamate con una stringa come argomento controlleranno ogni carattere della stringa e ritorneranno TRUE se ogni carattere della stringa soddisfa il criterio richiesto. Quando sono eseguite con una stringa vuota il risultato è sempre TRUE
Passare qualsiasi cosa eccetto una stringa o un numero intero restituirà immediatamenente FALSE.
A partire da PHP 4.2.0 queste funzioni sono abilitate di default. Per le versioni più vecchie bisogna configurare e compilare PHP con --enable-ctype.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Nota: Il supporto per CType pre-compilato è disponibile a partire dalla versione 4.3.0.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Restituisce TRUE se ogni carattere di testo è una lettera o una cifra, FALSE in caso contrario. Nell'ambiente standard del C le lettere sono solamente [A-Za-z] e la funzione è equivalente a preg_match('/^[a-z0-9]*$/i', $text).
Esempio 1. Esempio di uso di ctype_alnum() (utilizzando le impostazioni locali di default)
Questo esempio visualizzerà :
|
Vedere anche ctype_alpha(), ctype_digit() e setlocale().
Restituisce TRUE se ogni carattere di testo è una lettera dell'ambiente corrente, FALSE in caso contrario. Nell'ambiente standard del C le lettere sono solo [A-Za-z] e ctype_alpha() è equivalente a (ctype_upper($text) || ctype_lower($text)), se $text è di un singolo carattere, ma altri linguaggi hanno lettere che non sono considerate nè maiuscole nè minuscole.
Esempio 1. Esempio di uso di ctype_alpha() (utilizzando le impostazioni locali di default)
This example will output :
|
Vedere anche ctype_upper(), ctype_lower() e setlocale().
Restituisce TRUE se ogni carattere di testo ha una speciale funzione di controllo, FALSE in caso contrario. I caratteri di controllo sono per esempio line feed (avanza di una riga), tab, esc.
Esempio 1. Esempio di uso di ctype_cntrl()
L'esempio visualizzerà :
|
Restituisce TRUE se ogni carattere di testo è una cifra decimale, FALSE in caso contrario.
Esempio 1. Esempio di uso di ctype_digit()
Questo esempio visualizzerà :
|
Vedere anche ctype_alnum() e ctype_xdigit().
Restituisce TRUE se ogni carattere di testo è stampabile e crea un output realmente visibile (senza spazi bianchi), FALSE in caso contrario.
Esempio 1. Esempio di uso di ctype_graph()
Questo esempio visualizzerà :
|
Vedere anche ctype_alnum(), ctype_print() e ctype_punct().
Restituisce TRUE se ogni carattere di testo è una lettera minuscola nell'ambiente corrente.
Esempio 1. Esempio di uso di ctype_lower() (utilizzando le impostazioni locali di default)
Questo esempio visualizzerà :
|
Vedere anche ctype_alpha(), ctype_upper() e setlocale().
Restituisce TRUE se ogni carattere di testo creerà veramente un output (compresi gli spazi). Restituisce FALSE se testo contiene dei caratteri di controllo o caratteri che non hanno nessun output o che non hanno per niente una funzione di controllo.
Esempio 1. Esempio di uso di ctype_print()
Questo esempio visualizzerà :
|
Vedere anche ctype_cntrl(), ctype_graph() e ctype_punct().
(PHP 4 >= 4.0.4, PHP 5)
ctype_punct -- Controlla ogni carattere stampabile che non è uno spazio o un carattere alfanumericoRestituisce TRUE se ogni carattere di testo è stampabile, ma non è nè una lettera nè; una cifra nè uno spazio, FALSE in caso contrario.
Esempio 1. Esempio di uso di ctype_punct()
Questo esempio visualizzerà :
|
Vedere anche ctype_cntrl() e ctype_graph().
Restituisce TRUE se ogni carattere di testo crea qualche tipo di spazio, FALSE in caso contrario. Oltre allo spazio questo include anche tab, tab verticale, line feed (avanza di una riga), carriage return (a capo) e form feed (avanza di un modulo).
Esempio 1. Esempio di uso di ctype_space()
Questo esempio visualizzerà :
|
Vedere anche ctype_cntrl(), ctype_graph() e ctype_punct().
Restituisce TRUE se ogni carattere di testo è una lettera maiuscola nell'ambiente corrente.
Esempio 1. Esempio di uso di ctype_upper() (utilizzando le impostazioni locali di default)
Questo esempio visualizzerà :
|
Vedere anche ctype_alpha(), ctype_lower(), e setlocale().
(PHP 4 >= 4.0.4, PHP 5)
ctype_xdigit -- Controlla i caratteri che rappresentano una cifra esadecimaleRestituisce TRUE se ogni carattere di testo è una 'cifra' esadecimale, cioè una cifra decimale o un carattere fra [A-Fa-f] , FALSE in caso contrario.
Esempio 1. Esempio di uso di ctype_xdigit()
Questo esempio visualizzerà :
|
Vedere anche ctype_digit().
PHP supporta libcurl, una libreria creata da Daniel Stenberg, che permette di collegarsi e comunicare con parecchi tipi di server e con parecchi tipi di protocolli. Libcurl al momento supporta i protocolli http, https, ftp, gopher, telnet, dict, file, e ldap. libcurl supporta anche i certificati HTTPS, HTTP POST, HTTP PUT, l'upload via FTP (questo può essere ottenuto anche con l'estensione ftp di PHP), upload attraverso una form HTTP, proxy, cookie e autenticazione con utente e password.
Queste funzioni sono state aggiunte in PHP 4.0.2.
Per utilizzare le funzioni CURL occorre installare il pacchetto CURL. PHP richiede che si usi CURL 7.0.2-beta o successivi. PHP non funzionerà con alcuna versione di CURL antecedente alla 7.0.2-beta. Dalla versione 4.2.3 di PHP è necessario usare CURL versione 7.9.0 o successiva. Con PHP 4.3.0 occorre avere CURL 7.9.8 o successive. PHP 5.0.0 molto probabilmente richiederà CURL 7.10.5 o successiva.
Al fine di utilizzare il supporto CURL occorre anche compilare PHP con --with-curl[=DIR] dove DIR è il percorso della directory che contiene le directory lib e include. Nella directory "include" ci dovrebbe essere una cartella chiamata "curl" che dovrebbe contenere i file easy.h e curl.h. Ci dovrebbe essere un file chiamato libcurl.a nella directory "lib". A cominciare da PHP 4.3.0 si può configurare PHP all'uso di CURL per gli URL stream --with-curlwrappers.
Nota agli utenti Win32: Per abilitare questo modulo in ambiente Windows, occorre copiare libeay32.dll e ssleay32.dll dalla cartella delle DLL del pacchetto PHP/Win32 nella cartella SYSTEM32 della propria macchina Windows. (Es: C:\WINNT\SYSTEM32 o C:\WINDOWS\SYSTEM)
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Disponibile da PHP 5.1.0
Available since PHP 5.1.0
Available since PHP 5.1.0
Disponibile da PHP 5.1.0
Una volta compilato PHP con supporto CURL, si possono usare le funzioni CURL. L'idea di fondo che sta dietro le funzioni CURL è: si inizializza una sessione CURL usando curl_init(), si impostano le opzioni per il trasferimento tramite curl_setopt(), si esegue la sessione usando curl_exec() e quindi si termina la sessione con curl_close(). Qui di seguito si trova un esempio che fa uso delle funzioni CURL per scaricare la homepage del sito example.com e metterla in un file:
Questa funzione chiude una sessione CURL e libera tutte le risorse. L'handle CURL ch viene anch'esso eliminato.
Esempio 1. Inizializza una sessione CURL e scarica una pagina
|
Vedere anche: curl_init().
This function copies a cURL handle, returning a new cURL handle with the same preferences.
Esempio 1. Copying a cURL handle.
|
La funzione resituisce il numero dell'errore per l'ultima operazione cURL sulla risorsa ch, oppure 0 (zero) se non vi sono errori.
Vedere anche curl_error() e I codici di errore CURL.
(PHP 4 >= 4.0.3, PHP 5)
curl_error -- Restituisce una stringa contenente l'ultimo errore relativo alla sessione correnteLa funzione restituisce un messaggio di errore testuale per l'ultima operazione cURL eseguita sulla risorsa ch, oppure '' (una stringa vuota) se non vi sono errori.
Vedere anche curl_errno() e Codici di errore CURL.
Questa funzione deve essere chiamata dopo aver inizializzato una sessione CURL e dopo che tutte le opzioni per la sessione sono state impostate. La sua funzione è semplicemente quella di eseguire la sessione CURL predefinita (identificata dal parametro ch).
Esempio 1. Inizializza una sessione CURL e scarica una pagina web.
|
Nota: Se si desidera avere restituito il risultato anzichè averlo visualizzato direttamente sul browser, utilizzare l'opzione CURLOPT_RETURNTRANSFER di curl_setopt().
La funzione restituisce informazioni sull'ultimo trasferimento, il parametro opt può assumere uno dei seguenti valori:
"CURLINFO_EFFECTIVE_URL" - L'ultimo URL reale
"CURLINFO_HTTP_CODE" - L'ultimo codice HTTP ricevuto
"CURLINFO_FILETIME" - Data del documento remoto ricevuto, -1 indica che la data del documento è sconosciuta
"CURLINFO_TOTAL_TIME" - Tempo totale in secondi per l'ultimo trasferimento
"CURLINFO_NAMELOOKUP_TIME" - Tempo in secondi impiegato per risolvere il nome
"CURLINFO_CONNECT_TIME" - Tempo in secondi necessario per stabilire la connessione
"CURLINFO_PRETRANSFER_TIME" - Tempo in secondi dall'inizio fino a prima di cominciare il trasferimento
"CURLINFO_STARTTRANSFER_TIME" - Tempo in secondi fino a quando comincia il trasferimento del primo byte
"CURLINFO_REDIRECT_TIME" - Tempo in secondi richiesto dai passi di redirezione prima che sia cominciata la transazione finale
"CURLINFO_SIZE_UPLOAD" - Numero totale dei byte inviati
"CURLINFO_SIZE_DOWNLOAD" - Numero totale dei byte scaricati
"CURLINFO_SPEED_DOWNLOAD" - Velocità media di download
"CURLINFO_SPEED_UPLOAD" - Velocità media di upload
"CURLINFO_HEADER_SIZE" - Dimensione totale di tutte le header ricevute
"CURLINFO_REQUEST_SIZE" - Dimensione totale delle richieste, attualmente solo per le richieste HTTP
"CURLINFO_SSL_VERIFYRESULT" - Risultato delle verifiche del certificato richieste da CURLOPT_SSL_VERIFYPEER
"CURLINFO_CONTENT_LENGTH_DOWNLOAD" - Lunghezza del download ottenuta dal campo Content-Length:
"CURLINFO_CONTENT_LENGTH_UPLOAD" - Dimensione specificata dell'upload
"CURLINFO_CONTENT_TYPE" - Content-type dell'oggetto scaricato, il valore NULL indica che il server non ha inviato un Content-Type: valido
Se la funzione viene eseguita senza il parametro opzionale opt, sarà restituito un array contenente i seguenti elementi corrispondenti alle opzioni di opt:
"url"
"content_type"
"http_code"
"header_size"
"request_size"
"filetime"
"ssl_verify_result"
"redirect_count"
"total_time"
"namelookup_time"
"connect_time"
"pretransfer_time"
"size_upload"
"size_download"
"speed_download"
"speed_upload"
"download_content_length"
"upload_content_length"
"starttransfer_time"
"redirect_time"
curl_init() inizializza una nuova sessione e restituisce un handle CURL da usarsi con le funzioni curl_setopt(), curl_exec() e curl_close(). Se viene dato il parametro opzionale url, allora l'opzione CURLOPT_URL verrà impostata al valore di quel parametro. Questo si può impostare manualmente usando la funzione curl_setopt().
Esempio 1. Inizializzare una nuova sessione CURL e scaricare una pagina web
|
Vedere anche: curl_close() e curl_setopt().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init(), curl_init() e curl_multi_remove_handle().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init() e curl_close().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init() e curl_exec().
(PHP 5)
curl_multi_getcontent -- Restituisce il contenuto di un handle cURL se è impostato CURLOPT_RETURNTRANSFERAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_init() e curl_multi_close().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init(), curl_init() e curl_multi_add_handle().
(PHP 5)
curl_multi_select -- Restituisce tutti i socket associati alla estensione cURL che possono essere "selected"Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init().
Imposta le opzioni per una sessione CURL identificata dal parametro ch. opzione specifica quale opzione impostare e valore specifica il valore per l'opzione data.
valore dovrebbe essere di tipo booleano per i seguenti valori del parametro opzione):
Option | Set value to | Notes |
---|---|---|
CURLOPT_BINARYTRANSFER | TRUE restituisce la riga di output quando CURLOPT_RETURNTRANSFER è usata. | |
CURLOPT_CRLF | TRUE per convertire la Unix newlines in CRLF newlines per i trasferimenti. | |
CURLOPT_DNS_USE_GLOBAL_CACHE | TRUE per usare una cache gobale DNS. Questa opzione non è thread-safe ed è abilitata per default. | |
CURLOPT_FAILONERROR | TRUE per terminare in maniera silenziosa se il codice HTTP restituito è maggiore di 300. Il comportamento di default è di restituire la pagina normalmente, ignorando il codice. | |
CURLOPT_FILETIME | TRUE per cercare di recuperare la data di modifica del documento remoto. Si può cercare di ripristinare questo valore usando l'opzione CURLINFO_FILETIME con curl_getinfo(). | |
CURLOPT_FOLLOWLOCATION | TRUE per seguire una qualunque "Location: " intestazione inviata dal server come parte dell' header HTTP (notare che è ricorsiva, PHP seguirà come molte "Location: " intestazioni inviate, a meno che CURLOPT_MAXREDIRS sia impostata). | |
CURLOPT_FORBID_REUSE | TRUE forza la chiusura esplicita della connessione quando ha finito il processo e non può essere riutilizzata. | |
CURLOPT_FRESH_CONNECT | TRUE forza l'uso di una nuova connessione invece di usarne una in cache. | |
CURLOPT_FTP_USE_EPRT | TRUE per usare EPRT (e LPRT) quando si opera un download FTP. Usa FALSE per disaibilitare EPRT e LPRT e usare PORT solamente. | |
CURLOPT_FTP_USE_EPSV | TRUE prima cerca un comando EPSV per trasferimento FTP prima di ritornare alla modalità PASV. Imposta a FALSE per disabilitare EPSV. | |
CURLOPT_FTPAPPEND | TRUE per accodare aò file remoto invece di sovrascriverlo. | |
CURLOPT_FTPASCII | Un alias di CURLOPT_TRANSFERTEXT. Usarlo al suo posto. | |
CURLOPT_FTPLISTONLY | TRUE per elencare solamente i nomi di una directory FTP. | |
CURLOPT_HEADER | TRUE per includere l'intestazione in output. | |
CURLOPT_HTTPGET | TRUE per resettare la richiesta HTTP col metodo GET. Dopo che GET è il default, diventa necessario solo se il metodo di richiesta è cambiato. | |
CURLOPT_HTTPPROXYTUNNEL | TRUE per passare attraverso un proxy HTTP fornito. | |
CURLOPT_MUTE | TRUE per essere totalemtne silenzioso nei riguardi di una funzione CURL. | |
CURLOPT_NETRC | TRUE per condurre il file ~/.netrc a trovare username e password per il sito remoto col quale si stabilisce una connessione. | |
CURLOPT_NOBODY | TRUE esclude il corpo dall'output. | |
CURLOPT_NOPROGRESS |
TRUE per disabilitare il progress meter per trasferimetni CURL.
| |
CURLOPT_NOSIGNAL | TRUE per ignorare qualunque funzione CURL che causa l'invio di un segnale a un processo PHP. Ciò è settato come default con le multi-threaded SAPI in modo che le opzioni di timeout possano essere ancora usate. | Aggiunto in CURL 7.10. |
CURLOPT_POST | TRUE per compiere un regolare HTTP POST. Questo POST è il tipo normale di application/x-www-form-urlencoded, più comunemente usata dai form HTML. | |
CURLOPT_PUT | TRUE per HTTP PUT un file. Il file da PUT deve essere impostato con CURLOPT_INFILE e CURLOPT_INFILESIZE. | |
CURLOPT_RETURNTRANSFER | TRUE per restituire il trasferimento come una stringa del valore restituito di curl_exec() al posto di metterlo in output direttamente. | |
CURLOPT_SSL_VERIFYPEER | FALSE per fermare CURL dal verificare i certificati dei peer. Un certificato alternativo di verificare può essere specificato con l'opzione CURLOPT_CAINFO o una directory certificata può essere specificata con l'opzione CURLOPT_CAPATH . CURLOPT_SSL_VERIFYHOST può anche dover essere messa TRUE o FALSE se CURLOPT_SSL_VERIFYPEER è disabilitata (il default è 2). | TRUE per default nel CURL 7.10. Default bundle installed as of CURL 7.10. |
CURLOPT_TRANSFERTEXT | TRUE per usare la modalità ASCII per trasferimenti FTP. Per LDAP, riporta i dati in testo iano invece che in HTML. Sui sistemi Windows, non imposterà STDOUT alla modalità binaria. | |
CURLOPT_UNRESTRICTED_AUTH | TRUE invia username e password quando le seguenti locazioni (che usano CURLOPT_FOLLOWLOCATION), anche quando l'hostname è cambiato. | |
CURLOPT_UPLOAD | TRUE per preparare un upload. | |
CURLOPT_VERBOSE | TRUE per inviare un'informazione di tipo verbose. Scrive l'output su STDERR, o sul file specificato usando CURLOPT_STDERR. |
value dovrebbe essere un intero per i seguenti valori del parametro option :
Option | Set value to | Notes |
---|---|---|
CURLOPT_BUFFERSIZE | La dimensione del buffer da utilizzare per ogni lettura. Non è garantito che questa richiesta venga soddisfatta, comunque. | Aggiunto in CURL 7.10. |
CURLOPT_CLOSEPOLICY | Anche CURLCLOSEPOLICY_LEAST_RECENTLY_USED or CURLCLOSEPOLICY_OLDEST. Ci sono altri tre CURLCLOSEPOLICY_ costanti, ma CURL non li supporta ancora. | |
CURLOPT_CONNECTTIMEOUT | Il numero di secondi da aspettare mentre si cerca di connettersi. Usare 0 per aspettare indefinitamente. | |
CURLOPT_DNS_CACHE_TIMEOUT | Il numero di secondi con cui mantenere le istanze DNS in memoria. Questa opzio è posta a 120 (2 minuti) per default. | |
CURLOPT_FTPSSLAUTH | Il metodo di autenticazione FTP (quando attivato): CURLFTPAUTH_SSL (cerca per primo SSL), CURLFTPAUTH_TLS (cerca per primo SSL), o CURLFTPAUTH_DEFAULT (lascia decidere a CURL). | Aggiunto in CURL 7.12.2 e disponibile da PHP 5.1.0 |
CURLOPT_HTTP_VERSION | CURL_HTTP_VERSION_NONE (default, lascia decidere CURL quale versione usare), CURL_HTTP_VERSION_1_0 (forza HTTP/1.0), o CURL_HTTP_VERSION_1_1 (forza HTTP/1.1). | |
CURLOPT_HTTPAUTH |
Il metodo(i) di autenticazione HTTP da usare. Le opzioni sono: CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE, CURLAUTH_NTLM, CURLAUTH_ANY, e CURLAUTH_ANYSAFE. Si può usre l'operatore binario | (or) per combinare più di un metodo. In questo caso, CURL testerà il server per vedere quali metodi esso supporta e sceglierà il migliore. CURLAUTH_ANY è un alias per CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM. CURLAUTH_ANYSAFE è un alias per CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM. | |
CURLOPT_INFILESIZE | La grandezza attesa, in bytes, del file quando si invia (upload) un file a un sito remoto. | |
CURLOPT_LOW_SPEED_LIMIT | La velocità di trasferimento, in bytes al secondo, in cui la trasmissione dovrebbe stare al di sotto durante CURLOPT_LOW_SPEED_TIME secondi affinchè PHP to consideri la trasmissione troppo lenta e la abortisca. | |
CURLOPT_LOW_SPEED_TIME | Il numero di secondi in cui il trasferimento dovrebbe stare al di sotto CURLOPT_LOW_SPEED_LIMIT in modo che PHP consideri la rasmisiosne troppo lenta e la abortisca. | |
CURLOPT_MAXCONNECTS | L'ammontare massimo di connessioni persistenti consentite. Quando il limite è raggiunto, CURLOPT_CLOSEPOLICY viene usata per determinare quale connessione chiudere. | |
CURLOPT_MAXREDIRS | L'ammontare massimo di redirezioni HTTP da seguire. Usare questa opzione insieme a CURLOPT_FOLLOWLOCATION. | |
CURLOPT_PORT | Un numero di porta alternativo a cui connettersi. | |
CURLOPT_PROXYAUTH | Il metodo di autenticazione HTTP da usare per la connessione al proxy. Usare la stessa bitmask come descritto in in CURLOPT_HTTPAUTH. Per l'autenticazione del proxy, solo CURLAUTH_BASIC e CURLAUTH_NTLM sono attualmente supportate. | Aggiunto in CURL 7.10.7 e PHP 5.1.0. |
CURLOPT_PROXYPORT | Il numero di porta del proxy alla quale connettersi. Questo numero può essere anche impostato in CURLOPT_PROXY. | |
CURLOPT_PROXYTYPE | Anche CURLPROXY_HTTP (default) o CURLPROXY_SOCKS5. | Aggiunto in CURL 7.10. |
CURLOPT_RESUME_FROM | L' offset, in byte, per ripristinare un trasferimento. | |
CURLOPT_SSL_VERIFYHOST | 1 per verificare l'esistenza di un nome comune nel certificato SSL peer . 2 per verificare l'esistenza di un nome comune e verificare inoltre che soddisfi l'hostname fornito. | |
CURLOPT_SSLVERSION | La versione SSL (2 or 3) da usare. Per default PHP cercherà di determinare ciò da se stesso, benchè in alcuni casi si possa impostarlo manualmente. | |
CURLOPT_TIMECONDITION | Come CURLOPT_TIMEVALUE è trattato. Usare CURL_TIMECOND_IFMODSINCE per restituire la pagina solo se è stata mpdificata dalla data specificata in CURLOPT_TIMEVALUE. Se non è stata modificata, un "304 Not Modified" header sarà restituito assumendo che CURLOPT_HEADER è TRUE. Usare CURL_TIMECOND_ISUNMODSINCE per l'effetto opposto. CURL_TIMECOND_IFMODSINCE è il default. | Aggiunto in PHP 5.1.0. |
CURLOPT_TIMEOUT | Il numero massimo di secondi per permettere alle funzioni CURL di essere eseguite. | |
CURLOPT_TIMEVALUE | Il tempo in secondi dal 1 Gennaio 1970. Il tempo verrà usato da CURLOPT_TIMECONDITION. Per default, CURL_TIMECOND_IFMODSINCE è usato. |
value dovrebbe essere una stringa per i seguenti valori del parametro option :
Option | Set value to | Notes |
---|---|---|
CURLOPT_CAINFO | Il nome di un file contenente uno o più certificati che verificano la parità. Ciò ha significato solo quando usato in combinazione con CURLOPT_SSL_VERIFYPEER. | |
CURLOPT_CAPATH | Una directory che contiene certificati multipli CA. Usare questa opzione insieme a CURLOPT_SSL_VERIFYPEER. | |
CURLOPT_COOKIE | The contents of the "Set-Cookie: " header to be used in the HTTP request. | |
CURLOPT_COOKIEFILE | Il nome del file che contiene i dati del cookie. Il cookie può essere nel formato Netscape, o solo un semplice header HTTP-style allegato in un file. | |
CURLOPT_COOKIEJAR | Il nome di un file in cui salvare tutti i cookie interni finchè la connessione termina. | |
CURLOPT_CUSTOMREQUEST |
Un metodo custom di richiesta da usare al posto di
"GET" o "HEAD" quando avviene una
richiesta HTTP. Ciò è utile per un
"DELETE" o altro, in più nasconde le richieste HTTP.
Valori validi sono termini quali "GET",
"POST", "CONNECT" e così via;
i.e. Non inserire un'intera riga di richieste HTTP qui. Ad esempio,
scrivere "GET /index.html HTTP/1.0\r\n\r\n"
sarebbe errato.
| |
CURLOPT_EGBSOCKET | Come CURLOPT_RANDOM_FILE, ecetto un filename per un Entropy Gathering Daemon socket. | |
CURLOPT_ENCODING | I contenuti di un' "Accept-Encoding: " header. Ciò abilita la decodifica della risposta. Termini supportati sono "identity", "deflate", e "gzip". Se viene impostata una stringa vuota, "", viene inviato un header contenente tutti i tipi di termini supportati. | |
CURLOPT_FTPPORT | Il valore che verrà utilizzato per ottenere un indirizzo IP da usare per l'istruzione FTP "POST" . L'istruzione "POST" indica al server remoto il proprio indirizzo IP a cui connettersi. La stringa può essere un semplice indirizzo IP, un hostname, un nome di un'interfaccia di rete (sotto Unix), o un semplice '-' per usare l'indirizzo Ip del sistema di default. | |
CURLOPT_INTERFACE | Il nome di un'interfaccia di rete di uscita da usare. Può essere il nome di un'interfaccia, un indirizzo IP o un host name. | |
CURLOPT_KRB4LEVEL | Il livello di sicurezza KRB4 (Kerberos 4). Uno qualunque dei valori seguenti (in ordine dal meno al più significativo) sono validi: "clear", "safe", "confidential", "private".. Se la stringa non corrisponde a uno di questi, si usa "private". Impostando questa opzione a NULL disabilita la sicurezza KRB4. Attualmente la sicurezza KRB4 lavora solamente con transazioni FTP. | |
CURLOPT_POSTFIELDS | I dati completi da mandare in post in un'operazione HTTP "POST" . | |
CURLOPT_PROXY | Il proxy HTTP in cui veicolare le richieste. | |
CURLOPT_PROXYUSERPWD | Username e password formattate come "[username]:[password]" da usare per la connessione al proxy. | |
CURLOPT_RANDOM_FILE | IL nome del file da passare al generatore di numeri casuali per SSL. | |
CURLOPT_RANGE | Intervallo(i) di dati da ricevere nel formato "X-Y" dove X o Y sono opzionali. I trasferimenti HTTP supportano inoltre svariati intervalli, separati da virgole nel formato "X-Y,N-M". | |
CURLOPT_REFERER | Il contenuto dell'header "Referer: " da usare in una richiesta HTTP. | |
CURLOPT_SSL_CIPHER_LIST | Elenco di cifre da usare con SSL. Per esempio, RC4-SHA e TLSv1 sono elenchi validi di cifre. | |
CURLOPT_SSLCERT | Il nome di un file contenente un certificato PEM formattato. | |
CURLOPT_SSLCERTPASSWD | La password richiesta per usare il CURLOPT_SSLCERT certificato. | |
CURLOPT_SSLCERTTYPE | Il formato del certificato. Formati ammessi sono "PEM" (default), "DER", e "ENG". | Aggiunto in CURL 7.9.3. |
CURLOPT_SSLENGINE | L' identificatore per il cripto-motore della chiave privata SSL specificata in CURLOPT_SSLKEY. | |
CURLOPT_SSLENGINE_DEFAULT | L' identificatore per il motore crypto usato per cripto-operazioni asimmetriche. | |
CURLOPT_SSLKEY | Il nome di un file contenente una chiave privata SSL. | |
CURLOPT_SSLKEYPASSWD |
La password segreta necessaria per usare la chiave privata SSL specificata in
CURLOPT_SSLKEY.
| |
CURLOPT_SSLKEYTYPE | Il tipo di chiave della chiave privata SSL specificata in CURLOPT_SSLKEY. I tipi di chiavi supportate sono "PEM" (default), "DER", e "ENG". | |
CURLOPT_URL | L' URL da raggiungere. E' possibnile impostarla quando si inizializza una sessione con curl_init(). | |
CURLOPT_USERAGENT | I contenuti dell'header "User-Agent: " da usare in una richiesta HTTP. | |
CURLOPT_USERPWD | Username e password formattate come "[username]:[password]" da usare per la connessione. |
value dovrebbe essere un array per i seguenti valori del parametro option :
Option | Set value to | Notes |
---|---|---|
CURLOPT_HTTP200ALIASES | Un array di 200 risposte HTTP che saranno trattate come risposte valide e non come errori. | Aggiunto in CURL 7.10.3. |
CURLOPT_HTTPHEADER | Un array di campi di header HTTP da impostare. | |
CURLOPT_POSTQUOTE | Un array di comandi FTP da eseguire sul server dopo che la richiesta FTP è stata eseguita. | |
CURLOPT_QUOTE | Un array di comandi FTP commands da eseguire sul server prima della richiesta FTP. |
value dovrebbe essere una risorsa di streaming (usando fopen(), per esempio) per i seguenti valori del parametro option :
Option | Set value to | Notes |
---|---|---|
CURLOPT_FILE | Il file che il trasferimento dovrebbe scrivere. Il default è STDOUT (la finestra del browser). | |
CURLOPT_INFILE | Il file ce il trasferimento dovrebbe leggere quando si fa un upload. | |
CURLOPT_STDERR | Una locazione alternativa per gli errori di output al posto di STDERR. | |
CURLOPT_WRITEHEADER | Il file su cui viene scritto l' header parte del trasferimento. |
value dovrebbe essere una stringa col nome di una funzione di callback valida per i seguenti valori del parametro option :
Option | Set value to | Notes |
---|---|---|
CURLOPT_HEADERFUNCTION | Il nome della funzione di callback la quale prende due parametri. il primo è la risorsa CURL, il secondo è una stringa con i dati dell'header da scrivere. Usando questa funzione di callback, diventa propria la responsabilità di scrivere i dati di header. Restituisce il numero di bytes scritti. | |
CURLOPT_PASSWDFUNCTION | Il nome della funzione di callback che prende tre parametri. Il primo è la risorsa CURL, il secondo è una stringa contenente la richiesta di password e il terzo è la lunghezza massima della password. Restituisce la stringa che contiene la password. | |
CURLOPT_READFUNCTION | Il nome della funzione di callback che prende due parametri. Il primo è la risorsa CURL, e il secondo è una stringa con i dati da leggere. Usindo questa funzione di callback, diventa propria la responsabilità di leggere i dati. Restituisce il numero di bytes letti. Restituisce 0 per un segnale di EOF. | |
CURLOPT_WRITEFUNCTION | Il nome della funzione di callback che prende due parametri. Il primo è la risorsa CURL, e il secondo è una stringa con i dati da scrivere. Usindo questa funzione di callback, diventa propria la responsabilità di scrivere i dati. Deve restituire l'esatto numero di bytes scritti altrimenti fallisce. |
Esempio 1. Inizializza una sessione CURL nuova e carica una pagina web
|
Queste funzione sono disponibili solo se l'interprete è stato compilato con l'opzione --with-cybercash=[DIR].
A partire da PHP 4.3.0 questo modulo è stato spostato, ed ora è reperibile in PECL.
Se si hanno dubbi sullo stato di CyberCash vedere CyberCash Faq In breve, CyberCash è stato acquisito da VeriSign e, sebbene il servizio CyberCash continui ad esistere, VeriSign incoraggia gli utenti a spostarsi. Vedere la faq precedente e PECL per dettagli.
La funzione restituisce un array associativo con gli elementi "errcode" e, se "errcode" è FALSE, "outbuff" (stringa), "outLth" (long) and "macbuff" (stringa).
Questa estensione vi permette di processare le transazioni delle carte di credito usando il sistema Crédit Mutuel CyberMUT (http://www.creditmutuel.fr/centre_commercial/vendez_sur_internet.html).
CynerMUT, in Francia, è un popolare servizio di pagamento tramite web, fornito dalla banca Crédit Mutuel. Se siete stranieri in Francia, queste funzioni non saranno utili.
Queste funzioni sono disponibili se PHP è stato compilato con l'opzione --with-cybermut[=DIR], dove DIR è la locazione di libcm-mac.a e cm-mac.h. Verrà richiesto l'appropriato SDK per la piattaforma, che sarà spedito dopo la sottoscrizione al servizio CyberMUT (contattateli via Web, o recatevi presso il più vicino Crédit Mutuel).
L'uso di queste funzioni è abbastanza simile alle funzioni originali, ad eccezione dei parametri restituiti da cybermut_creerformulairecm() e cybermut_creerreponsecm(), che sono restituiti direttamente dalle funzioni PHP, mentre loro sono passati in riferimento nelle funzioni originali.
Queste funzioni sono state aggiunte in PHP 4.0.6.
Nota: Queste funzioni forniscono solo un link all'SDK di CyberMUT. Assicuratevi di leggere la Guida per gli Sviluppatori del CyberMUT per i dettagli completi dei parametri richiesti.
(4.0.5 - 4.2.3 only, PECL)
cybermut_creerformulairecm -- Genera un form HTML per la richiesta di pagamentocybermut_creerformulairecm() è usato per generare il form HTML per la richiesta di pagamento.
Esempio 1. Primo passo di pagamento (equiv cgi1.c)
|
Vedere anche cybermut_testmac() e cybermut_creerreponsecm().
(4.0.5 - 4.2.3 only, PECL)
cybermut_creerreponsecm -- Genera la conferma della consegna della conferma di pagamentocybermut_creerreponsecm() restituisce una stringa contenente un messaggio di conferma di consegna.
Il parametro è "OK" se il messaggio di conferma del pagamento è stato correttamente autenticato da cybermut_testmac(). Ogni altra catena è considerata come un messaggio di errore.
Vedere anche cybermut_creerformulairecm() e cybermut_testmac().
(4.0.5 - 4.2.3 only, PECL)
cybermut_testmac -- Assicura che non siano contenuti dati manipolati nel messaggio di conferma ricevutocybermut_testmac() è usato per assicurare che non siano contenuti dati manipolati nel messaggio di conferma ricevuto. Prestate attenzione ai parametri code-retour e texte-libre, che non possono essere valutati tal quali, a causa del trattino. Dovete recuperarli usando:
<?php $code_retour=$HTTP_GET_VARS["code-retour"]; $texte_libre=$HTTP_GET_VARS["texte-libre"]; ?> |
Esempio 1. Ultimo passaggio del pagamento (equiv cgi2.c)
|
Vedere anche cybermut_creerformulairecm() e cybermut_creerreponsecm().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Questo modulo non è disponibile su piattaforme Windows.
Questo modulo è disponibile soltanto se PHP è stato configurato con l'opzione --with-cyrus .
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Queste funzioni ti permettono di scaricare la data e l'orario dal server dove gira il PHP. Puoi usare queste funzioni per formattare l'output delle date e degli orari in diversi modi.
Nota: Ricordati che queste funzioni dipendono dai settaggi locali del tuo server. Considera specialmente l'ora legale e gli anni bisestili.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Restituisce TRUE se la data inserita è valida; altrimenti restituisce FALSE. Controlla la validità di una data formata dagli argomenti. Una data è considerata valida se:
anno è compreso tra 1 e 32767
mese è compreso tra 1 e 12
Giorno è compreso tra il numero dei giorni possibile per il mese dato. Gli anno(i) bisestili sono presi in considerazione.
Guarda anche mktime() e strtotime().
(PHP 5 >= 5.1.0RC1)
date_default_timezone_get -- Gets the default timezone used by all date/time functions in a scriptThis functions returns the default timezone, using the following "guess" order:
The timezone set using the date_default_timezone_set() function (if any)
The TZ environment variable (if non empty)
The date.timezone ini option (if set)
"magical" guess (if the operating system supports it)
If none of the above options succeeds, return UTC
(PHP 5 >= 5.1.0RC1)
date_default_timezone_set -- Sets the default timezone used by all date/time functions in a scriptdate_default_timezone_set() sets the default timezone used by all date/time functions.
Nota: Since PHP 5.1.0 (when the date/time functions were rewritten), every call to a date/time function will generate a E_NOTICE if the timezone isn't valid, and/or a E_STRICT message if using the system settings or the TZ environment variable.
The timezone identifier, like UTC or Europe/Lisbon. The list of valid identifiers is available in the Appendice H.
date_sunrise() returns the sunrise time for a given day (specified as a timestamp) and location. The latitude, longitude and zenith parameters default to the date.default_latitude, date.default_longitude and date.sunrise_zenith configuration options, respectively.
The latitude defaults to North. So, if you want to specify a South value, you must pass a negative value. The same note applies to longitude, which defaults to East.
The gmt_offset parameter is specified in hours.
Tabella 1. format constants
constant | description | example |
---|---|---|
SUNFUNCS_RET_STRING | returns the result as string | 16:46 |
SUNFUNCS_RET_DOUBLE | returns the result as float | 16.78243132 |
SUNFUNCS_RET_TIMESTAMP | returns the result as integer (timestamp) | 1095034606 |
Esempio 1. date_sunrise() example
Il precedente esempio visualizzerà qualcosa simile a:
|
See also date_sunset().
date_sunset() returns the sunset time for a given day (specified as a timestamp) and location. The latitude, longitude and zenith parameters default to the date.default_latitude, date.default_longitude and date.sunset_zenith configuration options, respectively.
The latitude defaults to North. So, if you want to specify a South value, you must pass a negative value. The same note applies to longitude, which defaults to East.
The gmt_offset parameter is specified in hours.
Tabella 1. format constants
constant | description | example |
---|---|---|
SUNFUNCS_RET_STRING | returns the result as string | 16:46 |
SUNFUNCS_RET_DOUBLE | returns the result as float | 16.78243132 |
SUNFUNCS_RET_TIMESTAMP | returns the result as integer (timestamp) | 1095034606 |
Esempio 1. date_sunset() example
Il precedente esempio visualizzerà qualcosa simile a:
|
See also date_sunrise().
Restituisce una stringa formattata in accordo con il formato della stringa usato nell' intero timestamp o nell'attuale orario locale se timestamp non è assegnato.
Nota: Il valido intervallo del timestamp è abitualmente da Fri, 13 Dec 1901 20:45:54 GMT a Tue, 19 Jan 2038 03:14:07 GMT. (Queste date corrispondono al valore minimo e al massimo per un intero segnato a 32-bit.)
Per generare un timestamp da una stringa rappresentante la data, devi sapere usare strtotime(). In aggiunta, dei databases hanno funzioni che convertono i loro formati di data in timestamps (come la funzione di MySQL, UNIX_TIMESTAMP).
I seguenti caratteri sono utilizzati nella stringa formato:
a - "am" o "pm"
A - "AM" o "PM"
B - Swatch Internet time
d - giorno del mese, 2 cifre senza tralasciare gli zero; i.e. "01" a "31"
D - giorno della settimana, testuale, 3 lettere; i.e. "Fri"
F - mese, testuale, long; i.e. "January"
g - ora, formato a 12-ore senza eventuali zero; i.e. "1" a "12"
G - ora, formato a 24-ore senza eventuali zero; i.e. "0" a "23"
h - ora, formato a 12-ore; i.e. "01" a "12"
H - ora, formato a 24-ore; i.e. "00" a "23"
i - minuti; i.e. "00" a "59"
I (i grande) - "1" se c'è l'ora legale, "0" altrimenti.
j - giorno del mese senza eventuali zero; i.e. "1" a "31"
l ('L' piccola) - giorno della settimana, testuale, long; i.e. "Friday"
L - valore booleano per stabilire se è un anno bisestile; i.e. "0" o "1"
m - mese; i.e. "01" a "12"
M - mese, testuale, 3 lettere; i.e. "Jan"
n - mese senza eventuali zero; i.e. "1" a "12"
O - Differenza in ore dal fuso orario Greenwich; i.e. "+0200"
r - Data formattata RFC 822; i.e. "Thu, 21 Dec 2000 16:01:07 +0200" (aggiunto nel PHP 4.0.4)
s - secondi; i.e. "00" a "59"
S - Suffisso ordinale Inglese per i giorni del mese, 2 caratteri; i.e. "th", "nd"
t - numero di giorni del mese dato; i.e. "28" a "31"
T - Fuso orario di questo computer; i.e. "MDT"
U - secondi dall'epoca since the epoch
w - giorno della settimana, numerico, i.e. "0" (Domenica) a "6" (Sabato)
W - ISO-8601 Numero della settimana dell'anno, le settimane iniziano il lunedì (aggiunto in PHP 4.1.0) (Sabato)
Y - anno, 4 cifre; i.e. "1999"
y - anno, 2 cifre; i.e. "99"
z - giorno dell'anno; i.e. "0" a "365"
Z - Fuso orario in secondi (i.e. "-43200" a "43200"). Il fuso orario ad ovest dell'UTC è sempre negativo, e per quelli ad est è sempre positivo.
Puoi utilizzare un carattere utilizzabile nella stringa del formato come carattere normale facendolo semplicemente precedere dal carattere di escape, il backslash. Se il carattere con un backslash è ancora una sequenza speciale, devi inserire di nuovo il carattere di escape per il backslash.
È possibile usare date() e mktime() assieme per cercare delle date nel futuro o nel passato.
Esempio 3. Esempio di date() e mktime()
|
Nota: Questo può essere più affidabile della semplice addizione e sottrazione del numero di secondi in un giorno o mese a un timestamp a causa del daylight savings time.
Alcuni esempi della formattazione di date(). Nota che puoi scrivere qualsiasi altro carattere senza escape, il quale attualmente non dovrebbe produrre risultati indesiderati, ma altri caratteri potrebbero essere assegnati come caratteri della stringa di formattazione nelle prossime versioni del PHP. Quando si utilizza il carattere di escape, assicurati di usare un singolo apice per prevenire che caratteri come \n facciano iniziare una nuova linea.
Esempio 4. Formattazione con date()
|
Per formattare le date in lingue diverse dall'inglese, dovresti usare le funzioni setlocale() e strftime().
Guarda anche getlastmod(), gmdate(), mktime(), strftime() e time().
Restituisce un array associativo contenente le informazioni sulla data del timestamp, o dell'attuale orario locale se non è stato assegnato timestamp, con i seguenti elementi di array:
"seconds" - secondi
"minutes" - minuti
"hours" - ore
"mday" - giorno del mese
"wday" - giorno della settimana, numerico : da 0 come Domenica a 6 come Sabato
"mon" - mese, numerico
"year" - anno, numerico
"yday" - giorno dell'anno, numerico; i.e. "299"
"weekday" - giorno della settimana, testuale, per intero; i.e. "Friday"
"month" - mese, testuale, per intero; i.e. "January"
Questa è un'interfaccia di gettimeofday(2). Restituisce un array associativo contenente i dati restituiti dalla chiamata al sistema.
"sec" - secondi
"usec" - microsecondi
"minuteswest" - minuti ovest di Greenwich
"dsttime" - tipo di correzione dell'ora legale
Identica alla funzione date() eccetto per il fatto che l'orario restituito è del Greenwich Mean Time (GMT). Per esempio, quando si è in Finlandia (GMT +0200), la prima linea sotto scrive "Jan 01 1998 00:00:00", mentre la seconda scrive "Dec 31 1997 22:00:00".
Guarda anche date(), mktime(), gmmktime() e strftime().
Identica alla funzione mktime() eccetto per il paramentro passato, che rappresenta una data GMT.
(PHP 3 >= 3.0.12, PHP 4, PHP 5)
gmstrftime -- Formatta una data/ora GMT/UTC secondo i parametri localiSi comporta allo stesso modo della funzione strftime() eccetto che l'orario restituito è del Greenwich Mean Time (GMT). Ad esempio, quando si è nell' Eastern Standard Time (GMT -0500), la prima linea sotto scrive "Dec 31 1998 20:00:00", mentre la seconda scrive "Jan 01 1999 01:00:00".
Guarda anche strftime().
Returns a number formatted according to the given format string using the given integer timestamp or the current local time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().
Unlike the function date(), idate() accepts just one char in the format parameter.
Tabella 1. The following characters are recognized in the format parameter string
format character | Description |
---|---|
B | Swatch Beat/Internet Time |
d | Day of the month |
h | Hour (12 hour format) |
H | Hour (24 hour format) |
i | Minutes |
I | returns 1 if DST is activated, 0 otherwise |
L | returns 1 for leap year, 0 otherwise |
m | Month number |
s | Seconds |
t | Days in current month |
U | Seconds since the Unix Epoch - January 1 1970 00:00:00 GMT - this is the same as time() |
w | Day of the week (0 on Sunday) |
W | ISO-8601 week number of year, weeks starting on Monday |
y | Year (1 or 2 digits - check note below) |
Y | Year (4 digits) |
z | Day of the year |
Z | Timezone offset in seconds |
Nota: As idate() returns always an integer and as they can't start with a "0", idate() may return less digits then you would expect. See the example below:
La funzione localtime() restituisce un array identico a quello della struttura della chimata della funzione di C. Il primo argomento per localtime() è il timestamp, se non esiste viene assegnato di default l'orario attuale. Il secondo argomento di localtime() è is_associative, se questo è settato a 0 o non sostituito l'array restituirà un regolare array numerico indicizzato. Se l'argomento è settato a 1, localtime() è un array associativo contenente tutti gli elementi differenti della struttura restituita dalla funzione chiamata localtime di C. Il nome delle differenti chiavi dell'array associativo sono le seguenti:
"tm_sec" - secondi
"tm_min" - minuti
"tm_hour" - ora
"tm_mday" - giorno del mese
"tm_mon" - mese dell'anno, iniziando con 0 per Gennaio
"tm_year" - Anni dal 1900
"tm_wday" - Giorno della settimana
"tm_yday" - Giorno dell'anno
"tm_isdst" - Se l'ora legale è effettiva
Restituisce la stringa "msec sec" dove sec è l'attuale orario misurato nel numero di secondi dalla Unix Epoch (0:00:00 January 1, 1970 GMT), e msec è la parte in microsecondi. Questa funzione è disponibile solo su sistemi operativi che supportano la chiamata di sistema gettimeofday().
Entrambi le parti della stringa sono restituite in unità di secondi.
Esempio 1. Esempio di microtime()
|
Vedere anche time().
Attenzione: Nota lo strano ordine degli argomenti, che differiscono dal normale ordine degli argomenti in una normale chiamata UNIX mktime() e che non si presta bene a far comparire i parametri da destra a sinistra (guarda sotto). E' un comune errore la confusione di questi argomenti in uno script.
Restituisce la Unix timestamp corrispondente all'argomento dato. Questa timestamp è un intero lungo contenente il numero di secondi tra la Unix Epoch (January 1 1970) e la data e orario specificati.
Gli argomenti possono essere omessi nell'ordine da destra a sinistra; degli argomenti omessi saranno impostati con l'attuale valore accordandolo alla data e orario locale.
is_dst può essere impostato su 1 se l'orario è nell'ora legale, 0 altrimenti, o -1 (di default) se è sconosciuta la presenza dell'ora legale o meno. Se è sconosciuto, il PHP proverà ad impostarlo da se. Questo può causare un risultato non aspettato (ma non sbagliato).
Nota: is_dst è stato aggiunto nella verisone 3.0.10.
mktime() è usata per fare calcoli tra date e validazioni, come può calcolare automaticamente il corretto valore per un valore fuori dall'intervallo valido. Per esempio, ognuna delle seguenti linee produce la stringa "Jan-01-1998".
L'ultimo giorno del mese dato può essere espresso come il giorno "0" del mese successivo, non come il giorno -1. Entrami i seguenti esempi produrranno la stringa "L'ultimo giorno di Feb 2000 è: 29".
Date con anno, mese e giorno uguali a 0 non sono considerate valide (altrimenti saranno considerate come 30.11.1999, quando hanno uno strano behavior).
(PHP 3, PHP 4, PHP 5)
strftime -- Formatta una data/orario locale accordandola/o alle impostazioni locali according to locale settingsRestituisce una stringa formattata in accordo con la stringa del formato data usando il parametro dato timestamp o l'attuale orario locale se non è stato dato il timestamp. I nomi di mesi e giorni della settimana e le altre stringhe dipendenti dalla lingua rispettano le attuali impostazioni locali con setlocale().
Le seguenti sequenze di caratteri sono utilizzate nella stringa del formato:
%a - Nome del giorno della settimana abbreviato in accordo con i parametri locali
%A - Nome completo del giorno della settimana in accordo con i parametri locali
%b - Nome del mese abbreviato in accordo con i parametri locali
%B - Nome completo del mese in accordo con i parametri locali
%c - Rappresentazione preferita di data e orario per le attuali impostazioni locali
%C - numero del secolo (l'anno diviso 100 e troncato in un intero, intervallo tra 00 e 99)
%d - giorno del mese come numero decimale (intervallo tra 01 e 31)
%D - come %m/%d/%y
%e - giorno del mese come numero decimale, un singolo carattere è preceduto da uno spapzio (intervallo tra ' 1' e '31')
%g - come %G, ma senza il secolo.
%G - L'anno a 4 cifre corrispondente al numero di setitmana ISO (vedi %V). Questa ha lo stesso formato e valore di %Y, eccetto che se il numero di settimana ISO appartiene al precedente o prossimo anno, è invece utilizzato l'anno attuale.
%h - come %b
%H - ora come numero decimale usando il sistema a 24 ore (intervallo tra 00 e 23)
%I - ora come numero decimale usando il sistema a 12 ore (intervallo tra 01 e 12)
%j - giorno dell'anno come numero decimale (intervallo tra 001 e 366)
%m - mese come numero decimale (intervallo tra 01 e 12)
%M - minuto come numero decimale
%n - carattere di nuova linea
%p - entrambi `am' o `pm' accordati a un valore di tempo dato, o alle stringhe corrispondenti per le impostazioni locali
%r - orario in notazione a.m. e p.m
%R - orario nella notazione a 24 ore
%S - secondi come numero decimale
%t - Carattere di tabella
%T - orario attuale, identico a %H:%M:%S
%u - giorno della settimana come numero decimale [1,7], dove 1 rappresenta il Lunedì
Avvertimento |
Sun Solaris sembra far iniziare con la Domenica a come 1 sebbe la ISO 9889:1999 (l'attuale standard di C) specifica chiaramente che dovrebbe iniziare dal Lunedì. |
%U - numero della settimana dell'anno in corso come numero decimale, iniziando dalla prima Domenica come primo giorno della prima settimana
%V - Il numero di settimana ISO 8601:1988 dell'anno attuale come numero decimale, intervallo tra 01 e 53, dove la settimana 1 è la prima settimana che ha almeno 4 giorni dell'attuale anno, e con il Lunedì come primo giorno della settimana. (Utilizza %G o %g per l'anno componente che corrisponde al numero di settimana per il timestamp specificato.)
%W - numero della settimana dell'attuale anno come numero decimale, partendo con il primo Lunedì come primo giorno della prima settimana
%w - giorno della settimana come decimale, dove la Domenica è 0
%x - visualizzazione della data preferita dalle impostazioni del sistema locale senza orario
%X - visualizzazione dell'orario preferito dalle impostazioni del sistema locale senza data
%y - anno come numero decimale senza secolo (intervallo tra 00 e 99)
%Y - anno come numero decimale incluso il secolo
%Z - fuso orario o abbreviazione
%% - il carattere `%'
Nota: Non tutte le sequenze di caratteri potrebbero essere supportate dalla tua libreria locale di C, in tal caso la funzione strftime() non sarà supportata dal PHP. Questo significa che %T e %D non funzioneranno sotto Windows.
Guarda anche setlocale() e mktime() e le specifiche dell' Open Group per strftime().
strptime() returns an array with the date parsed, or FALSE on error.
Month and weekday names and other language dependent strings respect the current locale set with setlocale() (LC_TIME).
Nota: Questa funzione non è implementata su piattaforme Windows
The string to parse (e.g. returned from strftime())
The format used in date (e.g. the same as used in strftime()).
For more information about the format options, read the strftime() page.
Returns an array, or FALSE on failure.
Tabella 1. The following parameters are returned in the array
parameters | Description |
---|---|
tm_sec | Seconds after the minute (0-61) |
tm_min | Minutes after the hour (0-59) |
tm_hour | Hour since midnight (0-23) |
tm_mday | Day of the month (1-31) |
tm_mon | Months since January (0-11) |
tm_year | Years since 1900 |
tm_wday | Days since Sunday (0-6) |
tm_yday | Days since January 1 (0-365) |
unparsed | the date part which was not recognized using the specified format |
Esempio 1. strptime() example
Il precedente esempio visualizzerà qualcosa simile a:
|
(PHP 3 >= 3.0.12, PHP 4, PHP 5)
strtotime -- Analizza le descrizioni testuali di datetime in Inglese nell'UNIX timestampLa funzione aspetta di avere una stringa contenente un formato di data in Inglese e proverà a passare questo formato all'UNIX timestamp relativo al timestamp dato in now, o l'attuale orario se non è stato passato il parametro. Sul fallimento, è restituito -1.
Perché strtotime() si comporti in accordo con la sintassi della data GNU, dai uno sguardo alla pagina del manuale GNU intitolata Date Input Formats. Descrive se c'è una sinstassi valida per il parametro time.
Esempio 1. strtotime() - esempi
|
Nota: L'intervallo valido di un timestamp è normalmente da Fri, 13 Dec 1901 20:45:54 GMT a Tue, 19 Jan 2038 03:14:07 GMT. (Queste sono le date ce corrispondono al minimo e al massimo valore per un intero segnato a 32 bit.)
Restituisce l'attuale data e orario misurata in numero di secondi dalla Unix Epoch (January 1 1970 00:00:00 GMT).
Guarda anche date().
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
db++, made by the German company Concept asa, is a relational database system with high performance and low memory and disk usage in mind. While providing SQL as an additional language interface, it is not really a SQL database in the first place but provides its own AQL query language which is much more influenced by the relational algebra then SQL is.
Concept asa always had an interest in supporting open source languages, db++ has had Perl and Tcl call interfaces for years now and uses Tcl as its internal stored procedure language.
This extension relies on external client libraries so you have to have a db++ client installed on the system you want to use this extension on.
Concept asa provides db++ Demo versions and documentation for Linux, some other Unix versions. There is also a Windows version of db++, but this extension doesn't support it (yet).
In order to build this extension yourself you need the db++ client libraries and header files to be installed on your system (these are included in the db++ installation archives by default). You have to run configure with option --with-dbplus to build this extension.
configure looks for the client libraries and header files under the default paths /usr/dbplus, /usr/local/dbplus and /opt/dblus. If you have installed db++ in a different place you have add the installation path to the configure option like this: --with-dbplus=/your/installation/path.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Most db++ functions operate on or return dbplus_relation resources. A dbplus_relation is a handle to a stored relation or a relation generated as the result of a query.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 1. DB++ Error Codes
PHP Constant | db++ constant | meaning |
---|---|---|
DBPLUS_ERR_NOERR (integer) | ERR_NOERR | Null error condition |
DBPLUS_ERR_DUPLICATE (integer) | ERR_DUPLICATE | Tried to insert a duplicate tuple |
DBPLUS_ERR_EOSCAN (integer) | ERR_EOSCAN | End of scan from rget() |
DBPLUS_ERR_EMPTY (integer) | ERR_EMPTY | Relation is empty (server) |
DBPLUS_ERR_CLOSE (integer) | ERR_CLOSE | The server can't close |
DBPLUS_ERR_WLOCKED (integer) | ERR_WLOCKED | The record is write locked |
DBPLUS_ERR_LOCKED (integer) | ERR_LOCKED | Relation was already locked |
DBPLUS_ERR_NOLOCK (integer) | ERR_NOLOCK | Relation cannot be locked |
DBPLUS_ERR_READ (integer) | ERR_READ | Read error on relation |
DBPLUS_ERR_WRITE (integer) | ERR_WRITE | Write error on relation |
DBPLUS_ERR_CREATE (integer) | ERR_CREATE | Create() system call failed |
DBPLUS_ERR_LSEEK (integer) | ERR_LSEEK | Lseek() system call failed |
DBPLUS_ERR_LENGTH (integer) | ERR_LENGTH | Tuple exceeds maximum length |
DBPLUS_ERR_OPEN (integer) | ERR_OPEN | Open() system call failed |
DBPLUS_ERR_WOPEN (integer) | ERR_WOPEN | Relation already opened for writing |
DBPLUS_ERR_MAGIC (integer) | ERR_MAGIC | File is not a relation |
DBPLUS_ERR_VERSION (integer) | ERR_VERSION | File is a very old relation |
DBPLUS_ERR_PGSIZE (integer) | ERR_PGSIZE | Relation uses a different page size |
DBPLUS_ERR_CRC (integer) | ERR_CRC | Invalid crc in the superpage |
DBPLUS_ERR_PIPE (integer) | ERR_PIPE | Piped relation requires lseek() |
DBPLUS_ERR_NIDX (integer) | ERR_NIDX | Too many secondary indices |
DBPLUS_ERR_MALLOC (integer) | ERR_MALLOC | Malloc() call failed |
DBPLUS_ERR_NUSERS (integer) | ERR_NUSERS | Error use of max users |
DBPLUS_ERR_PREEXIT (integer) | ERR_PREEXIT | Caused by invalid usage |
DBPLUS_ERR_ONTRAP (integer) | ERR_ONTRAP | Caused by a signal |
DBPLUS_ERR_PREPROC (integer) | ERR_PREPROC | Error in the preprocessor |
DBPLUS_ERR_DBPARSE (integer) | ERR_DBPARSE | Error in the parser |
DBPLUS_ERR_DBRUNERR (integer) | ERR_DBRUNERR | Run error in db |
DBPLUS_ERR_DBPREEXIT (integer) | ERR_DBPREEXIT | Exit condition caused by prexit() * procedure |
DBPLUS_ERR_WAIT (integer) | ERR_WAIT | Wait a little (Simple only) |
DBPLUS_ERR_CORRUPT_TUPLE (integer) | ERR_CORRUPT_TUPLE | A client sent a corrupt tuple |
DBPLUS_ERR_WARNING0 (integer) | ERR_WARNING0 | The Simple routines encountered a non fatal error which was corrected |
DBPLUS_ERR_PANIC (integer) | ERR_PANIC | The server should not really die but after a disaster send ERR_PANIC to all its clients |
DBPLUS_ERR_FIFO (integer) | ERR_FIFO | Can't create a fifo |
DBPLUS_ERR_PERM (integer) | ERR_PERM | Permission denied |
DBPLUS_ERR_TCL (integer) | ERR_TCL | TCL_error |
DBPLUS_ERR_RESTRICTED (integer) | ERR_RESTRICTED | Only two users |
DBPLUS_ERR_USER (integer) | ERR_USER | An error in the use of the library by an application programmer |
DBPLUS_ERR_UNKNOWN (integer) | ERR_UNKNOWN |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
This function will add a tuple to a relation. The tuple data is an array of attribute/value pairs to be inserted into the given relation. After successful execution the tuple array will contain the complete data of the newly created tuple, including all implicitly set domain fields like sequences.
The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_aql() will execute an AQL query on the given server and dbpath.
On success it will return a relation handle. The result data may be fetched from this relation by calling dbplus_next() and dbplus_current(). Other relation access functions will not work on a result relation.
Further information on the AQL A... Query Language is provided in the original db++ manual.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_chdir() will change the virtual current directory where relation files will be looked for by dbplus_open(). dbplus_chdir() will return the absolute path of the current directory. Calling dbplus_chdir() without giving any newdir may be used to query the current working directory.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Calling dbplus_close() will close a relation previously opened by dbplus_open().
Returns TRUE on success or DBPLUS_ERR_UNKNOWN on failure.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_curr() will read the data for the current tuple for the given relation and will pass it back as an associative array in tuple.
The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.
See also dbplus_first(), dbplus_prev(), dbplus_next(), and dbplus_last().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_errcode() returns a cleartext error string for the error code passed as errno of for the result code of the last db++ operation if no parameter is given.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_errno() will return the error code returned by the last db++ operation.
See also dbplus_errcode().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_find() will place a constraint on the given relation. Further calls to functions like dbplus_curr() or dbplus_next() will only return tuples matching the given constraints.
Constraints are triplets of strings containing of a domain name, a comparison operator and a comparison value. The constraints parameter array may consist of a collection of string arrays, each of which contains a domain, an operator and a value, or of a single string array containing a multiple of three elements.
The comparison operator may be one of the following strings: '==', '>', '>=', '<', '<=', '!=', '~' for a regular expression match and 'BAND' or 'BOR' for bitwise operations.
See also dbplus_unselect().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_curr() will read the data for the first tuple for the given relation, make it the current tuple and pass it back as an associative array in tuple.
The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.
See also dbplus_curr(), dbplus_prev(), dbplus_next(), and dbplus_last().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_flush() will write all changes applied to relation since the last flush to disk.
The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_freealllocks() will free all tuple locks held by this client.
See also dbplus_getlock(), dbplus_freelock(), and dbplus_freerlocks().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_freelock() will release a write lock on the given tuple previously obtained by dbplus_getlock().
See also dbplus_getlock(), dbplus_freerlocks(), and dbplus_freealllocks().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_freerlocks() will free all tuple locks held on the given relation.
See also dbplus_getlock(), dbplus_freelock(), and dbplus_freealllocks().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_getlock() will request a write lock on the specified tuple. It will return zero on success or a non-zero error code, especially DBPLUS_ERR_WLOCKED, on failure.
See also dbplus_freelock(), dbplus_freerlocks(), and dbplus_freealllocks().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_getunique() will obtain a number guaranteed to be unique for the given relation and will pass it back in the variable given as uniqueid.
The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_curr() will read the data for the last tuple for the given relation, make it the current tuple and pass it back as an associative array in tuple.
The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.
See also dbplus_first(), dbplus_curr(), dbplus_prev(), and dbplus_next().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_lockrel() will request a write lock on the given relation. Other clients may still query the relation, but can't alter it while it is locked.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_curr() will read the data for the next tuple for the given relation, will make it the current tuple and will pass it back as an associative array in tuple.
The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.
See also dbplus_first(), dbplus_curr(), dbplus_prev(), and dbplus_last().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The relation file name will be opened. name can be either a file name or a relative or absolute path name. This will be mapped in any case to an absolute relation file path on a specific host machine and server.
On success a relation file resource (cursor) is returned which must be used in any subsequent commands referencing the relation. Failure leads to a zero return value, the actual error code may be asked for by calling dbplus_errno().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_curr() will read the data for the previous tuple for the given relation, will make it the current tuple and will pass it back as an associative array in tuple.
The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure. See dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.
See also dbplus_first(), dbplus_curr(), dbplus_next(), and dbplus_last().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_rchperm() will change access permissions as specified by mask, user and group. The values for these are operating system specific.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_rcreate() will create a new relation named name. An existing relation by the same name will only be overwritten if the relation is currently not in use and overwrite is set to TRUE.
domlist should contain the domain specification for the new relation within an array of domain description strings. ( dbplus_rcreate() will also accept a string with space delimited domain description strings, but it is recommended to use an array). A domain description string consists of a domain name unique to this relation, a slash and a type specification character. See the db++ documentation, especially the dbcreate(1) manpage, for a description of available type specifiers and their meanings.
(4.1.0 - 4.2.3 only, PECL)
dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indicesAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_rcrtexact() will create an exact but empty copy of the given relation under a new name. An existing relation by the same name will only be overwritten if overwrite is TRUE and no other process is currently using the relation.
Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.
(4.1.0 - 4.2.3 only, PECL)
dbplus_rcrtlike -- Creates an empty copy of a relation with default indicesAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_rcrtexact() will create an empty copy of the given relation under a new name, but with default indices. An existing relation by the same name will only be overwritten if overwrite is TRUE and no other process is currently using the relation.
Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_resolve() will try to resolve the given relation_name and find out internal server id, real hostname and the database path on this host. The function will return an array containing these values under the keys 'sid', 'host' and 'host_path' or FALSE on error.
See also dbplus_tcl().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_rkeys() will replace the current primary key for relation with the combination of domains specified by domlist.
domlist may be passed as a single domain name string or as an array of domain names.
Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_ropen() will open the relation file locally for quick access without any client/server overhead. Access is read only and only dbplus_current() and dbplus_next() may be applied to the returned relation.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_rquery() performs a local (raw) AQL query using an AQL interpreter embedded into the db++ client library. dbplus_rquery() is faster than dbplus_aql() but will work on local data only.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_rrename() will change the name of relation to name.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_rsecindex() will create a new secondary index for relation with consists of the domains specified by domlist and is of type type
domlist may be passed as a single domain name string or as an array of domain names.
Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_unlink() will close and remove the relation.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_rzap() will remove all tuples from relation.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
A db++ server will prepare a TCL interpreter for each client connection. This interpreter will enable the server to execute TCL code provided by the client as a sort of stored procedures to improve the performance of database operations by avoiding client/server data transfers and context switches.
dbplus_tcl() needs to pass the client connection id the TCL script code should be executed by. dbplus_resolve() will provide this connection id. The function will return whatever the TCL code returns or a TCL error message if the TCL code fails.
See also dbplus_resolve().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_tremove() removes tuple from relation if it perfectly matches a tuple within the relation. current, if given, will contain the data of the new current tuple after calling dbplus_tremove().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_unlockrel() will release a write lock previously obtained by dbplus_lockrel().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Calling dbplus_unselect() will remove a constraint previously set by dbplus_find() on relation.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_update() replaces the tuple given by old with the data from new if and only if old completely matches a tuple within relation.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_xlockrel() will request an exclusive lock on relation preventing even read access from other clients.
See also dbplus_xunlockrel().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_xunlockrel() will release an exclusive lock on relation previously obtained by dbplus_xlockrel().
These functions build the foundation for accessing Berkeley DB style databases.
This is a general abstraction layer for several file-based databases. As such, functionality is limited to a common subset of features supported by modern databases such as Sleepycat Software's DB2. (This is not to be confused with IBM's DB2 software, which is supported through the ODBC functions.)
The behaviour of various aspects depends on the implementation of the underlying database. Functions such as dba_optimize() and dba_sync() will do what they promise for one database and will do nothing for others. You have to download and install supported dba-Handlers.
Tabella 1. List of DBA handlers
Handler | Notes |
---|---|
dbm | Dbm is the oldest (original) type of Berkeley DB style databases. You should avoid it, if possible. We do not support the compatibility functions built into DB2 and gdbm, because they are only compatible on the source code level, but cannot handle the original dbm format. |
ndbm | Ndbm is a newer type and more flexible than dbm. It still has most of the arbitrary limits of dbm (therefore it is deprecated). |
gdbm | Gdbm is the GNU database manager. |
db2 | DB2 is Sleepycat Software's DB2. It is described as "a programmatic toolkit that provides high-performance built-in database support for both standalone and client/server applications. |
db3 | DB3 is Sleepycat Software's DB3. |
db4 | DB4 is Sleepycat Software's DB4. This is available since PHP 4.3.2. |
cdb | Cdb is "a fast, reliable, lightweight package for creating and reading constant databases." It is from the author of qmail and can be found at http://cr.yp.to/cdb.html. Since it is constant, we support only reading operations. And since PHP 4.3.0 we support writing (not updating) through the internal cdb library. |
cdb_make | Since PHP 4.3.0 we support creation (not updating) of cdb files when the bundled cdb library is used. |
flatfile | This is available since PHP 4.3.0 for compatibility with the deprecated dbm extension only and should be avoided. However you may use this where files were created in this format. That happens when configure could not find any external library. |
inifile | This is available since PHP 4.3.3 to be able to modify php.ini files from within PHP scripts. When working with ini files you can pass arrays of the form array(0=>group,1=>value_name) or strings of the form "[group]value_name" where group is optional. As the functions dba_firstkey() and dba_nextkey() return string representations of the key there is a new function dba_key_split() available since PHP 5 which allows to convert the string keys into array keys without loosing FALSE. |
qdbm | This is available since PHP 5.0.0. The qdbm library can be loaded from http://qdbm.sourceforge.net. |
When invoking the dba_open() or dba_popen() functions, one of the handler names must be supplied as an argument. The actually available list of handlers is displayed by invoking phpinfo() or dba_handlers().
By using the --enable-dba=shared configuration option you can build a dynamic loadable module to enable PHP for basic support of dbm-style databases. You also have to add support for at least one of the following handlers by specifying the --with-XXXX configure switch to your PHP configure line.
Avvertimento |
After configuring and compiling PHP you must execute the following test from commandline: php run-tests.php ext/dba. This shows whether your combination of handlers works. Most problematic are dbm and ndbm which conflict with many installations. The reason for this is that on several systems these libraries are part of more than one other library. The configuration test only prevents you from configuring malfaunctioning single handlers but not combinations. |
Tabella 2. Supported DBA handlers
Handler | Configure Switch |
---|---|
dbm |
To enable support for dbm add
--with-dbm[=DIR].
|
ndbm |
To enable support for ndbm add
--with-ndbm[=DIR].
|
gdbm | To enable support for gdbm add --with-gdbm[=DIR]. |
db2 |
To enable support for db2 add
--with-db2[=DIR].
|
db3 |
To enable support for db3 add
--with-db3[=DIR].
|
db4 |
To enable support for db4 add
--with-db4[=DIR].
|
cdb |
To enable support for cdb add
--with-cdb[=DIR].
|
flatfile |
To enable support for flatfile add
--with-flatfile.
|
inifile |
To enable support for inifile add
--with-inifile.
|
qdbm |
To enable support for qdbm add
--with-qdbm[=DIR].
|
Nota: Up to PHP 4.3.0 you are able to add both db2 and db3 handler but only one of them can be used internally. That means that you cannot have both file formats. Starting with PHP 5.0.0 there is a configuration check avoid such misconfigurations.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
The functions dba_open() and dba_popen() return a handle to the specified database file to access which is used by all other dba-function calls.
DBA is binary safe and does not have any arbitrary limits. However, it inherits all limits set by the underlying database implementation.
All file-based databases must provide a way of setting the file mode of a new created database, if that is possible at all. The file mode is commonly passed as the fourth argument to dba_open() or dba_popen().
You can access all entries of a database in a linear way by using the dba_firstkey() and dba_nextkey() functions. You may not change the database while traversing it.
dba_close() closes the established database and frees all resources of the specified database handle.
dba_delete() deletes the specified entry from the database.
The key of the entry which is deleted.
The database handler, returned by dba_open() or dba_popen().
dba_exists() checks whether the specified key exists in the database.
The key the check is performed for.
The database handler, returned by dba_open() or dba_popen().
dba_fetch() fetches the data specified by key from the database specified with handle.
The key the data is specified by.
Nota: When working with inifiles this function accepts arrays as keys where index 0 is the group and index 1 is the value name. See: dba_key_split().
The number of key-value pairs to ignore when using cdb databases. This value is ignored for all other databases which do not support multiple keys with the same name.
The database handler, returned by dba_open() or dba_popen().
dba_firstkey() returns the first key of the database and resets the internal key pointer. This permits a linear search through the whole database.
dba_handlers() list all the handlers supported by this extension.
Turns on/off full information display in the result. The default is FALSE.
Returns an array of database handlers. If full_info is set to TRUE, the array will be associative with the handlers names as keys, and their version information as value. Otherwise, the result will be an indexed array of handlers names.
Nota: When the internal cdb library is used you will see cdb and cdb_make.
Esempio 1. dba_handlers() Example
Il precedente esempio visualizzerà qualcosa simile a:
|
dba_insert() inserts the entry described with key and value into the database.
The key of the entry to be inserted. If this key already exist in the database, this function will fail. Use dba_replace() if you need to replace an existent key.
The value to be inserted.
The database handler, returned by dba_open() or dba_popen().
dba_key_split() splits a key (string representation) into an array representation.
Returns an array of the form array(0 => group, 1 => value_name). This function will return FALSE if key is NULL or FALSE.
dba_nextkey() returns the next key of the database and advances the internal key pointer.
dba_open() establishes a database instance for path with mode using handler.
Commonly a regular path in your filesystem.
It is r for read access, w for read/write access to an already existing database, c for read/write access and database creation if it doesn't currently exist, and n for create, truncate and read/write access.
Additionally you can set the database lock method with the next char. Use l to lock the database with a .lck file or d to lock the databasefile itself. It is important that all of your applications do this consistently.
If you want to test the access and do not want to wait for the lock you can add t as third character. When you are absolutely sure that you do not require database locking you can do so by using - instead of l or d. When none of d, l or - is used, dba will lock on the database file as it would with d.
Nota: There can only be one writer for one database file. When you use dba on a webserver and more than one request requires write operations they can only be done one after another. Also read during write is not allowed. The dba extension uses locks to prevent this. See the following table:
Tabella 1. DBA locking
already open mode = "rl" mode = "rlt" mode = "wl" mode = "wlt" mode = "rd" mode = "rdt" mode = "wd" mode = "wdt" not open ok ok ok ok ok ok ok ok mode = "rl" ok ok wait false illegal illegal illegal illegal mode = "wl" wait false wait false illegal illegal illegal illegal mode = "rd" illegal illegal illegal illegal ok ok wait false mode = "wd" illegal illegal illegal illegal wait false wait false
ok: the second call will be successfull. wait: the second call waits until dba_close() is called for the first. false: the second call returns false. illegal: you must not mix "l" and "d" modifiers for mode parameter.
The name of the handler which shall be used for accessing path. It is passed all optional parameters given to dba_open() and can act on behalf of them.
Versione | Descrizione |
---|---|
4.3.0 | It's possible to open database files over network connection. However in cases a socket connection will be used (as with http or ftp) the connection will be locked instead of the resource itself. This is important to know since in such cases locking is simply ignored on the resource and other solutions have to be found. |
4.3.0 | Locking and the mode modifiers "l", "d", "-" and "t" were added. In previous PHP versions, you must use semaphores to guard against simultaneous database access for any database handler with the exception of GDBM. See System V semaphore support. |
before 4.3.5 | open mode 'c' is broken for several internal handlers and truncates the database instead of appending data to an existent database. Also dbm and ndbm fail on mode 'c' in typical configurations (this cannot be fixed). |
dba_popen() establishes a persistent database instance for path with mode using handler.
Commonly a regular path in your filesystem.
It is r for read access, w for read/write access to an already existing database, c for read/write access and database creation if it doesn't currently exist, and n for create, truncate and read/write access.
The name of the handler which shall be used for accessing path. It is passed all optional parameters given to dba_popen() and can act on behalf of them.
dba_replace() replaces or inserts the entry described with key and value into the database specified by handle.
The key of the entry to be replaced.
The value to be replaced.
The database handler, returned by dba_open() or dba_popen().
Queste funzioni consentono di accedere ai record memorizzati nei database in formato dBase (dbf).
Non è previsto il supporto per indici o campi memo. Manca anche il supporto per il locking. E' probabile che due processi concorrenti che modifichino lo stesso database, finiscano con il rovinare il Database.
I files dBase sono semplici files sequenziali o records a lunghezza fissa. I record sono aggiunti (append) alla fine del file e quelli cancellati sono conservati fino alla chiamata della funzione dbase_pack().
Si raccomanda di non usare i files dBase come database di lavoro. Scegliere piuttosto qualsiasi reale SQL server; MySQL o Postgres sono scelte comuni con PHP. Il supporto dBase è presente per permettervi di importare ed esportare dati da e verso il vostro web database, perchè il formato del file è comunemente ben interpretato dai fogli elettronici e dagli organizers di Windows.
Allo scopo di abilitare le librerie dbase fornite e di usare queste funzioni, si deve compilare PHP con l'opzione --enable-dbase .
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Aggiunge i dati nel record al database. Se il numero di items nel record non è uguale al numero di campi nel database, l'operazione fallirà e sarà restituito FALSE.
Chiude il database associato con il dbase_identifier.
dBase_create()crea un database dBase nel filefilename con i campifields
Il parametro fields è un array di arrays, ciascun array descrive il formato di un campo nel database. Ogni campo consiste di un nome, un carattere che indica il tipo di campo, una lunghezza, e una precisione.
I tipi di campo disponibili sono:
Boolean. Questi non hanno una lunghezza o una precisione.
Memo. (Nota che non sono supportati da PHP.) Questi non hanno una lunghezza o una precisione.
Date (memorizzate nel formato YYYYMMDD). Questi non hanno una lunghezza o una precisione.
Number. Questi hanno sia una lunghezza sia una precisione (il numero di decimali).
String.
Se il database è creato con successo, viene restituito un dbase_identifier, altrimenti viene restituito FALSE.
Esempio 1. Creare un file di database dBase
|
Marca il record da cancellare dal database. Per rimuovere il record dal database, è necessario chiamare la funzione dbase_pack().
Restituisce informazioni sulla struttura delle colonne del database referenziato da dbase_identifier. Per ogni colonna del database, esiste un valore specificato in un array ad indice numerico. L'indice dell'array inizia da 0. Ogni elemento dell'array contiene un array associativo di informazioni sulle colonne. Se l'informazione dell'header dell'array non può esssere letta, viene restituito, FALSE .
Gli elementi dell'array sono:
Il nome della colonna
Il nome del tipo di colonna del dBase riconoscibile dall'utente (es. data, boolean, etc)
Il numero di bytes che la colonna può contenere
Il numero di cifre della precisione decimale della colonna
Un formato di printf() suggerito, specifico per la colonna
L'offest, in byte, della colonna dall'inizio riga
Esempio 1. Mostra le informazioni dell'header di un file di database in formato dBase
|
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
dbase_get_record_with_names -- Estrae un record da un database dBase come un array associativoRestituisce i dati da record in un array associativo. L'array include anche un membro associativo chiamato 'deleted' che è settato a 1 se il record è stato marcato per la cancellazione (vedere dbase_delete_record()).
Ogni campo è convertito all'appropriato tipo PHP, Fanno eccezione:
Le date, che sono lasciate come stringhe.
Gli interi che avrebbero causato un overflow (> 32 bits) sono restituiti come stringhe.
Restituisce i dati da record in un array. L'array è indicizzato partendo da 0, e include un membro associativo chiamato 'deleted' che è settato a 1 se il record è stato marcato per la cancellazione (vedere dbase_delete_record()).
Ogni campo è convertito all'appropriato tipo PHP, Fanno eccezione:
Le date, che sono lasciate come stringhe.
Gli interi che avrebbero causato un overflow (> 32 bits) sono restituiti come stringhe.
Restituisce il numero di campi (colonne) nel databaase specificato. I numeri dei campi sono compresi tra 0 e dbase_numfields($db)-1, mentre i numeri dei records sono compresi tra 1 e dbase_numrecords($db).
Restituisce il numero di records (righe) nel database specificato. I numeri dei records sono compresi tra 1 e dbase_numrecords($db), mentre i numeri dei campi sono compresi tra 0 e dbase_numfields($db)-1.
Restituisce un dbase_identifier per il database aperto, o FALSE se il database non può essere aperto
I parametri flags corrispondono a quelli della system call open() (Tipicamente, "0" significa sola-lettura, "1" significa sola scrittura e "2" lettura-scrittura).
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Stabilizza il database specificato (cancellando permanentemente tutti i records marcati per la cancellazione usando dbase_delete_record()).
Sostituisce i dati associati con il record record_number con i dati nel record nel database. Se il numero di items nel record non è uguale al numero di campi nel database, l'operazione fallirà e sarà restituito FALSE.
dbase_record_number è un integer che va da 1 al numero di records nel database (come restituito da dbase_numrecords()).
Questa funzioni consentono lo storage di records memorizzati in un dbm-style database. Questo tipo di database (supportato da Berkeley DB, GDBM, e qualche libreria di sistema, così come una built-in flatfile library) memorizza coppie key/value (al contrario dei full-blown records supportati dai database relazionali).
Nota: Il supporto per dbm è deprecato e si incoraggia ad utilizzare Database (dbm-style) abstraction layer functions.
Per utilizzare queste funzioni occorre compilare il PHP con il supporto per un database sottostante. Vedere l'elenco dei database supoprtati.
Per potere utilizzare queste funzioni occorre compilare il PHP con il supporto dbm utilizzando l'opzione --with-db. Inoltre occorre garantire il supporto per il sottostante database oppure occorre utilizzare qualche libreria di sistema.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
La funzione dbmopen() restituisce un identificatore di database che può essere utilizzato con le altre funzioni dbm.
Cancella il valore per key nel database.
Restituisce FALSE se la chiave non esisteva nel database.
Restituisce TRUE se c'è un valore associato con la key.
Restituisce il valore associato con key.
Restituisce la prima chiave nel database. Da notare che nessun ordine particolare è garantito dal momento che il database potrebbe essere stato costruito usando una hash-table, che non garantisce nessun ordine.
Aggiunge il valore al database con la chiave specificata.
Restituisce -1 se il database è stato aperto in modalità read-only (sola lettura), 0 se l'inserimento è andato a buon fine, e 1 se la chiave specificata già esiste. (Per sostituire il valore, usa dbmreplace().)
Restituisce la chiave successiva dopo key. Chiamando la funzione dbmfirstkey() seguita da successive chiamate alla funzione dbmnextkey() è possibile visionare ciascuna coppia key/value nel database DBM. Per esempio:
Il primo argomento è il nome (con il percorso completo) del file DBM da aprire e il secondo è l' open mode del file che può essere "r", "n", "c" or "w" per sola lettura, nuovo (implica lettura-scrittura, e molto probabilmente troncherà un database esistente con lo stesso nome), crea (implica lettura-scrittura, e non troncherà un database esistente con lo stesso nome) e lettura-scrittura rispettivamente.
Restituisce un identifier da passare alle altre funzioni DBM in caso di successo, o FALSE se fallisce.
Se è usato il supporto NDBM, NDBM creerà i file filename.dir e filename.pag. GDBM usa solo un file, in quanto fa l' internal flat-file support, e il Berkeley DB crea un filename.db file. Da notare che PHP fa il suo file locking in aggiunta a quello che eventualmente potrebbe fare la stessa libreria DBM. PHP non cancella i files .lck che crea. Semplicemente usa questi files come fixed inodes su cui fare il file locking. Per maggiori informazioni sui files DBM, guarda le pagine del tuo manuale UNIX, o scarica GNU's GDBM.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
The dbx module is a database abstraction layer (db 'X', where 'X' is a supported database). The dbx functions allow you to access all supported databases using a single calling convention. The dbx-functions themselves do not interface directly to the databases, but interface to the modules that are used to support these databases.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.1.0.
To be able to use a database with the dbx-module, the module must be either linked or loaded into PHP, and the database module must be supported by the dbx-module. Currently, the following databases are supported, but others will follow:
FrontBase (available from PHP 4.1.0).
Sybase-CT (available from PHP 4.2.0).
Oracle (oci8) (available from PHP 4.3.0).
SQLite (PHP 5).
Documentation for adding additional database support to dbx can be found at http://www.guidance.nl/php/dbx/doc/.
In order to have these functions available, you must compile PHP with dbx support by using the --enable-dbx option and all options for the databases that will be used, e.g. for MySQL you must also specify --with-mysql=[DIR]. To get other supported databases to work with the dbx-module refer to their specific documentation.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. DBX Configuration Options
Name | Default | Changeable | Changelog |
---|---|---|---|
dbx.colnames_case | "unchanged" | PHP_INI_SYSTEM | Available since PHP 4.3.0. |
Breve descrizione dei parametri di configurazione.
Columns names can be returned "unchanged" or converted to "uppercase" or "lowercase". This directive can be overridden with a flag to dbx_query().
There are two resource types used in the dbx module. The first one is the link-object for a database connection, the second a result-object which holds the result of a query.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Always refer to the module-specific documentation as well.
See also dbx_connect().
dbx_compare() returns 0 if the row_a[$column_key] is equal to row_b[$column_key], and 1 or -1 if the former is greater or is smaller than the latter one, respectively, or vice versa if the flag is set to DBX_CMP_DESC. dbx_compare() is a helper function for dbx_sort() to ease the make and use of the custom sorting function.
The flags can be set to specify comparison direction:
DBX_CMP_ASC - ascending order
DBX_CMP_DESC - descending order
DBX_CMP_NATIVE - no type conversion
DBX_CMP_TEXT - compare items as strings
DBX_CMP_NUMBER - compare items numerically
Esempio 1. dbx_compare() example
|
See also dbx_sort().
dbx_connect() returns an object on success, FALSE on error. If a connection has been made but the database could not be selected, the connection is closed and FALSE is returned. The persistent parameter can be set to DBX_PERSISTENT, if so, a persistent connection will be created.
The module parameter can be either a string or a constant, though the latter form is preferred. The possible values are given below, but keep in mind that they only work if the module is actually loaded.
DBX_MYSQL or "mysql"
DBX_ODBC or "odbc"
DBX_PGSQL or "pgsql"
DBX_MSSQL or "mssql"
DBX_FBSQL or "fbsql" (available from PHP 4.1.0)
DBX_SYBASECT or "sybase_ct" (available from PHP 4.2.0)
DBX_OCI8 or "oci8" (available from PHP 4.3.0)
DBX_SQLITE or "sqlite" (PHP 5)
The host, database, username and password parameters are expected, but not always used depending on the connect functions for the abstracted module.
The returned object has three properties:
It is the name of the currently selected database.
It is a valid handle for the connected database, and as such it can be used in module-specific functions (if required).
It is used internally by dbx only, and is actually the module number mentioned above.
Nota: Always refer to the module-specific documentation as well.
See also dbx_close().
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)
dbx_error -- Report the error message of the latest function call in the module (not just in the connection)dbx_error() returns a string containing the error message from the last function call of the abstracted module (e.g. mysql module). If there are multiple connections in the same module, just the last error is given. If there are connections on different modules, the latest error is returned for the module specified by the link_identifier parameter.
Nota: Always refer to the module-specific documentation as well.
The error message for Microsoft SQL Server is actually the result of the mssql_get_last_message() function.
The error message for Oracle (oci8) is not implemented (yet).
(PHP 4 >= 4.3.0, PHP 5 <= 5.0.4)
dbx_escape_string -- Escape a string so it can safely be used in an sql-statementdbx_escape_string() returns the text, escaped where necessary (such as quotes, backslashes etc). It returns NULL on error.
Esempio 1. dbx_escape_string() example
|
See also dbx_query().
(PHP 5 <= 5.0.4)
dbx_fetch_row -- Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag setdbx_fetch_row() returns a row on success, and 0 on failure (e.g. when no more rows are available). When the DBX_RESULT_UNBUFFERED is not set in the query, dbx_fetch_row() will fail as all rows have already been fetched into the results data property.
As a side effect, the rows property of the query-result object is incremented for each successful call to dbx_fetch_row().
Esempio 1. How to handle the returned value
|
The result_identifier parameter is the result object returned by a call to dbx_query().
The returned object contains the same information as any row would have in the dbx_query result data property, including columns accessible by index or fieldname when the flags for dbx_guery were set that way.
See also dbx_query().
dbx_query() returns an object or 1 on success, and 0 on failure. The result object is returned only if the query given in sql_statement produces a result set (i.e. a SELECT query, even if the result set is empty).
Esempio 1. How to handle the returned value
|
The flags parameter is used to control the amount of information that is returned. It may be any combination of the following constants with the bitwise OR operator (|). The DBX_COLNAMES_* flags override the dbx.colnames_case setting from php.ini.
It is always set, that is, the returned object has a data property which is a 2 dimensional array indexed numerically. For example, in the expression data[2][3] 2 stands for the row (or record) number and 3 stands for the column (or field) number. The first row and column are indexed at 0.
If DBX_RESULT_ASSOC is also specified, the returning object contains the information related to DBX_RESULT_INFO too, even if it was not specified.
It provides info about columns, such as field names and field types.
It effects that the field values can be accessed with the respective column names used as keys to the returned object's data property.
Associated results are actually references to the numerically indexed data, so modifying data[0][0] causes that data[0]['field_name_for_first_column'] is modified as well.
This flag will not create the data property, and the rows property will initially be 0. Use this flag for large datasets, and use dbx_fetch_row() to retrieve the results row by row.
The dbx_fetch_row() function will return rows that are conformant to the flags set with this query. Incidentally, it will also update the rows each time it is called.
The case of the returned column names will not be changed.
The case of the returned column names will be changed to uppercase.
The case of the returned column names will be changed to lowercase.
DBX_RESULT_INDEX
DBX_RESULT_INDEX | DBX_RESULT_INFO
DBX_RESULT_INDEX | DBX_RESULT_INFO | DBX_RESULT_ASSOC - this is the default, if flags is not specified.
The returned object has four or five properties depending on flags:
It is a valid handle for the connected database, and as such it can be used in module specific functions (if required).
These contain the number of columns (or fields) and rows (or records) respectively.
It is returned only if either DBX_RESULT_INFO or DBX_RESULT_ASSOC is specified in the flags parameter. It is a 2 dimensional array, that has two named rows (name and type) to retrieve column information.
This property contains the actual resulting data, possibly associated with column names as well depending on flags. If DBX_RESULT_ASSOC is set, it is possible to use $result->data[2]["field_name"].
Esempio 3. outputs the content of data property into HTML table
|
Esempio 4. How to handle UNBUFFERED queries
|
Nota: Always refer to the module-specific documentation as well.
Column names for queries on an Oracle database are returned in lowercase.
See also dbx_escape_string(), dbx_fetch_row() and dbx_connect().
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)
dbx_sort -- Sort a result from a dbx_query by a custom sort functionRestituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: It is always better to use ORDER BY SQL clause instead of dbx_sort(), if possible.
Esempio 1. dbx_sort() example
|
See also dbx_compare().
Il PHP supporta funzioni per l'I/O diretto, come descritto dallo standard POSIX (Sezione 6), per potere eseguire operazioni di I/O ad un livello inferiore rispetto agli streams del linguaggio C (fopen(), fread(),..). Si dovrebbe prendere in considerazione l'uso delle funzioni di DIO soltanto nei casi in cui occorra un controllo diretto del device. In tutti gli altri casi le funzioni filesystem sono più che adeguate.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.1.0.
Questo modulo è disponibile sulla piattaforma Windows solo dal PHP 5.0.0
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Questa estensione definisce un solo tipo di risorsa: un descrittore di file restituito dalla funzione dio_open().
La funzione dio_fcntl() esegue le operazioni specificate dal parametro cmd sul descrittore di file fd. Qualora i comandi richiedano informazioni addizionali occorre valorizzare args con tali informazioni.
Nota: Questa funzione non è implementata su piattaforme Windows
Descrittore di file restituito da dio_open().
Può indicare una delle seguenti operazioni:
F_SETLK - imposta o azzera un lock. Se il lock è impostato da un'altro processo la funzione dio_fcntl() restituisce -1.
F_SETLKW - come F_SETLK, ma nel caso in cui il lock sia impostato da un'altro processo la funzione dio_fcntl() attende sino a quando il blocco non viene rimosso.
F_GETLK - la dio_fcntl() restituisce un array associativo (come descritto precedentemente) se qualche altro processo impedisce il lock. Se non vi sono problemi la chiave "type" sarà impostata a F_UNLCK.
F_DUPFD - trova il più piccolo numero di descrittore di file disponibile che sia maggiore o uguale rispetto ad args e lo restituisce.
F_SETFL - Imposta i flag del descrittore di file al valore specificato da args. Tale valore può essere O_APPEND, O_NONBLOCK oppure O_ASYNC. Per utilizzare O_ASYNC occorre utilizzare l'estensione PCNTL.
Il parametro args è un array associativo, nei casi in cui cmd è impostato a F_SETLK oppure a F_SETLLW, contiene le seguenti chiavi:
"start" - offset da cui comincia il lock
"length" - dimensione dell'area bloccata, zero significa fine file
"wenth" - a cosa l_start è relativo: può valere SEEK_SET, SEEK_END o SEEK_CUR
"type" - tipo di lock: può essere F_RDLCK (lock in lettura), F_WRLCK (lock in scrittura) oppure F_UNLCK (rimozione del lock)
Esempio 1. Impostare e cancellare un lock
|
(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)
dio_open -- Apre un nuovo file nella modalità specificata da flags e i permessi indicati in modeLa funzione dio_open() apre un file e restituisce un nuovo descrittore di file per questo.
Il file aperto.
Il parametro flags può contenere qualsiasi combinazione dei seguenti valori:
O_CREAT - crea un file, se questo non esiste già.
O_EXCL - se sono impostati sia O_CREAT e sia O_EXCL, la funzione dio_open() fallisce se il file esiste.
O_TRUNC - se il file esiste, ed è aperto in scrittura, il file verrà portato a lunghezza zero.
O_APPEND - nelle operazioni di scrittura, scrive i dati alla fine del file.
O_NONBLOCK - imposta la modalità non blocking.
Se flags vale O_CREAT, allora il parametro mode imposta la modalità del file (permessi di creazione).
O_RDONLY - apre il file per accessi in lettura.
O_WRONLY - apre il file in scrittura.
O_RDWR - apre il file sia in lettura sia in scrittura.
La funzione dio_read() legge e restituisce len bytes dal file indicato dal descrittore fd.
Descrittore di file restituito da dio_open().
Numero di byte da leggere. Se non indicato dio_read() legge blocchi da un 1k.
La funzione dio_seek() viene utilizzata per modificare la posizione nel file indicato dal descrittore fd.
Descrittore di file restituito da dio_open().
La nuova posizione.
specifica come debba essere interpretata la posizione indicata da pos:
SEEK_SET (default) - Indica che pos è determinato dall'inizio del file.
SEEK_CUR - Indica che pos è il numero di caratteri dalla posizione attuale. Questo valore può essere positivo o negativo.
SEEK_END - Indica che pos è il numero di caratteri dalla fine del file. Un valore negativo specifica una posizione all'interno dell'estensione del file; un valore positivo specifica una posizione oltre la fine corrente del file. Se si specifica una posizione oltre la fine del file, e vi si scrive dei dati, il file sarà allungato e riempito di zero fino a quella posizione.
Esempio 1. Posizionamento in un file
|
(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)
dio_stat -- Restituisce le informazioni relative al file indicato da fdLa funzione dio_stat() restituisce le informazioni sul dato descrittore di file.
Restituisce un array associativo contenente le seguenti chiavi:
"device" - device
"inode" - inode
"mode" - mode
"nlink" - numero di link
"uid" - user id
"gid" - group id
"device_type" - device type (se inode device)
"size" - total size in bytes
"blocksize" - blocksize
"blocks" - dimensione totale in byte
"atime" - data dell'ultimo accesso
"mtime" - data dell'ultima modifica
"ctime" - data dell'ultimo cambiamento
(PHP 4 >= 4.3.0, PHP 5 <= 5.0.4)
dio_tcsetattr -- Imposta gli attributi terminale e la velocità per una porta serialeLa funzione dio_tcsetattr() imposta gli attributi di terminale e la velocità della porta aperta fd.
Nota: Questa funzione non è implementata su piattaforme Windows
Descrittore di file restituito da dio_open().
Attualmente le opzioni disponibili sono:
'baud' - velocità della porta - può essere 38400,19200,9600,4800,2400,1800,1200,600,300,200,150,134,110,75 oppure 50, il valore di default è 9600
'bits' - bit di dati - può essere 8,7,6 oppure 5 il valore di default è 8.
'stop' - bit di stop - può essere 1 o 2 il valore di default è 1.
'parity' - può essere 0,1 o 2 il valore di default è 0.
Esempio 1. Esempio di impostazione della velocità di una porta seriale
|
(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)
dio_truncate -- Tronca il file indicato da fd ad un numero di byte specificatoLa funzione dio_truncate() tronca il file indicato da fd ad una lunghezza massima di offset bytes.
Se in precedenza il file ha una dimensione maggiore, i dati in eccesso sono persi. Al contrario se il file è più corto, non è specificato se si debba lasciarlo inalterato o debba essere allungato. Nell'ultimo caso la parte aggiunta viene riempita a zero.
Nota: Questa funzione non è implementata su piattaforme Windows
(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)
dio_write -- Scrive dati sul file indicato da fd con la possibilità di troncarne la lunghezzaLa funzione dio_write() scrive fino a len bytes da data nel file fd.
Descrittore di file restituito da dio_open().
I dati scritti.
Lunghezza dei dati da scrivere in byte. Se non indicato, la funzione scrive tutti i dati nel file indicato.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Nota: La costante PATH_SEPARATOR è stata inserita dalla versione 4.3.0-RC2.
Per funzioni correlate, quali dirname(), is_dir(), mkdir() e rmdir(), vedere la sezione Filesystem.
Cambia la directory in uso da parte del PHP in directory. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Quando safe-mode è abilitato, PHP controlla che la directory nella quale si sta lavorando, abbia lo stesso UID dello script che è in esecuzione.
Vedere anche getcwd().
Cambia la directory di root del processo in esecuzione in directory. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Questa funzione è disponibile soltanto se il sistema la supporta e se si sta utilizzando il PHP come CLI, CGI o Embed SAPI.
Nota: chroot() richiede i privilegi di root.
Nota: Questa funzione non è implementata su piattaforme Windows
Un meccanismo pseudo orientato agli oggetti per leggere una directory. La directory data è aperta. Due proprietà sono disponibili nonappena la directory è stata aperta. La proprietà handle può essere usata in congiunzione ad altre funzioni relative alle directory, quali readdir(), rewinddir() e closedir(). La proprietà path è impostata alla directory che è stata aperta. Sono disponibili tre metodi: read (leggi), rewind (riavvolgi) e close (chiudi).
Fare attenzione al modo in cui il valore restituito dalla funzione dir() è controllato nell'esempio sotto riportato. Controlliamo esplicitamente che il valore restituito sia identico a (uguale a e dello stesso tipo di (fare riferimento a Comparison Operators per maggiori informazioni) FALSE altrimenti, ogni risultato il cui nome non venga valutato FALSE farà interrompere il ciclo.
Nota: L'ordine nel quale vengono restituiti i dati dal metodo read è dipendente dal sistema usato.
Nota: Questo definisce la classe interna Directory, ciò significa che non sarà possibile definire una nuova classe con lo stesso nome. Per una lista completa delle classi predefinite presenti in PHP, fare riferimento a Predefined Classes.
Chiude il flusso directory indicato da dir_handle. Il flusso deve essere stato aperto in precedenza da opendir().
Restituisce la directory di lavoro in uso al momento o FALSE in caso di errore.
Nota: In alcune versioni di Unix, getcwd() restituirà FALSE se una delle directory superiori non ha i permessi di lettura o di ricerca abilitati, anche se li ha la directory corrente Vedere chmod() per maggiori infprmazioni sui permessi.
Restituisce un handle della directory da usare nelle chiamate alle funzioni closedir(), readdir() e rewinddir().
Se percorso non è una directory valida o la directory non può essere aperta a causa di restrizioni sui permessi di accesso o a causa di errori del filesystem, opendir() restituisce FALSE e genera un errore PHP di tipo E_WARNING. Si può sopprimere l'output dell'errore di opendir() anteponendo '@' davanti al nome della funzione.
Dal PHP 4.3.0 path può essere anche un URL che suuporto la visualizzazione del contenuto della directory, tuttavia, in PHP 4.3.0, soltanto il wrapper URL file:// supporta ciò. A partire da PHP 5.0.0, sarà disponibile il supporto per ftp://.
Restituisce il nomefile del file successivo della directory. I nomi dei file vengono restituiti secondo l'ordine in cui sono memorizzati nel filesystem.
Si faccia caso al modo in cui il valore restituito da readdir() viene controllato negli esempi successivi. Viene controllato esplicitamente che il valore restituito sia identico a (uguale a e dello stesso tipo di (vedere Comparison Operators per maggiori informazioni) FALSE altrimenti avverrebbe che ogni nome di directory il cui nome fosse valutato FALSE interromperebbe il loop (per esempio una directory chiamata "0").
Esempio 1. Elenca tutti i file presenti in una directory
|
Nota che readdir() restituirà le voci . e ... Se non si vogliono ottenere queste, si possono semplicemente eliminare:
Reimposta il flusso della directory indicato da dir_handle all'inizio della directory.
Returns an array of files and directories from the directory.
The directory that will be scanned.
By default, the sorted order is alphabetical in ascending order. If the optional sorting_order is used (set to 1), then the sort order is alphabetical in descending order.
For a description of the context parameter, refer to the streams section of the manual.
Returns an array of filenames on success, or FALSE on failure. If directory is not a directory, then boolean FALSE is returned, and an error of level E_WARNING is generated.
Esempio 1. A simple scandir() example
Il precedente esempio visualizzerà qualcosa simile a:
|
Esempio 2. PHP 4 alternatives to scandir()
Il precedente esempio visualizzerà qualcosa simile a:
|
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
L'estensione DOM è la sostituzione dell'estensione DOM XML del PHP 4. Questo modulo continua a contenere diverse vecchie funzioni, ma non dovrebbereo essere più utilizzate. In particolar modo si dovrebbe evitare le funzioni che non sono orientate agli oggetti.
L'estensione permette di lavorare su un documento XML con le API DOM.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Le APi del modulo seguono lo standard DOM Level 2 il più fedelmente possibile. Di conseguenza la API sono completamente ad oggetti. E' consigliabile avere a portata di mano lo standard DOM quando si utilizza questo modulo.
Questo modulo definisce diverse classi, che sono illustrate nelle seguenti tabelle. Quelle con una corrispondente classe nello standard DOM sono chia,ate DOMxxx.
Estende DOMNode. L'interfaccia DOMAttr rappresenta un attributo dell'oggetto DOMElement.
Espande DOMNode.
DOMCharacterData->appendData() - Aggiunge un testo alla fine dei dati di un nodo
DOMCharacterData->deleteData() - Rimuove un range di caratteri dal nodo
DOMCharacterData->insertData() - Inserisce una stringa alla posizione indicata
DOMCharacterData->replaceData() - Sostituisce una posizione di testo nel nodo DOMCharacterData
DOMCharacterData->substringData() - Estrai una porzione di dati dal nodo
Espande DOMNode.
DOMDocument->createAttribute() - Crea un nuovo attributo
DOMDocument->createAttributeNS() - Crea un nuovo nodo attributo con associato uno spazio dei nomi
DOMDocument->createCDATASection() - Crea un nuovo nodo cdata
DOMDocument->createComment() - Crea un nuovo nodo commento
DOMDocument->createDocumentFragment() - Crea un nuovo nodo frammento
DOMDocument->createElement() - Crea un nuovo nodo elemento
DOMDocument->createElementNS() - Crea un nuovo nodo elemento con associato uno spazio dei nomi
DOMDocument->createEntityReference() - Crea un nuovo nodo entità
DOMDocument->createProcessingInstruction() - CRea un nuovo nodo PI
DOMDocument->createTextNode() - Crea un nuovo nodo testo
DOMDocument->getElementById() - Cerca un elemento con un certo ID
DOMDocument->getElementsByTagName() - Cerca tutti gli elementi per un dato tag
DOMDocument->getElementsByTagNameNS() - Cerca tutti gli elementi per un dato tag in un specifico spazio dei nomi
DOMDocument->importNode() - Importa il nodo nel documento corrente
DOMDocument->load() - Carica un file XML
DOMDocument->loadHTML() - Carica un documento HTML da una stringa
DOMDocument->loadHTMLFile() - Carica un file HTML
DOMDocument->loadXML() - Carica un documento XML da una stringa
DOMDocument->normalize() - Normalizza il documento
DOMDocument->relaxNGValidate() - Esegue una validazione relaxNG sul documento
DOMDocument->relaxNGValidateSource() - Esegue una validazione relaxNG sul documento
DOMDocument->save() - Scrive l'albero XML in un file
DOMDocument->saveHTML() - Scarica il docuemnto interno in una stringa formattato in HTML
DOMDocument->saveHTMLFile() - Scarica il docuemnto interno in un file formattato in HTML
DOMDocument->saveXML() - Scrive l'albero XML in un file in una stringa
DOMDocument->schemaValidate() - Valida il documento in base ad uno schema
DOMDocument->schemaValidateSource() - Valida il documento in base ad uno schema
DOMDocument->validate() - Valida il documento in base ad al suo DTD
DOMDocument->xinclude() - Sostituisce gli XIncludes in un oggetto DOMDocument
Tabella 3.
Nome | Tipo | Sola lettura | Descrizione |
---|---|---|---|
actualEncoding | string | sì | |
config | DOMConfiguration | sì | |
doctype | DOMDocumentType | sì | Dichiarazione del tipo documento associato al docuemnto. |
documentElement | DOMElement | sì | Attributo di convenienza per accedere direttamente al nodo figlio, che è l'elemento del documento. |
documentURI | string | no | Luogo del documento oppure NULL se indefinito. |
encoding | string | no | |
formatOutput | bool | no | |
implementation | DOMImplementation | sì | L'oggetto DOMImplementation che gestisce questo documento. |
preserveWhiteSpace | bool | no | Non rimuovere gli spazi ridondanti. Default TRUE. |
recover | bool | no | |
resolveExternals | bool | no | Impostare a TRUE per caricare le entità esterne dalla dichiarazione doctype. Questo è utile per includere entità di caratteri nel documento XML. |
standalone | bool | no | |
strictErrorChecking | bool | no | Genera un DOMException in caso di errore. Default TRUE. |
substituteEntities | bool | no | |
validateOnParse | bool | no | Carica e valida nei confronti della DTD. Default FALSE. |
version | string | no | |
xmlEncoding | string | sì | L'attributo specifica, come parte della dichiarazione XML, la codifica del docuemnto. Vale NULL se non specificato oppure quando non è noto, come quando il documento è creato in memoria. |
xmlStandalone | bool | no | Attributo che specifica, come parte della dichiarazione XML, se il documento è standalone. Vale FALSE se non specificato. |
xmlVersion | string | no | Attributo che specifica, come parte della dichiarazione XML, il numero di versione del documento. Se non viè una dichiarazione e se il documento supporta le spcifiche "XML", vale "1.0". |
Espande DOMNode
Ciascun DOMDocument possiede un attributo doctype il cui valore può essere o NULL o un oggetto DOMDocumentType.
Tabella 4.
Nome | Tipo | Sola lettura | Descrizione |
---|---|---|---|
publicId | string | sì | Identificatore pubblico del subset esterno. |
systemId | string | sì | Identificatore di sistema del subset esterno. Può essere un URI assoluto o meno. |
name | string | sì | Il nome della DTD; ad esempio il nome che segue immediatamente la parola chiave DOCTYPE. |
entities | DOMNamedNodeMap | sì | Un oggetto DOMNamedNodeMap che contiene le entità generali, sia interne che esterne, dichiarate nella DTD. |
notations | DOMNamedNodeMap | sì | Un oggetto DOMNamedNodeMap contenente le notazioni dichiarate nella DTD. |
internalSubset | string | sì | SubSet interno definito come stringa, oppure null se non vi è nulla. Questo non contiene le parentesi quadre di delimitazione. |
Espande DOMNode.
DOMElement->getAttribute() - Restituisce il valore di un attributo
DOMElement->getAttributeNode() - Restituisce il nodo attributo
DOMElement->getAttributeNodeNS() - Restituisce il nodo attributo
DOMElement->getAttributeNS() - Restituisce il valore di un attributo
DOMElement->getElementsByTagName() - Restituisce gli elementi in base al nome tag
DOMElement->getElementsByTagNameNS() - Restituisce gli elementi in base all UTRI dello spazio dei nomi ed il nome locale
DOMElement->hasAttribute() - Verifica se l'attributo esiste
DOMElement->hasAttributeNS() - Verifica se l'attributo esiste
DOMElement->removeAttribute() - Rimuove l'attributo
DOMElement->removeAttributeNode() - Rimuove l'attributo
DOMElement->removeAttributeNS() - Rimuove l'attributo
DOMElement->setAttribute() - Aggiunge un nuovo attributo
DOMElement->setAttributeNode() - Aggiunge un nuovo nodo attributo all'elemento
DOMElement->setAttributeNodeNS() - Aggiunge un nuovo nodo attributo all'elemento
DOMElement->setAttributeNS() - Aggiunge un nuovo attributo
Espande DOMNode
Questa interfaccia rappresenta una entità nota, sia interpretata che no, in un documento XML.
Tabella 6.
Nome | Tipo | Sola lettura | Descrizione |
---|---|---|---|
publicId | string | sì | Identificatore pubblico associato all'entità, se indicato, altrimenti NULL. |
systemId | string | sì | Identificatore di sistema associato all'entità, se indicato, altrimenti NULL. Può essere un URI assoluto. |
notationName | string | sì | Per le entità non interpretate, il nome della notazione dell'entità. Per le entità interpretate vale NULL. |
actualEncoding | string | no | Attributo che indica la codifica utilizzata per questa entità al momento dell'intepretazione, in caso di interpretazione di entità esterne. Vale NULL se si tratta di un'entità interna, o se non è noto. |
encoding | string | sì | Attributo che indica, come parte del testo di dichiarazione, la codifica dell'entità, in caso di entità esterna. Negli altri casi vale NULL. |
version | string | sì | Attributo che indica, come parte del testo di dichiarazione, il numero di versione di questa entità, in caso di entità esterna. Altrimenti NULL. |
Le funzioni DOM, in casi particolari, generano delle eccezioni, ad esempio quando un'operazione non può essere eseguita per motivi logici.
Vedere anche Capitolo 20.
L'interfaccia DOMImplementation fornisce diversi metodi per eseguire operazioni che sono indipendenti da qualsiasi istanza del modello ad oggetti del documento.
DOMImplementation->createDocument() - Crea un nuovo oggetto DOM Document del tipo specificato con il suo elemento documento
DOMImplementation->createDocumentType() - Crea un oggetto DOMDocumentType vuoto
DOMImplementation->hasFeature() - Verifica se l'implementazione DOM supporta specifiche caratteristiche
DOMNode->appendChild() - Aggiunge un nuovo nodo figlio alla fine dei nodi figli
DOMNode->cloneNode() - Clona un nodo
DOMNode->hasAttributes() - Verifica se il nodo ha attributi
DOMNode->hasChildNodes() - Verifica se il nodo ha figli
DOMNode->insertBefore() - Aggiunge un nuovo figlio prima del nodo indicato
DOMNode->isSameNode() - Indica se due nodi sono lo stesso nodo
DOMNode->isSupported() - Verifica se la caratteristica chiesta è supportata dalla versione
DOMNode->lookupNamespaceURI() - Restituisce l'URI dello spazio dei nomi del nodo in base al suo prefisso
DOMNode->lookupPrefix() - Restituisce il prefisso dello spazio dei nomi del nodo in base all'URI dello spazio dei nomi
DOMNode->normalize() - Normalizza il nodo
DOMNode->removeChild() - Rimuove un nodo figlio dall'elenco dei nodi figli
DOMNode->replaceChild() - Sostituisce un nodo figlio
Tabella 8.
Nome | Tipo | Sola lettura | Descrizione |
---|---|---|---|
nodeName | string | sì | Restituisce un nome più accurato per il tipo di nodo. |
nodeValue | string | no | Valore di questo nodo, dipende dal tipo. |
nodeType | int | sì | Tipo di nodo. Una delle costanti XML_xxx_NODE predefinite. |
parentNode | DOMNode | sì | Nodo genitore di questo nodo. |
childNodes | DOMNodeList | sì | Un oggetto DOMNodeList che contiene tutti i nodi figli di questo nodo. Se non vi sono nodi figli, questa è un DOMNodeList vuoto. |
firstChild | DOMNode | sì | Il primo figlio di questo nodo. Se tale nodo non esiste, restituisce NULL. |
lastChild | DOMNode | sì | L'ultimo figlio di questo nodo. Se tale nodo non esiste, restituisce NULL. |
previousSibling | DOMNode | sì | Il nodo immediatamente precedente a questo. Se tale nodo non esiste, restituisce NULL. |
nextSibling | DOMNode | sì | Il nodo immediatamente seguente a questo. Se tale nodo non esiste, restituisce NULL. |
attributes | DOMNamedNodeMap | sì | Un oggetto DOMNamedNodeMap contenente gli attributi di questo nodo (se si tratta di un DOMElement) oppure NULL. |
ownerDocument | DOMDocument | sì | L'oggetto DOMDocument associato a questo nodo. |
namespaceURI | string | sì | L'URI dello spazio dei nomi di questo nodo, oppure NULL se non specificato. |
prefix | string | no | Prefisso dello spazio dei nomi del nodo, oppure NULL se non specificato. |
localName | string | sì | Restituisce la parte locale del nome qualificato del nodo. |
baseURI | string | sì | L'URI assoluto del nodo oppure NULL se l'implementazione non è in grado di ottenere l'URI assoluto. |
textContent | string | no | Questo attributo restituisce il testo contenuto nel nodo e nei suoi discendenti. |
Espande DOMNode.
DOMProcessingInstruction->__construct() - costruisce un nuovo oggetto DOMProcessingInstruction
Espande DOMCharacterData.
DOMText->isWhitespaceInElementContent() - Indica se questo nodo contiene degli spazi
DOMText->splitText() - Divide il nodo in due alla posizione indicata
DOMXPath->registerNamespace() - Registers the namespace with the DOMXpath object
DOMXPath->evaluate() - Evaluates the given XPath expression and returns a typed result if possible
DOMXPath->query() - Evaluates the given XPath expression
Many examples in this reference require an XML file. We will use book.xml that contains the following:
Esempio 1. chapter.xml
|
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 14. Costanti XML
Costante | Valore | Descrizione |
---|---|---|
XML_ELEMENT_NODE (integer) | 1 | Il nodo è un DOMElement |
XML_ATTRIBUTE_NODE (integer) | 2 | Il nodo è un DOMAttr |
XML_TEXT_NODE (integer) | 3 | Il nodo è un DOMText |
XML_CDATA_SECTION_NODE (integer) | 4 | Il nodo è un oggetto DOMCharacterData |
XML_ENTITY_REF_NODE (integer) | 5 | Il nodo è un oggetto DOMEntityReference |
XML_ENTITY_NODE (integer) | 6 | Il nodo è un DOMEntity |
XML_PI_NODE (integer) | 7 | Il nodo è un DOMProcessingInstruction |
XML_COMMENT_NODE (integer) | 8 | Il nodo è un DOMComment |
XML_DOCUMENT_NODE (integer) | 9 | Il nodo è un DOMDocument |
XML_DOCUMENT_TYPE_NODE (integer) | 10 | Il nodo è un oggetto DOMDocumentType |
XML_DOCUMENT_FRAG_NODE (integer) | 11 | Il nodo è un oggetto DOMDocumentFragment |
XML_NOTATION_NODE (integer) | 12 | Il nodo è un oggetto DOMNotation |
XML_HTML_DOCUMENT_NODE (integer) | 13 | |
XML_DTD_NODE (integer) | 14 | |
XML_ELEMENT_DECL_NODE (integer) | 15 | |
XML_ATTRIBUTE_DECL_NODE (integer) | 16 | |
XML_ENTITY_DECL_NODE (integer) | 17 | |
XML_NAMESPACE_DECL_NODE (integer) | 18 | |
XML_ATTRIBUTE_CDATA (integer) | 1 | |
XML_ATTRIBUTE_ID (integer) | 2 | |
XML_ATTRIBUTE_IDREF (integer) | 3 | |
XML_ATTRIBUTE_IDREFS (integer) | 4 | |
XML_ATTRIBUTE_ENTITY (integer) | 5 | |
XML_ATTRIBUTE_NMTOKEN (integer) | 7 | |
XML_ATTRIBUTE_NMTOKENS (integer) | 8 | |
XML_ATTRIBUTE_ENUMERATION (integer) | 9 | |
XML_ATTRIBUTE_NOTATION (integer) | 10 |
Tabella 15. Costanti DOMException
Costante | Valore | Descrizione |
---|---|---|
DOM_INDEX_SIZE_ERR (integer) | 1 | Se l'indice o la dimensione sono negativi, o maagiori del valore ammesso. |
DOMSTRING_SIZE_ERR (integer) | 2 | Se il range di testo indicato non rientra nell'oggetto DOMString. |
DOM_HIERARCHY_REQUEST_ERR (integer) | 3 | Se il nodo è inserito in posti non attesi |
DOM_WRONG_DOCUMENT_ERR (integer) | 4 | Se il nodo viene utilizzato in documenti differenti rispetto a quello che lo ha creato. |
DOM_INVALID_CHARACTER_ERR (integer) | 5 | Carattere invalido o illegale. |
DOM_NO_DATA_ALLOWED_ERR (integer) | 6 | Dati indicati per un nodo che non gestisce i dati. |
DOM_NO_MODIFICATION_ALLOWED_ERR (integer) | 7 | Tentativo di modifica di un oggetto che non permette modifiche. |
DOM_NOT_FOUND_ERR (integer) | 8 | Riferimento ad un nodo in un contesto in cui non esiste. |
DOM_NOT_SUPPORTED_ERR (integer) | 9 | Tipo di oggetto oppure operazione non supportata dall'implementazione. |
DOM_INUSE_ATTRIBUTE_ERR (integer) | 10 | Tentativo di aggiungere un attributo già in uso altrove. |
DOM_INVALID_STATE_ERR (integer) | 11 | Utilizzo di un oggetto che non è più utilizzabile. |
DOM_SYNTAX_ERR (integer) | 12 | Stringa non valida o illegale. |
DOM_INVALID_MODIFICATION_ERR (integer) | 13 | Tentativo di modificare il tipo dell'oggetto sottostante. |
DOM_NAMESPACE_ERR (integer) | 14 | Tentativo di creare o modficiare un oggetto in un modo che non è corretto rispetto allo spazio dei nomi. |
DOM_INVALID_ACCESS_ERR (integer) | 15 | Parametro od operazione non supportati dall'oggetto. |
DOM_VALIDATION_ERR (integer) | 16 | Chiamata ad un metodo tipo insertBefore oppure removeChild che renda il nodo invalido ripetto ad una 'validazione parziale'; questa eccezione comporta la mancata esecuzione dell'operazione. |
(no version information, might be only in CVS)
DOMAttr->__construct() -- Crea un nuovo oggetto DOMAttrCrea un nuovo oggetto DOMAttr. Questo oggetto è in sola lettura. Può essere aggiunto al documento, ma non vi possono essere aggiunti nodi fino a quando DOMDocument->createAttribute().
Nome tag dell'attributo- The tag name of the attribute.
Valore dell'attributo.
Esempio 1. Esempio di creazione di un nuovo DOMAttr
|
(no version information, might be only in CVS)
DOMAttr->isId() -- Verifica se l'attributo è un ID definitoQuesta funzione verifica se l'attributo sia un ID definito.
In base allo standard DOM, questa funzione riochiede la presenza di una DTD che definisca l'attributo ID di tipo ID. Occorre validare il documento con DOMDocument->validate() oppure DOMDocument::validateOnParse prima di utilizzare questa funzione.
Esempio 1. DOMAttr->isId() Example
|
(no version information, might be only in CVS)
DOMCharacterData->appendData() -- Aggiunge una stringa alla fine del testo di un nodoAggiunge la stringa data alla fine dei dati del nodo.
DOMCharacterData->deleteData() |
DOMCharacterData->insertData() |
DOMCharacterData->replaceData() |
DOMCharacterData->substringData() |
(no version information, might be only in CVS)
DOMCharacterData->deleteData() -- Rimuove un range di caratteri da un nodoRimuove un numero di caratteri pari a count a partire dalla posizione offset.
Offset da cui partire a rimuovere.
Il numero di caratteri da rimuovere. Se la somma di offset e count eccede la lunghezza del testo, saranno cancellati tutti i caratteri fino alla fine.
Eccezione generata se offset è negativo oppure più grande di un numero di 16 bit, oppure se count è negativo.
DOMCharacterData->appendData() |
DOMCharacterData->insertData() |
DOMCharacterData->replaceData() |
DOMCharacterData->substringData() |
(no version information, might be only in CVS)
DOMCharacterData->insertData() -- Inserisce una stringa all'offset di 16 bit indicatoInserisce la stringa data alla posizione offset.
L'offset del carattere da cui cominciare ad inserire.
La stringa da inserire.
DOMCharacterData->appendData() |
DOMCharacterData->deleteData() |
DOMCharacterData->replaceData() |
DOMCharacterData->substringData() |
(no version information, might be only in CVS)
DOMCharacterData->replaceData() -- Sostituisce una stringa all'interno di un nodo DOMCharacterDataSostituisce count caratteri a partire dalla posizione offset con data.
Offset da cui iniziare la sostituzione.
Numero di caratteri da sostituire. Se la somma di offset e count eccede la lunghezza, allora saranno sostituiti tutti i caratteri fino alla fine.
La stringa con cui sostituire i caratteri del range indicato.
Generato se offset è negativo o maggiore di un numero di 16 bit, oppure se count è negativo.
DOMCharacterData->appendData() |
DOMCharacterData->deleteData() |
DOMCharacterData->insertData() |
DOMCharacterData->substringData() |
(no version information, might be only in CVS)
DOMCharacterData->substringData() -- Estrae un tange di dati da un nodoRestituisce la stringa richiesta.
Offset di partenza della stringa richiesta.
Numero di caratteri da estrarre.
La stringa richiesta. Se la somma di offset e count supera in lunghezza i dati del nodo, considerati tutti a 16 bit, viengono restituiti tutti i dati fino alla fine.
Generato se offset è negativo o maggiore di un numero di 16 bit, oppure se count è negativo.
DOMCharacterData->appendData() |
DOMCharacterData->deleteData() |
DOMCharacterData->insertData() |
DOMCharacterData->replaceData() |
(no version information, might be only in CVS)
DOMComment->__construct() -- Crea un nuovo oggetto DOMCommentCrea un nuovo oggetto DOMComment. Questo oggetto è in sola lettura. Può essere aggiunto ad un documento, ma non si possono inserire nodi aggiuntivi a questo nodo sino a quando il nodo è associato al docuemnto. Per creare un modo modificabile utilizzare DOMDocument->createComment().
Esempio 1. Esempio di creazione di un nuovo DOMComment
|
(no version information, might be only in CVS)
DOMDocument->__construct() -- Crea un nuovo oggetto DOMDocumentCrea un nuovo oggetto DOMDocument.
Numero di versione del documento come parte della dichiarazione XML.
Codifica del docuemnto utilizzata nella dichisrazione XML.
(no version information, might be only in CVS)
DOMDocument->createAttribute() -- Crea un nuovo attributoQuesta funzione crea una nuova istanza della classe DOMAttr. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
DOMNode->appendChild() |
DOMDocument->createAttributeNS() |
DOMDocument->createCDATASection() |
DOMDocument->createComment() |
DOMDocument->createDocumentFragment() |
DOMDocument->createElement() |
DOMDocument->createElementNS() |
DOMDocument->createEntityReference() |
DOMDocument->createProcessingInstruction() |
DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createAttributeNS() -- Crea un nuovo nodo attributo con associato lo spazio dei nomiQuesta funzione crea una nuova istanza della classe DOMAttr. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
L' URI dello spazio dei nomi.
Il nome del tag e prefisso dell'attributo nella struttura prefix:tagname.
Generato se qualifiedName contiene carattei non validi.
Generato se qualifiedName se è un nome malformato, oppure se qualifiedName ha un prefisso e namespaceURI vale NULL.
DOMNode->appendChild() |
DOMDocument->createAttribute() |
DOMDocument->createCDATASection() |
DOMDocument->createComment() |
DOMDocument->createDocumentFragment() |
DOMDocument->createElement() |
DOMDocument->createElementNS() |
DOMDocument->createEntityReference() |
DOMDocument->createProcessingInstruction() |
DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createCDATASection() -- Crea un nuovo nodo cdataQuesta funzione crea una nuova istanza della classe DOMCDATASection. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
DOMNode->appendChild() |
DOMDocument->createAttribute() |
DOMDocument->createAttributeNS() |
DOMDocument->createComment() |
DOMDocument->createDocumentFragment() |
DOMDocument->createElement() |
DOMDocument->createElementNS() |
DOMDocument->createEntityReference() |
DOMDocument->createProcessingInstruction() |
DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createComment() -- Crea un nuovo nodo di commentoQuesta funzione crea una nuova istanza della classe DOMComment. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
DOMNode->appendChild() |
DOMDocument->createAttribute() |
DOMDocument->createAttributeNS() |
DOMDocument->createCDATASection() |
DOMDocument->createDocumentFragment() |
DOMDocument->createElement() |
DOMDocument->createElementNS() |
DOMDocument->createEntityReference() |
DOMDocument->createProcessingInstruction() |
DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createDocumentFragment() -- Crea un nuovo frammento di documentoQuesta funzione crea una nuova istanza della classe DOMDocumentFragment. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
DOMNode->appendChild() |
DOMDocument->createAttribute() |
DOMDocument->createAttributeNS() |
DOMDocument->createCDATASection() |
DOMDocument->createComment() |
DOMDocument->createElement() |
DOMDocument->createElementNS() |
DOMDocument->createEntityReference() |
DOMDocument->createProcessingInstruction() |
DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createElement() -- Crea un nuovo nodo elementoQuesta funzione crea una nuova istanza della classe DOMElement. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
Il nome del tag dell'elemento.
Il valore dell'elemento. Per default si crea un elemento vuoto. Il valore può essere impostato in un secondo momento tramite DOMElement->nodeValue.
Restituisce una nuova istanza della classe DOMElement oppure FALSE in caso di errore.
Esempio 1. Esempio di creazione di un nuovo elemento ed inserimento nel documento come root
Il precedente esempio visualizzerà:
|
DOMNode->appendChild() |
DOMDocument->createAttribute() |
DOMDocument->createAttributeNS() |
DOMDocument->createCDATASection() |
DOMDocument->createComment() |
DOMDocument->createDocumentFragment() |
DOMDocument->createElementNS() |
DOMDocument->createEntityReference() |
DOMDocument->createProcessingInstruction() |
DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createElementNS() -- Crea un nuovo nodo elemento con associato lo spazio dei nomiQuesta funzione crea un nuovo nodo elemento con associato lo spazio dei nomi. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
L' URI dello spazio dei nomi.
Un nuome qualificato pe l'elemento del tipo prefix:tagname.
Il valore dell'elemento. Per default si crea un elemento vuoto. Il valore può essere impostato in un secondo momento tramite DOMElement->nodeValue.
Generato se qualifiedName contiene caratteri non validi.
Generato se qualifiedName se è un nome qualificato invalido.
Esempio 1. Esempio di creazione di un nuovo elemento ed inserimento nel documento come root
Il precedente esempio visualizzerà:
|
DOMNode->appendChild() |
DOMDocument->createAttribute() |
DOMDocument->createAttributeNS() |
DOMDocument->createCDATASection() |
DOMDocument->createComment() |
DOMDocument->createDocumentFragment() |
DOMDocument->createElement() |
DOMDocument->createEntityReference() |
DOMDocument->createProcessingInstruction() |
DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createEntityReference() -- Crea un nuovo nodo riferimento ad entitàQuesta funzione crea una nuova istanza della classe DOMEntityReference. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
Il contenuto del riferimento all'entità, ad esempio il riferimento all'entità meno & iniziale e ; finale.
DOMNode->appendChild() |
DOMDocument->createAttribute() |
DOMDocument->createAttributeNS() |
DOMDocument->createCDATASection() |
DOMDocument->createComment() |
DOMDocument->createDocumentFragment() |
DOMDocument->createElement() |
DOMDocument->createElementNS() |
DOMDocument->createProcessingInstruction() |
DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createProcessingInstruction() -- Crea un nuovo nodo PIQuesta funzione crea una nuova istanza della classe DOMProcessingInstruction. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
Il target delle itrsuzioni di processamento.
Il contenuto della PI.
DOMNode->appendChild() |
DOMDocument->createAttribute() |
DOMDocument->createAttributeNS() |
DOMDocument->createCDATASection() |
DOMDocument->createComment() |
DOMDocument->createDocumentFragment() |
DOMDocument->createElement() |
DOMDocument->createElementNS() |
DOMDocument->createEntityReference() |
DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createTextNode() -- Crea un nuovo nodo di testoQuesta funzione crea una nuova istanza della classe DOMText. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
DOMNode->appendChild() |
DOMDocument->createAttribute() |
DOMDocument->createAttributeNS() |
DOMDocument->createCDATASection() |
DOMDocument->createComment() |
DOMDocument->createDocumentFragment() |
DOMDocument->createElement() |
DOMDocument->createElementNS() |
DOMDocument->createEntityReference() |
DOMDocument->createProcessingInstruction() |
(no version information, might be only in CVS)
DOMDocument->getElementById() -- Cerca un elemento con un certo idQuesta funzione è simile a DOMDocument->getElementsByTagName(), ma cerca un elemento per il dato id.
In base allo standard DOM, questa funzione riochiede la presenza di una DTD che definisca l'attributo ID di tipo ID. Occorre validare il documento con DOMDocument->validate() oppure DOMDocument->validateOnParse prima di utilizzare questa funzione.
Esempio 1. Esempio di uso di DOMDocument->getElementById()
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
DOMDocument->getElementsByTagName() -- Cerca tutti gli eleemnti per un dato nome di tagQuesta funzione crea una nuova istanza della classe DOMNodeList contenente gli elementi con il nome tag cercato.
(no version information, might be only in CVS)
DOMDocument->getElementsByTagNameNS() -- Ricerca tutti gli elementi per un dato nome tag nello spazio dei nomi indicato.Restituicse un DOMNodeList contenente tutti gli elementi con il nome e lo spazio dei nomi indicati.
L' URI dello spazio dei nomi degli elementi da cercare. Il valore speciale * indica tutti.
Il nome locale degli elementi da cercare. Il valore speciale * indica tutti.
Esempio 1. Ottienet tutti gli elementi XInclude
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
DOMDocument->importNode() -- Importa un nodo nel documento correnteQuesta funzione restituisce una copia del nodo da importare e lo associa al documento corrente.
Il nodo da importare.
Se impostato a TRUE, questo metodo importerà in modo ricorsivo il sotto-albero di importedNode.
(no version information, might be only in CVS)
DOMDocument->load() -- Carica un documento XML da un fileCarica un documento XML da un file.
Questo metodo può essere richiamato staticamente per caricare e creare un oggetto DOMDocument. L'inbvocazione statica può essere utilizzata quando non occorre impostare le proprietà di DOMDocument prima del caricamento.
(no version information, might be only in CVS)
DOMDocument->loadHTML() -- Carica una pagina HTML da una stringaLa funzione esegue il parsing di una pagina HTML contenuta nella stringa source. A differenza del carico di un documento XML, il documento HTML non deve essere ben formato per potere essere caricato. Questa funzione può essere richiamata staticamente per caricare e creare un oggetto DOMDocument. L'invocazione statica può essere utilizzata quando non debbano essere impostate proprietà per DOMDocument prima del caricamento.
La funzione esegue il parsing del file HTML filename. A differenza del carico di un documento XML, il documento HTML non deve essere ben formato per potere essere caricato.
Questa funzione può essere richiamata staticamente per caricare e creare un oggetto DOMDocument. L'invocazione statica può essere utilizzata quando non debbano essere impostate proprietà per DOMDocument prima del caricamento.
(no version information, might be only in CVS)
DOMDocument->loadXML() -- Carica un documento XML da una stringaCarica un documento XML da una stringa.
Questa funzione può essere richiamata staticamente per caricare e creare un oggetto DOMDocument. L'invocazione statica può essere utilizzata quando non debbano essere impostate proprietà per DOMDocument prima del caricamento.
(no version information, might be only in CVS)
DOMDocument->relaxNGValidate() -- Esegue una validazione relaxNG sul documentoEsegue una validazione relaxNG sul documento in base allo schema RNG dato.
DOMDocument->relaxNGValidateSource() |
DOMDocument->schemaValidate() |
DOMDocument->schemaValidateSource() |
DOMDocument->validate() |
(no version information, might be only in CVS)
DOMDocument->relaxNGValidateSource() -- Esegue una validazione relaxNG sul documentoEsegue una validazione relaxNG sul documento in base alla sorgente RNG data.
DOMDocument->relaxNGValidate() |
DOMDocument->schemaValidate() |
DOMDocument->schemaValidateSource() |
DOMDocument->validate() |
(no version information, might be only in CVS)
DOMDocument->save() -- Scarica l'albero XML interno in un fileCrea un docuemnto XML dalla rappresentazione DOM. Usualmente questa funzione è chiamata dopo la creazione da zero di un nuovo documento DOM come nell'esempio seguente.
La funzione restituisce il numero di byte scritti, oppure FALSE in caso di errore.
Esempio 1. Salvataggio di un albero DOM in un file
|
(no version information, might be only in CVS)
DOMDocument->saveHTML() -- Dumps the internal document into a string using HTML formattingCreates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.
Esempio 1. Saving a HTML tree into a string
|
(no version information, might be only in CVS)
DOMDocument->saveHTMLFile() -- Dumps the internal document into a file using HTML formattingCreates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.
Esempio 1. Saving a HTML tree into a file
|
(no version information, might be only in CVS)
DOMDocument->saveXML() -- Dumps the internal XML tree back into a stringCreates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.
Use this parameter to output only a specific node without XML declaration rather than the entire document.
Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.
Esempio 1. Saving a DOM tree into a string
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
DOMDocument->schemaValidate() -- Validates a document based on a schemaValidates a document based on the given schema file.
DOMDocument->schemaValidateSource() |
DOMDocument->relaxNGValidate() |
DOMDocument->relaxNGValidateSource() |
DOMDocument->validate() |
(no version information, might be only in CVS)
DOMDocument->schemaValidateSource() -- Validates a document based on a schemaValidates a document based on a schema defined in the given string.
DOMDocument->schemaValidate() |
DOMDocument->relaxNGValidate() |
DOMDocument->relaxNGValidateSource() |
DOMDocument->validate() |
(no version information, might be only in CVS)
DOMDocument->validate() -- Valida il documento in base alla sua DTDValida il documento in base alla sua DTD.
Si può anche utilizzare la proprietà validateOnParse di DOMDocument per ottenere una validazione DTD.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. Se il documenti non ha una DTD collegata, questo metodo restituisce FALSE.
Esempio 1. Esempio di validazione con DTD
Si può anche validare il documento mentre lo si carica:
|
DOMDocument->schemaValidate() |
DOMDocument->schemaValidateSource() |
DOMDocument->relaxNGValidate() |
DOMDocument->relaxNGValidateSource() |
(no version information, might be only in CVS)
DOMDocument->xinclude() -- Sostituisce gli XIncludes in un oggetto DOMDocumentSostituisce gli XIncludes in un oggetto DOMDocument.
Nota: Poichè libxml2 risolve automaticamente le entità, quetso metodo può dare risultati inaspettati si il fil eXML incluso ha una DTD collegata.
Esempio 1. Esempio di uso di DOMDocument->xinclude()
Il precedente esempio visualizzerà qualcosa simile a:
|
(no version information, might be only in CVS)
DOMElement->__construct() -- Crea un nuovo oggetto DOMElementCrea un nuovo oggetto DOMElement. Questo oggetto è in sola lettura. Può essere aggiunto al documento, ma nodi addizionali non possono essere aggiunti a questo, fino a quando il nodo è associatoi al docuemnto. Per creare un nodo modificabile utilizzare DOMDocument->createElement() oppure DOMDocument->createElementNS().
Nome del tag dell'elemento. Quando si passa l'URI di uno spazio dei nomi, il nome dell'elemento può avere un prefisso per essere associato all'URI.
Valore dell'elemento.
URI dello spazio dei nomi, usato per creare l'elemento nello spazio dei nomi indicato.
Esempio 1. Creazione di un nuovo DOMElement
|
(no version information, might be only in CVS)
DOMElement->getAttribute() -- Restituisce il valore di un attributoRestituisce il valore dell'attributo con nome name per il nodo corrente.
La funzione restituisce il valore dell'attributo oppure una stringa vuota se non si trova alcun attributo con nome name.
(no version information, might be only in CVS)
DOMElement->getAttributeNode() -- Restituisce il nodo attributoRestituisce il nodo attributo con nome name per l'elemento corrente.
DOMElement->hasAttribute() |
DOMElement->setAttributeNode() |
DOMElement->removeAttributeNode() |
(no version information, might be only in CVS)
DOMElement->getAttributeNodeNS() -- Restituisce un nodo attributoRestituisce il nodo attributo cone nome localName nello spazio dei nomi namespaceURI per il nodo corrente.
DOMElement->hasAttributeNS() |
DOMElement->setAttributeNodeNS() |
DOMElement->removeAttributeNode() |
(no version information, might be only in CVS)
DOMElement->getAttributeNS() -- Restituisce il valore di un attributoRestituisce il valore dell'attributo con nome localName nello spazio dei nomi namespaceURI per il nodo corrente.
Il valore dell'attributo, oppure una stringa vuota nel caso in cui non si trovi un attributo con i dati localName e namespaceURI.
DOMElement->hasAttributeNS() |
DOMElement->setAttributeNS() |
DOMElement->removeAttributeNS() |
(no version information, might be only in CVS)
DOMElement->getElementsByTagName() -- Restituisce gli elementi in base al nome del tagQuesta funzione restituisce una nuova istanza della classe DOMNodeList contenente gli elementi i cui nomi di tag corrispondono al parametro name, nell'ordine in cui sono incontrati durante l'attraversamento dell'albero.
Il nome del tag. Utilizzare "*" per indicare di restituire tutti gli elementi del documento.
Questa funzione crea una nuova istanza della classe DOMNodeList contenente tutti gli elementi trovati.
(no version information, might be only in CVS)
DOMElement->getElementsByTagNameNS() -- Restituisce gli elementi per spazio dei nomi e nome localeQuesta funzione scarica tutti gli elementi con un dato localName e namespaceURI.
URI dello spazio dei nomi.
Nome locale. Utilizzare come nome "*" per restituire tutti gli elementi presenti nell'albero degli elementi.
Questa funzione crea una nuova istanza della classe DOMNodeList contenente tutti gli elementi trovati nell'ordine in cui sono incontrati durante l'atttraversamento dell'albero degli elementi.
(no version information, might be only in CVS)
DOMElement->hasAttribute() -- Verifica se l'attributo esisteIndica se l'attributo name esiste come menbro dell'elemento.
DOMElement->hasAttributeNS() |
DOMElement->getAttribute() |
DOMElement->setAttribute() |
DOMElement->removeAttribute() |
(no version information, might be only in CVS)
DOMElement->hasAttributeNS() -- Verifica se esiste l'attributoIndica se l'attributo nello spazio dei nomi namespaceURI con nome localName esiste come membro dell'elemento.
DOMElement->hasAttribute() |
DOMElement->getAttributeNS() |
DOMElement->setAttributeNS() |
DOMElement->removeAttributeNS() |
Rimuove l'attributo name dall'elemento.
Generato se il nodo non può essere modificato (in sola lettura).
(no version information, might be only in CVS)
DOMElement->removeAttributeNode() -- Rimuove gli attributiRimuove l'attributo oldnode dall'elemento.
Generato se il nodo è in sola lettura.
Generato se oldnode non è un attributo dell'elemento.
DOMElement->hasAttribute() |
DOMElement->getAttributeNode() |
DOMElement->setAttributeNode() |
(no version information, might be only in CVS)
DOMElement->removeAttributeNS() -- Rimuove gli attributiRimuove l'attributo localName nello spazio dei nomi namespaceURI dall'elemento.
(no version information, might be only in CVS)
DOMElement->setAttribute() -- Aggiunge un nuovo attributoImposta l'attributo con nome name al dato valore. Se l'attributo non esiste lo crea.
(no version information, might be only in CVS)
DOMElement->setAttributeNode() -- Aggiunge un nuovo nodo attributo all'elementoAggiunge un nuovo nodo attributo attr all'elemento.
DOMElement->hasAttribute() |
DOMElement->getAttributeNode() |
DOMElement->removeAttributeNode() |
(no version information, might be only in CVS)
DOMElement->setAttributeNodeNS() -- Aggiunge un nuovo nodo attributo all'elementoAggiunge un nuovo nodo attr all'elemento.
DOMElement->hasAttributeNS() |
DOMElement->getAttributeNodeNS() |
DOMElement->removeAttributeNode() |
(no version information, might be only in CVS)
DOMElement->setAttributeNS() -- Aggiunge un nuovo attributoImposta un attributo di nome name nello spazio dei nomi namespaceURI al valore dato. Se l'attributo non esiste viene creato.
URI dello spazio dei nomi.
Nome qualificato dell'attributo, nella forma prefisso:nometag.
Valore dell'attributo.
Generato se il nodo è in sola lettura.
Generato se qualifiedName è un nome qualificato malformato, oppure se qualifiedName ha un prefisso, ma namespaceURI è NULL.
DOMElement->hasAttributeNS() |
DOMElement->getAttributeNS() |
DOMElement->removeAttributeNS() |
(no version information, might be only in CVS)
DOMAttr->__construct() -- Crea un nuovo oggetto DOMEntityReferenceCrea un nuovo oggetto DOMEntityReference.
Esempio 1. Creazione di un nuovo DOMEntityReference
|
(no version information, might be only in CVS)
DOMImplementation->__construct() -- Crea un nuovo oggetto DOMImplementationCrea un nuovo oggetto DOMImplementation.
(no version information, might be only in CVS)
DOMImplementation->createDocument() -- Crea un oggetto DOMDocument del tipo indicato con il suo elemento documentoCrea un oggetto DOMDocument del tipo specificato, con l'elemento documento.
URI dello spazio dei nomi dell'elemento documento da creare.
Nome qualificato dell'elemento documento da creare.
Tipo del documento da creare oppure NULL.
Restituisce un nuovo oggetto DOMDocument. Se namespaceURI, qualifiedName, e doctype sono a null, l'oggetto DOMDocument restituito è vuoto, cioè privo dell'elemento documento.
Generato se doctype è già utilizzato in un documento differente oppure è stato creato con una differente implementazione.
Generato se esiste un errore nello spazio dei nomi indicato da namespaceURI e qualifiedName.
(no version information, might be only in CVS)
DOMImplementation->createDocumentType() -- Crea un oggetto DOMDocumentType vuotoCrea un oggetto DOMDocumentType vuoto. Le dichiarazioni delle entità e notazioni non sono disponibili. L'espansione delle entità e gli attributi di default non sono presenti.
Nome qualificato del tipo documento da creare.
Identificatore pubblico esterno.
Identificatore di sistema esterno.
Esempio 1. Creazione di un documento con una DTD collegata
Il precedente esempio visualizzerà:
|
Generato se vi è un errore nello spazio dei nomi indicato da qualifiedName.
(no version information, might be only in CVS)
DOMImplementation->hasFeature() -- Verifica se l'implementazione DOM ha una specifica caratteristicaVerifica se l'implementazione DOM ha una specifica feature.
Si può avere l'eleneco di tutte le caratteristiche alla sezione Conformance delle specifiche DOM.
Caratteristica da verificare.
Numero di versione della feature da verificare. Nel livello 2 questo parametro può valere 2.0 o 1.0.
Esempio 1. Verifica dell'implementazione DOM
|
(no version information, might be only in CVS)
DOMNamedNodeMap->getNamedItem() -- Recupera un nodo indicandone il nomeRecupera il nodo indicato da nodeName.
Il nodo (di qualsiasi tipo) con il nome richiesto, oppure NULL se non viene trovato.
(no version information, might be only in CVS)
DOMNamedNodeMap->getNamedItemNS() -- Recupera un nodo indicando il nome locale e l'URI dello spazio dei nomiRecupera il nodo indicato da localName e namespaceURI.
URI dello spazio dei nomi del nodo da cercare
Nome locale del nodo da cercare.
Un nodo (di qualsiasi tipo) con il nome locale ed l'URI dello spazio dei nomi richiesti, oppure NULL se non viene trovato nulla.
(no version information, might be only in CVS)
DOMNamedNodeMap->item() -- Recupera un nodo tramite il suo indiceRecupera un nodo tramite l'indice index all'interno dell'oggetto DOMNamedNodeMap.
Il nodo alla posizione indexnella tabella, oppure NULL se non si tratta di un indice valido (maggiore o uguale al numero dei nodi in questa tabella).
(no version information, might be only in CVS)
DOMNode->appendChild() -- Aggiunge un nuovo nodo figlio alla fine dei nodi figliQuesta funzione accoda un nodo figlio ad una lista esistente di nodi figlio oppure crea una nuova lista. Il nodo figlio può essere creato, ad esempio, con DOMDocument->createElement(), DOMDocument->createTextNode() ecc. oppure semplicemente utilizzando un'altro nodo.
Generato se questo nodo è in sola lettura, oppure se il nodo genitore del nodo da inserire è in sola lettura.
Generato se questo nodo è del tipo che non ammette figli del tipo di newnode, oppure se il nodo da aggiungere è uno dei genitori del nodi o di se stesso.
Generato se newnode è stato creato in un documento differente rispetto al nodo che crea questo.
Indica se occorre copiare tutti i nodi sottostanti. Questo parametro, opzionale, ha come default FALSE.
(no version information, might be only in CVS)
DOMNode->hasAttributes() -- Verifica se un nodo ha degli attributiQuesta funzione verifica se un nodo ha degli attributi. Il nodo verificato deve essere di tipo XML_ELEMENT_NODE.
(no version information, might be only in CVS)
DOMNode->hasChildNodes() -- Verifica se un nodo ha nodi figliQuesta funzione verifica se un nodo ha nodi figli.
(no version information, might be only in CVS)
DOMNode->insertBefore() -- Aggiunge un nuovo nodo figlio prima del riferimentoQuesta funzione inserisce un nuovo nodo prima del nodo di riferimento. Se si prevede di fare ulteriori aggiunte al nodo aggiunto, utilizzare il nodo restituito.
Il nuovo nodo.
Nodo di riferimento. Se non viene fornito, newnode viene accodato ai nodi figli.
Generato se il nodo è in sola lettura o se il precedente nodo padre del nodo da aggiungere è in sola lettura.
Generato se questo nodo è di un tipo che non permette l'aggiunta di nodi figli del tipo di newnode, o se il nodo da aggiungere è uno dei genitori di questo nodo, oppure se si tratta proprio di questo nodo.
Generato se newnode è stato creato in un docuemnto differente rispetto al documento in cui è sttao creato questo nodo.
Generato se refnode non è un nodo figlio di questo nodo.
(no version information, might be only in CVS)
DOMNode->isSameNode() -- Indica se due nodi sono il medesimo nodoQuesta funzione indica se due nodi sono il medesimo nodo. Il confronto NON è basato sul contenuto.
(no version information, might be only in CVS)
DOMNode->isSupported() -- Verifica se una caratteristica è supportata dalla versione indicataVerifica se una feature è supportata dalla version indicata.
Caratteristica da verificare. Vedere l'esempio di DOMImplementation->hasFeature() per avere l'elenco delle caratteristiche.
Numero di versione della feature da verificare.
(no version information, might be only in CVS)
DOMNode->lookupNamespaceURI() -- Restituisce l'URI dello spazio dei nomi in base al prefissoRestituisce l'URI dello spazio dei nomi del nodo in base al prefisso prefix.
(no version information, might be only in CVS)
DOMNode->lookupPrefix() -- Resituisce il prefisso dello spazio dei nomi in base all'URI dello spazio dei nomiResituisce il prefisso dello spazio dei nomi in base all'URI dello spazio dei nomi.
(no version information, might be only in CVS)
DOMNode->removeChild() -- Rimuove un nodo figlio dalla lista dei nodi figliQuesta funzione rimuove un nodo figlio dalla lista dei nodi figli.
Se si riesce a rimuovere il nodo figlio, la funzione restituisce il vecchio nodo figlio.
Generato se il nodo è in sola lettura.
Generato se oldnode non è un figlio di questo nodo.
Nel seguente esempio si rimuoverà il nodo 'chapter' dal nostro documento XML.
Esempio 1. Rimozione di un nodo figlio
Il precedente esempio visualizzerà:
|
Questa funzione sostituisce il nodo figlio oldnode con il nuovo nodo fornito. Se il nuovo nodo è già un nodo figlio, questo non verrà inserito una seconda volta. Se la sostituzione ha avuto successo, la funzione restituisce il vecchio nodo.
Il nuovo nodo. Deve essere membro del docuemnto di destinazione, ad esempio creato da uno dei metodi DOMDocument->createXXX() oppure importato nel documento con DOMDocument->importNode().
Il vecchio nodo.
Generato se questo nodo è in sola lettura oppure se il precdente padre del nodo da inserire è in sola lettura.
Generato se il nodo è di un tipo che non ammette nodi figli del tipo di newnode, oppure se il nodo da inserire è uno dei padri del nodo, oppure se è il nodo stesso.
Generato se newnode è stato creato in un docuemnto differente rispetto al documento in cui è stato creato il nodo.
Generato se oldnode non è figlio del nodo.
(no version information, might be only in CVS)
DOMNodelist->item() -- Recupera il nodo indicato dall'indiceTrova il nodo indicato dall'indice index all'interno di un oggetto DOMNodeList.
Suggerimento: Se occorre conoscere il numero di nodi di una collezzione utilizzare la prorpietà length dell'oggetto DOMNodeList.
Il nodo alla posizione index in DOMNodeList, oppure NULL se non è un indice valido.
Esempio 1. Attraversamento di tutti gli elementi di una tabella
Oppure si può utilizzare foreach, che è molto pratico:
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
DOMProcessingInstruction->__construct() -- Crea un nuovo oggetto DOMProcessingInstructionCrea un nuovo oggetto DOMProcessingInstruction. Questo oggetto è in sola lettura. Può essere aggiunto al documento, ma non possono essere inseriti nodi aggiuntivi fino a quando il nodo è associato al documento. Per creare un nodo modificabile utilizzare DOMDocument->createProcessingInstruction().
Nome del tag dell'istruzione di processamento.
Valore dell'istruzione di processamento.
Esempio 1. Creazione di un nuovo DOMProcessingInstruction
|
(no version information, might be only in CVS)
DOMText->__construct() -- Crea un nuovo oggetto DOMText
Valore del nodo di testo. Se non fornito, sarà creato un nodo con il testo vuoto.
Esempio 1. Creazione di un nuovo DOMText
|
(no version information, might be only in CVS)
DOMText->isWhitespaceInElementContent() -- Indica se questo nodo di testo contiene spaziIndica se questo nodo di testo contiene spazi. Si determina se un nodo di testo contiene spazi durante la fase di caricamento del documento.
(no version information, might be only in CVS)
DOMText->splitText() -- Spezza il nodo in due all'offset specificatoSpezza questo nodo in due all'offset indicato, mantenendo entrambi nell'albero come nodi fratelli.
Dopo la divisione, questo nodo conterrà tutto il testo fino a offset. Se il nodo originale ha un nodo genitore, allora il nuovo nodo sarà inserito come successivo al nodo originale. Nel caso in cui offset sia uguale alla lunghezza del nodo, il nuovo nodo non conterrà dati.
(no version information, might be only in CVS)
DOMXPath->__construct() -- Crea un nuovo oggetto DOMXPath(no version information, might be only in CVS)
DOMXPath->evaluate() -- Valuta l'espressione XPath data e restituisce un risultato se possibileEsegue l'espressione XPath data e restituisce un risultato se possibile
L'espressione XPath da eseguire.
Il parametro opzinale contextnode serve per indicare di eseguire query XPath relative. Per default le query sono relative all'elemento radice.
Restituisce un risultato oppure un oggetto DOMNodeList contenente tutti i nodi che soddisfano la query XPath .
Esempio 1. Ottenere il numero dei libri inglesi
Il precedente esempio visualizzerà:
|
Esegue la query XPath data.
La query XPath da eseguire.
Il parametro opzinale contextnode serve per indicare di eseguire query XPath relative. Per default le query sono relative all'elemento radice.
Restituisce un oggetto DOMNodeList contenente tutti i nodi che soddisfano la condizione expression. Qualsiasi espressione che non restituisce nodi creerà un DOMNodeList vuoto.
Esempio 1. Ottenere il numero dei libri inglesi
Il precedente esempio visualizzerà:
Possiamo utilizzare il parametro contextnode per ridurre l'espressione:
|
(no version information, might be only in CVS)
DOMXPath->registerNamespace() -- Registra lo spazio dei nomi nell'oggetto DOMXpathRegistra lo spazio dei nomi namespaceURI e prefix nell'oggetto DOMXpath.
Questa funzione prende il nodo node della classe SimpleXML e lo converte in un nodo DOMElement. Questo nuovo oggetto può essere utilizzato come nodo DOMElement nativo.
Esempio 1. Importare SimpleXML nel DOM con dom_import_simplexml()
|
Nella versione 4.3.0 di PHP l'estensione DOM XML è stata rivista in modo da fornire una migliore adesione allo standard DOM. Il modulo contiene ancora diverse vecchie funzioni, ma non dovrebbero essere più usate. Specialmente quelle funzioni non orientate agli oggetti.
Questo modulo permette di operare con un documento XML utilizzando API DOM. Inoltre viene fornita una funzione, domxml_xmltree(), per convertire l'intero documento XML in un albero di oggetti PHP. Attualmente questo albero dovrebbe essere considerato di sola lettura, è possibile modificarlo, ma questa operazione non avrebbe senso dato che la funzione DomDocument_dump_mem() non può essere applicata all'albero. Pertanto se si desidera leggere un file XML e scriverne una versione modificata, occorre utilizzare le funzioni DomDocument_create_element(), DomDocument_create_text_node(), set_attribute(), ecc. ed infine DomDocument_dump_mem().
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.0.0.
Questo modulo utilizza la libreria GNOME XML library. Fare il download ed installare questa libreria. Occorre avere almeno la libxml-2.4.14. Per potere utilizzare le caratteristiche previste nel DOM XSLT occorre utilizzare libxslt library ed EXSLT enhancements da http://www.exslt.org/. Scaricare ed installare queste librerie se si prevede di utilizzare la funzioni avanzate di XSLT. Occorre almeno la versione libxslt-1.0.18.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/domxml.
In PHP 4 this PECL extensions source can be found in the ext/ directory within the PHP source or at the PECL link above. Questo modulo è disponibile soltanto se il PHP è stato configurato con --with-dom=[DIR]. Aggiungere --with-dom-xslt[=DIR] per includere il supporto al DOM XSLT support. DIR indica la directory in cui è installato libxslt. Aggiungere --with-dom-exslt[=DIR] per includere il supporto al DOM EXSLT, dove DIR indica la directory in cui è installato libexslt.
Gli utenti Windows devono abilitare php_domxml.dll dal php.ini per potere utilizzare queste funzioni. In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/. Inoltre, per potere utilizzare queste funzioni, occorre che una DLL aggiuntiva sia presente nella PATH del sistema. In PHP 4 questa DLL si trova nella directory dlls/. Il suo nome: Per PHP <= 4.2.0, è libxml2.dll. Per PHP >= 4.3.0, è iconv.dll. E dal PHP 5.0.0 iconv è compilata nell'eseguibile PHP per Windows, percui non vi è più bisogno di dll aggiuntive.
Esistono alcune funzioni che non rientrano nello standard DOM e quindi non dovrebbero essere più utilizzate come evidenziato nella tabella seguente. La funzione DomNode_append_child() ha modificato il suo comportamento. Attualmente aggiunge un figlio e non un elemento fratello. Se ciò crea problemi alle applicazioni si può usare la funzione non DOM
Tabella 1. Funzioni deprecate e loro sostituti
Vecchia funzione | Nuova funzione |
---|---|
xmldoc | domxml_open_mem() |
xmldocfile | domxml_open_file() |
domxml_new_xmldoc | domxml_new_doc() |
domxml_dump_mem | DomDocument_dump_mem() |
domxml_dump_mem_file | DomDocument_dump_file() |
DomDocument_dump_mem_file | DomDocument_dump_file() |
DomDocument_add_root | DomDocument_create_element() seguita da DomNode_append_child() |
DomDocument_dtd | DomDocument_doctype() |
DomDocument_root | DomDocument_document_element() |
DomDocument_children | DomNode_child_nodes() |
DomDocument_imported_node | Nessun sostituto. |
DomNode_add_child | Creare un nuovo nodo con, ad esempio, DomDocument_create_element() e aggiungere il figlio con DomNode_append_child(). |
DomNode_children | DomNode_child_nodes() |
DomNode_parent | DomNode_parent_node() |
DomNode_new_child | Creare un nuovo nodo con, ad esempio, DomDocument_create_element() e aggiungere il figlio con DomNode_append_child(). |
DomNode_get_content | Il contenuto è semplicemente un nodo di testo ed è accessibile tramite DomNode_child_nodes(). |
DomNode_set_content | Il contenuto è semplicemente un nodo di testo e può essere aggiunto con DomNode_append_child(). |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 2. Costanti XML
Costante | Valore | Descrizione |
---|---|---|
XML_ELEMENT_NODE (integer) | 1 | Il nodo è un elemento |
XML_ATTRIBUTE_NODE (integer) | 2 | Il nodo è un attributo |
XML_TEXT_NODE (integer) | 3 | Il nodo è un segmento di testo |
XML_CDATA_SECTION_NODE (integer) | 4 | |
XML_ENTITY_REF_NODE (integer) | 5 | |
XML_ENTITY_NODE (integer) | 6 | Il nodo è un'entità come, ad esempio, |
XML_PI_NODE (integer) | 7 | Il nodo è una istruzione di processamento |
XML_COMMENT_NODE (integer) | 8 | Il nodo è un commento |
XML_DOCUMENT_NODE (integer) | 9 | Il nodo è un documento |
XML_DOCUMENT_TYPE_NODE (integer) | 10 | |
XML_DOCUMENT_FRAG_NODE (integer) | 11 | |
XML_NOTATION_NODE (integer) | 12 | |
XML_GLOBAL_NAMESPACE (integer) | 1 | |
XML_LOCAL_NAMESPACE (integer) | 2 | |
XML_HTML_DOCUMENT_NODE (integer) | ||
XML_DTD_NODE (integer) | ||
XML_ELEMENT_DECL_NODE (integer) | ||
XML_ATTRIBUTE_DECL_NODE (integer) | ||
XML_ENTITY_DECL_NODE (integer) | ||
XML_NAMESPACE_DECL_NODE (integer) | ||
XML_ATTRIBUTE_CDATA (integer) | ||
XML_ATTRIBUTE_ID (integer) | ||
XML_ATTRIBUTE_IDREF (integer) | ||
XML_ATTRIBUTE_IDREFS (integer) | ||
XML_ATTRIBUTE_ENTITY (integer) | ||
XML_ATTRIBUTE_NMTOKEN (integer) | ||
XML_ATTRIBUTE_NMTOKENS (integer) | ||
XML_ATTRIBUTE_ENUMERATION (integer) | ||
XML_ATTRIBUTE_NOTATION (integer) | ||
XPATH_UNDEFINED (integer) | ||
XPATH_NODESET (integer) | ||
XPATH_BOOLEAN (integer) | ||
XPATH_NUMBER (integer) | ||
XPATH_STRING (integer) | ||
XPATH_POINT (integer) | ||
XPATH_RANGE (integer) | ||
XPATH_LOCATIONSET (integer) | ||
XPATH_USERS (integer) | ||
XPATH_NUMBER (integer) |
Le API di questo modulo aderiscono il più possibile allo standard DOM di livello 2. Di conseguenza le API sono completamente orientate agli oggetti. Si ritiene una buona idea avere disponibile lo standard DOM quando si utilizza questo modulo. Sebbene le API siano orientate agli oggetti, vi sono alcune funzioni che possono essere richiamate in modo non orientato agli oggetti, passando l'oggetto su cui operare come primo argomento. Queste funzioni sono state mantenute per compatibilità verso le vecchie versioni del modulo, ma non se ne incoraggia l'uso nello sviluppo di nuovi prodotti.
Queste API differiscono della API DOM ufficiali per due aspetti. Primo, gli attributi della classe sono implermentati come funzioni con il medesimo nome e, secondo, i nomi delle funzioni seguono la convenzione del PHP. Questo significa che la funzione DOM lastChild() sarà chiamata last_child().
In questo modulo sono definite diverse classi, queste saranno elencate - compresi i loro metodi - nella seguente tabella. Le classi con un equivalente nello standard DOM sono chiamate DOMxxx.
Tabella 3. Elenco delle classi
Nome della classe | Classe genitrice |
---|---|
DomAttribute | DomNode |
DomCData | DomNode |
DomComment | DomCData : DomNode |
DomDocument | DomNode |
DomDocumentType | DomNode |
DomElement | DomNode |
DomEntity | DomNode |
DomEntityReference | DomNode |
DomProcessingInstruction | DomNode |
DomText | DomCData : DomNode |
Parser | Attualmente chiamata DomParser |
XPathContext |
Tabella 4. Classe DomDocument (DomDocument : DomNode)
Metodi | Funzioni | Note |
---|---|---|
doctype | DomDocument_doctype() | |
document_element | DomDocument_document_element() | |
create_element | DomDocument_create_element() | |
create_text_node | DomDocument_create_text_node() | |
create_comment | DomDocument_create_comment() | |
create_cdata_section | DomDocument_create_cdata_section() | |
create_processing_instruction | DomDocument_create_processing_instruction() | |
create_attribute | DomDocument_create_attribute() | |
create_entity_reference | DomDocument_create_entity_reference() | |
get_elements_by_tagname | DomDocument_get_elements_by_tagname() | |
get_element_by_id | DomDocument_get_element_by_id() | |
dump_mem | DomDocument_dump_mem() | non standard DOM |
dump_file | DomDocument_dump_file() | non standard DOM |
html_dump_mem | DomDocument_html_dump_mem() | non standard DOM |
xpath_init | xpath_init | non standard DOM |
xpath_new_context | xpath_new_context | non standard DOM |
xptr_new_context | xptr_new_context | non standard DOM |
Tabella 5. Classe DomElement (DomElement : DomNode)
Metodo | Funzioni | Note |
---|---|---|
tagname | DomElement_tagname() | |
get_attribute | DomElement_get_attribute() | |
set_attribute | DomElement_set_attribute() | |
remove_attribute | DomElement_remove_attribute() | |
get_attribute_node | DomElement_get_attribute_node() | |
get_elements_by_tagname | DomElement_get_elements_by_tagname() | |
has_attribute | DomElement_has_attribute() |
Tabella 6. Classe DomNode
Metodo | Note |
---|---|
DomNode_node_name() | |
DomNode_node_value() | |
DomNode_node_type() | |
DomNode_last_child() | |
DomNode_first_child() | |
DomNode_child_nodes() | |
DomNode_previous_sibling() | |
DomNode_next_sibling() | |
DomNode_parent_node() | |
DomNode_owner_document() | |
DomNode_insert_before() | |
DomNode_append_child() | |
DomNode_append_sibling() | non standard DOM. Questa funzione emula il comportamento di DomNode_append_child(). |
DomNode_remove_child() | |
DomNode_has_child_nodes() | |
DomNode_has_attributes() | |
DomNode_clone_node() | |
DomNode_attributes() | |
DomNode_unlink_node() | non standard DOM |
DomNode_replace_node() | non standard DOM |
DomNode_set_content() | non standard DOM, deprecata |
DomNode_get_content() | non standard DOM, deprecata |
DomNode_dump_node() | non standard DOM |
DomNode_is_blank_node() | non standard DOM |
Tabella 7. Classe DomAttribute (DomAttribute : DomNode)
Metodo | Note | |
---|---|---|
name | DomAttribute_name() | |
value | DomAttribute_value() | |
specified | DomAttribute_specified() |
Tabella 8. Classe DomProcessingInstruction (DomProcessingInstruction : DomNode)
Metodo | Funzione | Note |
---|---|---|
target | DomProcessingInstruction_target() | |
data | DomProcessingInstruction_data() |
Tabella 10. Classe XPathContext
Metodo | Funzione | Note |
---|---|---|
eval | XPathContext_eval() | |
eval_expression | XPathContext_eval_expression() | |
register_ns | XPathContext_register_ns() |
Tabella 11. Classe DomDocumentType (DomDocumentType : DomNode)
Metodo | Funzione | Note |
---|---|---|
name | DomDocumentType_name() | |
entities | DomDocumentType_entities() | |
notations | DomDocumentType_notations() | |
public_id | DomDocumentType_public_id() | |
system_id | DomDocumentType_system_id() | |
internal_subset | DomDocumentType_internal_subset() |
La classe DomDtd è derivata da DomNode. Mentre DomComment è derivata da DomCData
Diversi esempi presenti in questo manuale richiedono un testo XML. Anzichè ripetere questo testo in ogni esempio, si inserirà il testo in un file che verrà incluso in ogni esempio. Questo file di include verrà illustrato nel seguente esempio. Si può anche creare un documento XML e leggerlo con DomDocument_open_file().
Esempio 1. File di include example.inc con testo XML
|
(no version information, might be only in CVS)
DomAttribute->name -- Restituisce il nome di un attributoLa funzione restituisce il nome di un attributo.
Vedere anche domattribute_value() per un esempio.
(no version information, might be only in CVS)
DomAttribute->set_value -- Sets the value of an attributeThis function sets the value of an attribute.
(no version information, might be only in CVS)
DomAttribute->specified -- Verifica se l'attributo è presenteRifarsi allo standard DOM per una descrizione dettagliata.
(no version information, might be only in CVS)
DomAttribute->value -- Restituisce il valore di un attributoQuesta funzione restituisce il valore di un attributo.
Esempio 1. Ottenere tutti gli attributi di un nodo
Il precedente esempio visualizzerà:
|
Vedere anche domattribute_name().
(no version information, might be only in CVS)
DomDocument->add_root -- Aggiunge un nodo radice [deprecated]Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Aggiunge un nodo radice ad un documento DOM e restituisce il nuovo nodo. Il nome dell'elemento viene passato come parametro.
(no version information, might be only in CVS)
DomDocument->create_attribute -- Crea un nuovo attributoQuesta funzione restituisce una nuova istanza della classe DomAttribute. Il nome dell'attributo viene passato come primo parametro. Mentre il valore viene passato nel secondo parametro. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_processing_instruction(), domdocument_create_entity_reference() e domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->create_cdata_section -- Crea un nuovo nodo cdataQuesta funzione restituisce una nuova istanza della classe DomCData. Il contenuto del nodo cdata viene passato tramite il parametro. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference() e domnode_insert_before().
Questa funzione restituisce una nuova istanza della classe DomComment. Il contenuto del commento viene fornito tramite il parametro. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference() e domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->create_element_ns -- Crea un nodo elemento con il relativo spazio dei nomiQuesta funzione restituisce una nuova istanza della classe DomElement. Il nome del tag dell'elemento viene fornito tramite il parametro nome. L'URI dello spazio dei nomi vene passato tramite il parametro uri. Se nel nodo radice del documento esiste già uno spazio dei nomi con il medesimo URI, si utilizza il prefisso di questo, altrimenti si utilizzerà quello fornito tramite il parametro opzionale prefix oppure ne verrà generato uno casuale. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domdocument_create_element_ns(), domnode_add_namespace(), domnode_set_namespace(), domnode_append_child(), domdocument_create_text(), domdocument_create_comment(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference() e domnode_insert_before().
La funzione restituisce una nuova istanza della classe DomElement. Il nome del tag dell'elemento viene passato tramite il parametro. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domdocument_create_element_ns(), domnode_append_child(), domdocument_create_text(), domdocument_create_comment(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference() e domnode_insert_before().
Questa funzione restituisce una nuova istanza della classe DomEntityReference. Il contenuto dell'entità è passato tramite il parametro. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_processing_instruction(), domdocument_create_attribute() e domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->create_processing_instruction -- Crea un nuovo nodo PIQuesta funzione restituisce una nuova istanza della classe DomCData. Il contenuto della PI viene passato tramite il parametro.Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_attribute(), domdocument_create_entity_reference() e domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->create_text_node -- Crea un nodo di testoQuesta funzione restituisce una nuova istanza della classe DomText. Il testo del nodo viene passato tramite il parametro. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domnode_append_child(), domdocument_create_element(), domdocument_create_comment(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference() e domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->doctype -- Restituisce il tipo di documentoQuesta funzione restituisce una nuova istanza della classe DomDocumentType. Nelle versioni di PHP antecedenti al 4.3 questa classe era chiamata Dtd, ma lo standard DOM non riconosce tale classe.
Vedere anche i metodi della classe DomDocumentType.
(no version information, might be only in CVS)
DomDocument->document_element -- Restituisce il nodo radiceQuesta funzione restituisce il nodo radice di un documento.
Nell'esempio seguente la funzione restituisce l'elemento con nome CHAPTER. L'altro nodo -- the comment -- non viene restituito.
Esempio 1. Recupero dell'elemento radice
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
DomDocument->dump_file -- Scarica in un file l'albero XML internoLa funzione crea un documento XML dalla rappresentazione DOM. Solitamente questa funzione viene richiamata dopo avere creato da zero un nuovo documento XML, come nell'esempio seguente. Il parametro formato specifica se l'output debba essere ben formattato o meno. Il primo parametro specifica il nome del file ed il secondo se debba essere compresso o meno.
Esempio 1. Creazione dell'intestazione di un documento HTML
|
Vedere anche domdocument_dump_mem() e domdocument_html_dump_mem().
(no version information, might be only in CVS)
DomDocument->dump_mem -- Scarica in una stringa la struttura XML internaAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
La funzione crea un docuemnto XML dalla rappresentazione DOM. Solitamente si richiama questa funzione dopo avere creato un nuovo documento DOM da zero, come nell'esempio seguente. Il parametro formato specifica se l'output debba essere ben formattato o meno.
Esempio 1. Creazione dell'intestazione di un documento HTML
|
Nota: Il primo parametro è stato inserito nella versione 4.3.0 di PHP.
Vedere anche domdocument_dump_file() e domdocument_html_dump_mem().
(no version information, might be only in CVS)
DomDocument->get_element_by_id -- Ricerca di un elemento per idQuesta funzione è simile a domdocument_get_elements_by_tagname() ma ricerca un elemento per un dato id. In accordo con lo standard DOM, è richiesto un DTD che definisca l'attributo ID essere di tipo ID, sebbene l'implementazione corrente ricerchi semplicemente il testo "//*[@ID = '%s']". Ciò non è aderente allo standard DOM che richiede di restituire null se non è noto quale sia l'attributo di tipo id. Questo comportamento sta per essere corretto, pertanto non basarsi sull'implementazione odierna.
Vedere anche domdocument_get_elements_by_tagname()
(no version information, might be only in CVS)
DomDocument->get_elements_by_tagname -- Restituisce un elemento dato il tag
Vedere anche domdocument_add_root()
(no version information, might be only in CVS)
DomDocument->html_dump_mem -- Scarica la struttura XML interna in una stringa come HTMLLa funzione crea un documento HTML dalla rappresentazione DOM. Solitamente si richiama questa funzione dopo avere costruito un nuovo documento DOM da zero, come nell'esempio seguente.
Esempio 1. Creazione dell'intestazione di un documento HTML
Il precedente esempio visualizzerà:
|
Vedere anche domdocument_dump_file() e domdocument_html_dump_mem().
(no version information, might be only in CVS)
DomDocument->xinclude -- Sostituisce gli XIncludes in un oggetto DomDocumentAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Questa funzione sostituisce gli XIncludes in un oggetto DomDocument.
Esempio 1. Sostituzione di Xinclude
Il precedente esempio visualizzerà:
Se include.xml non esiste si avrà::
|
(no version information, might be only in CVS)
DomDocumentType->entities -- Restituisce l'elenco delle entità
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomDocumentType->internal_subset -- Restituisce un subset interno
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomDocumentType->name -- Restituisce il nome del tipo documentoQuesta funzione restituisce il nome del tipo documento.
(no version information, might be only in CVS)
DomDocumentType->notations -- Restituisce la lista delle notazioni
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomDocumentType->public_id -- Restituisce l'identificatore pubblico del tipo documentoQuesta funzione restituisce l'identificatore pubblico del tipo documento.
Il seguente esempio non visualizza niente.
(no version information, might be only in CVS)
DomDocumentType->system_id -- Restituisce l'identificativo di sistema del tipo documentoRestituisce l'identificativo di sistema del tipo documento.
Esempio 1. Recupero dell'identificativo di sistema
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
DomElement->get_attribute_node -- Restituisce il nodo dell'attributo datoRestituisce il nodo dell'attributo indicato da name nell'elemento corrente. Il parametro name distingue tra minuscole e maiuscole.
Se non si trova alcun attributo con il nome dato, la funzione restituisce FALSE
Esempio 1. Ottenere un nodo attributo
|
(no version information, might be only in CVS)
DomElement->get_attribute -- Restituisce il valore di un attributoLa funzione restituisce l'attributo chiamato nome del nodo corrente.
(PHP >= 4.3 solo) Se non si trova alcun attributo con il nome dato, la funzione restituisce una stringa vuota.
Vedere anche domelement_set_attribute()
(no version information, might be only in CVS)
DomElement->get_elements_by_tagname -- Restituisce l'elemento con il tag datoQuesta funzione restituisce un array con tutti gli elementi che hanno come nome del tag nome. Ogni elemento dell'array è un oggetto DomElement.
Esempio 1. Ottenere il contenuto
|
(no version information, might be only in CVS)
DomElement->has_attribute -- Verifica l'esistenza dell'attributo
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Imposta l'attributo chiamato nome al valore fornito. Se l'attributo non esiste lo crea.
Vedere anche domelement_get_attribute()
(no version information, might be only in CVS)
DomElement->tagname -- Restituisce il nome dell'elemento correnteReturns the name of the current node. Chiamare questa funzione è come accedere alla proprietà tagname del nodo corrente, o chiamare DomElement->node_name().
(no version information, might be only in CVS)
DomNode->add_namespace -- Aggiunge la dichiarazione dello spazio dei nomi ad un nodo
Vedere anche domdocument_create_element_ns() e domnode_set_namespace()
Questa funzione accoda un nodo figlio ad un elenco pre-esistente di figli oppure crea una nuova lista di figli. Il nodo figlio può essere creato con funzioni tipo domdocument_create_element(), domdocument_create_text() ecc. oppure usando un qualsiasi altro nodo.
(PHP < 4.3) Prima che sia aggiunto un nuovo nodo questo viene duplicato. Quindi il nuovo nodo è una nuova copia che può essere modificata senza variare il nodo passato alla funzione. Se il nodo ha dei nodi figli, anche questi saranno duplicati, ciò rende facile duplicare grandi parti di un documento XML. Il valore restituito è il nodo figlio accodato. Se si prevede di fare ulteriori modifiche al nodo aggiunto, occorre usare il nodo restituito.
(PHP 4.3.0/4.3.1) Il nuovo nodo figlio nuovo_nodo viene prima rimosso dal contesto esistente, se ne è già un figlio di DomNode. Quindi viene mosso e non più copiato.
(PHP >= 4.3.2) Il nuovo nodo figlio nuovo_nodo viene prima rimosso dal contesto esistente, se ne esiste uno nel documento. Quindi viene mosso e non più copiato. Questo comportamento si attiene alle specifiche W3C. Se si desidera duplicare una grande parte di un documento XML, occorre utilizzare DomNode->clone_node() prima di accodare il nodo.
Nel seguente esempio si accoderà un nuovo nodo ad un documento e si imposterà l'attributo "align" a "left".
Esempio 3. Aggiunta di un nodo figlio
|
Vedere anche domnode_insert_before() e domnode_clone_node().
Questa funzione aggiunge un nodo di pari livello rispetto ad un nodo esistente. Il nodo figlio può essere creato con funzioni del tipo domdocument_create_element(), domdocument_create_text() ecc. oppure utilizzando un'altro nodo.
Prima dell'aggiunta come nuovo nodo fratello, il nodo viene duplicato. Quindi il nuovo nodo figlio è una nuova copia dell'originale e pertanto, può essere modificato senza modificare il nodo di partenza passato alla funzione. Se il nodo fornito, a sua volta, ha dei nodi figli, pure questi saranno duplicati, in questo modo è abbastanza semplice duplicare grandi parti di un documento XML. La funzione restituisce il nodo aggiunto. Se in seguito occorre modificare il nodo fratello che si è aggiunto, occorre utilizzare il nodo restituito.
Questa funzione è stata aggiunta per replicare il comportamento di domnode_append_child() che si ha fino alla versione 4.2 di PHP.
Vedere anche domnode_append_before().
(no version information, might be only in CVS)
DomNode->attributes -- Restituisce la lista degli attributiQuesta funzione restituisce la lista degli attributi se il nodo è di tipo XML_ELEMENT_NODE.
(PHP >= 4.3 solo) Se non si trovano attributi, la funzione restituisce NULL.
(no version information, might be only in CVS)
DomNode->child_nodes -- Restituisce i figli di un nodoRestituisce tutti i nodi figlio del nodo.
Vedere anche domnode_next_sibling() e domnode_previous_sibling().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche domdocument_dump_mem().
(no version information, might be only in CVS)
DomNode->first_child -- Restituisce il primo nodo figlioRestituisce il primo nodo figlio.
(PHP >= 4.3 solo) Se non si trova il primo figlio, si restituisce NULL.
Vedere anche domnode_last_child(), domnode_next_sibling() e domnode_previous_sibling().
(no version information, might be only in CVS)
DomNode->get_content -- Restituisce il contenuto del nodoQuesta funzione restituisce il contenuto del nodo
Esempio 1. Ottenere il contenuto di un nodo
|
(no version information, might be only in CVS)
DomNode->has_attributes -- Verifica se il nodo ha attributiQuesta funzione verifica se il nodo ha attributi.
Vedere anche domnode_has_child_nodes().
(no version information, might be only in CVS)
DomNode->has_child_nodes -- Verifica se esistono nodi figlioQuesta funzione verifica se il nodo ha nodi figlio.
Vedere anche domnode_child_nodes().
(no version information, might be only in CVS)
DomNode->insert_before -- Inserisce un nuovo nodo come figlioQuesta funzione inserisce il nuovo_nodo a destra rispetto al nodo_riferimento. La funzione restituisce il nodo inserito. Occorre utilizzare questo valore se si intende apportare nuove modifiche al nodo appena accodato.
(PHP >= 4.3 solo) Se nuovo_nodo è già parte del documento, prima questo verrà scollegato dal contesto esistente. Se nodo_riferimento vale NULL, allora nuovo_nodo sarà inserito alla fine della lista dei nodi figlio.
La funzione domnode_insert_before() è molto simile a domnode_append_child() come illustrato nel seguente esempio nel quale si ha lo stesso comportamento visto nell'esempio di domnode_append_child().
Esempio 1. Aggiunta di un nodo figlio
|
Vedere anche domnode_append_child().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomNode->last_child -- Restituisce l'ultimo nodo figlio del nodoRestituisce l'ultimo nodo figlio del nodo.
(PHP >= 4.3 solo) Se non si trova l'ultimo figlio, si restituisce NULL.
Vedere anche domnode_first_child(), domnode_next_sibling() e domnode_previous_sibling().
(no version information, might be only in CVS)
DomNode->next_sibling -- Restituisce il successivo fratello del nodoRestituisce il nodo di pari livello successivo al nodo corrente. Se non ci sono nodi successivi la funzione restituisce FALSE (< 4.3) oppure null (>= 4.3). Si può utilizzare questa funzione per passare in rassegna tutti i figli di un nodo, come illustrato nell'esempio.
Esempio 1. Rassegna dei nodi figlio
|
Vedere anche domnode_previous_sibling().
Restituisce il nome del nodo. Il nome ha diversi significati per i differenti tipi di nodi, come sarà illustrato nella tabella seguente.
Tabella 1. Significato dei valori
Tipo | Significato |
---|---|
DomAttribute | valori di attributo |
DomAttribute | |
DomCDataSection | #cdata-section |
DomComment | #comment |
DomDocument | #document |
DomDocumentType | nome del tipo documento |
DomElement | nome tag |
DomEntity | nome di entittà |
DomEntityReference | nome di entità di riferimento |
DomNotation | nome della notazione |
DomProcessingInstruction | target |
DomText | #text |
La funzione restituisce il tipo di nodo. L'elenco di tutti i tipi possibili sono elencati in una tabella nell'introduzione.
Esempio 1.
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
DomNode->node_value -- Restituisce il valore di un nodoLa funzione restituisce il valore di un nodo. Il valore ha diversi significati per i diversi tipi di nodi, come illustrato nella seguente tabella.
Tabella 1. Significato dei valori
Tipo | Significato |
---|---|
DomAttribute | valori di un attributo |
DomAttribute | |
DomCDataSection | contenuto |
DomComment | contenuto del commento |
DomDocument | null |
DomDocumentType | null |
DomElement | null |
DomEntity | null |
DomEntityReference | null |
DomNotation | null |
DomProcessingInstruction | l'intero contenuto senza destinatario |
DomText | contenuto del testo |
(no version information, might be only in CVS)
DomNode->owner_document -- Restituisce il documento a cui appartiene questo nodoQuesta funzione restituisce il documento a cui appartiene questo nodo.
L'esempio seguente produce due liste uguali di nodi figli.
Vedere anche domnode_insert_before().
(no version information, might be only in CVS)
DomNode->parent_node -- Restituisce il genitore del nodoQuesta funzione restituisce il genitore del nodo.
(PHP >= 4.3 solo) Se non si trova il nodo genitore, si restituisce NULL.
L'esempio seguente visualizza due liste simili di nodi figli.
(no version information, might be only in CVS)
DomNode->prefix -- Restituisce lo spazio dei nomi prefisso al nodo(no version information, might be only in CVS)
DomNode->previous_sibling -- Restituisce il nodo fratello precedenteQuesta funzione restituisce il nodo fratello precedente rispetto al nodo corrente. Se non vi sono nodi precedenti la funzione restituisce FALSE (< 4.3) oppure null (>= 4.3). Si può utilizzare questa funzione per attraversare tutti i nodi figli come illustrato nell'esempio.
Vedere anche domnode_next_sibling().
(no version information, might be only in CVS)
DomNode->remove_child -- Rimuove un nodo figlio dalla lista dei figliQuesta funzione rimuove un nodo figlio dalla lista dei figli. Se il nodo non può essere rimosso, oppure non è un nodo figlio la funzione restituisce FALSE. Se il nodo figlio può essere rimosso la funzione restituisce il vecchio nodo.
Esempio 1. Rimozione di un nodo figlio
|
Vedere anche domnode_append_child().
(PHP 4.2) Questa funzione sostituisce il nodo vecchio_nodo con il parametro nuovo_nodo. Se il nuovo nodo è già un figlio questo non verrà aggiunto una seconda volta. Se la funzione non riesce a trovare il vecchio nodo, restituisce FALSE. Se, invece, la sostituzione riesce, la funzione restituisce il vecchio nodo.
(PHP 4.3) Questa funzione sostituisce il nodo figlio vecchio_nodo con il parametro nuovo_nodo, anche se il nuovo nodo è già un figlio di DomNode. Se nuovo_nodo era già presente nel documento, prima questo viene rimosso dal contesto esistente. Se la funzione non riesce a trovare il vecchio nodo, restituisce FALSE. Se la sostituzione riesce, la funzione restituisce il vecchio nodo. (Questo comportamento rispecchia le specifiche W3C).
Vedere anche domnode_append_child()
(PHP 4.2) Questa funzione sostituisce il nodo esistente con il nodo passato nel parametro nuovo_nodo. Qualora nuovo_nodo abbia un genitore, il nodo viene copiato in modo da non inserire nel documento due volte un nodo già presente. In questo modo si costringe a fare tutte le modifiche al nodo prima della sostituzione o di riprendere il nodo inserito in una fase successiva con funzioni tipo domnode_first_child(), domnode_child_nodes() ecc..
(PHP 4.3) Questa funzione sostituisce il nodo con il nuovo nodo passato. Questo non viene più copiato. Se nuovo_nodo è già inserito nel documento, prima viene rimosso dal contesto esistente. Se la sostituzione riesce, la funzione restituisce il vecchio nodo.
Vedere anche domnode_append_child()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Imposta il nome del nodo.
Vedere anche domnode_node_name().
(no version information, might be only in CVS)
DomNode->set_namespace -- Imposta lo spazio dei nomi del nodoImposta lo spazio dei nomi del nodo a uri. Se esiste già uno spazio dei nomi impostato con il medesimo uri in uno dei nodi genitore, si utilizza il prefisso di questo, altrimenti si utilizza il prefisso passato con il parametro opzionale prefix, oppure se ne genera uno casuale.
Vedere anche domdocument_create_element_ns() e domnode_add_namespace()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomProcessingInstruction->data -- Restituisce i dati di un nodo PI
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomProcessingInstruction->target -- Restituisce il target di un nodo PI
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomXsltStylesheet->process -- Applica una trasformazione XSLT ad un oggetto DomDocumentAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche domxml_xslt_stylesheet(), domxml_xslt_stylesheet_file() e domxml_xslt_stylesheet_doc().
(no version information, might be only in CVS)
DomXsltStylesheet->result_dump_file -- Scarica il risultato di una trasformazione XSLT in un fileAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Questa funzione è disponibile solo a partire dalla versione 4.3 di PHP.
Poichè DomXsltStylesheet->process() restituisce sempre un documento XML ben formato, a prescindere da quale metodo di output sia specificato in <xsl:output> od in attributi/elementi simili, questa non è di grande utilità se si desidera ottenere in output un testo normale o HTML. Al contrario questa funzione rispetta <xsl:output method="html|text"> e le altre direttive di output. Vedere l'esempio per dettagli su come usare la funzione.
Vedere anche domxml_xslt_result_dump_mem() e domxml_xslt_process()
(no version information, might be only in CVS)
DomXsltStylesheet->result_dump_mem -- Scarica il risultato di una trasformazione XSLT in una stringaAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Questa funzione è disponibile solo a partire dalla versione 4.3 di PHP.
Poichè DomXsltStylesheet->process() restituisce sempre un documento XML ben formato, a prescindere da quale metodo di output sia specificato in <xsl:output> od in attributi/elementi simili, questa non è di grande utilità se si desidera ottenere in output un testo normale o HTML. Al contrario questa funzione rispetta <xsl:output method="html|text"> e le altre direttive di output. Vedere l'esempio per dettagli su come usare la funzione.
Vedere anche domxml_xslt_result_dump_file() e domxml_xslt_process()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Crea da zero un nuovo documento DOM e lo restituisce.
Vedere anche domdocument_add_root()
Questa funzione analizza il documento XML presente nel file nome_file e restituisce un oggetto della classe "Dom document", con le proprietà indicate. Il file viene aperto in modalità di sola lettura.
Il parametro facoltativo mode può essere utilizzato per modificrea il comportamento della funzione. E' stato aggiunto in PHP 4.3.0. Esso può assumere una delle seguenti costanti: DOMXML_LOAD_PARSING (default), DOMXML_LOAD_VALIDATING oppure DOMXML_LOAD_RECOVERING. Inoltre si possono agguiungere DOMXML_LOAD_DONT_KEEP_BLANKS, DOMXML_LOAD_SUBSTITUTE_ENTITIES e DOMXML_LOAD_COMPLETE_ATTRS tramite l'operazione or.
Se si utilizza il parametro error, questo ocnterrà l'eventuale messaggio di errore. error deve essere passato per riferimento. Il parametro è stato aggiunto in PHP 4.3.0.
Vedere anche domxml_open_mem() e domxml_new_doc().
La funzione analizza il documento XML contenuto in str e restituisce un oggetto della classe "Dom document", avente le proprietà elencate. Queste funzioni, domxml_open_file() e domxml_new_doc(), devono essere richiamate prima di ogni altra funzione.
Il parametro facoltativo mode può essere utilizzato per modificare il comportamento di questa funzione. E' stato aggiunto in PHP 4.3.0. Vedere domxml_open_file() per i valori ammessi.
Se si utilizza il parametro error, questo ocnterrà l'eventuale messaggio di errore. error deve essere passato per riferimento. Il parametro è stato aggiunto in PHP 4.3.0.
Vedere anche domxml_open_file() e domxml_new_doc().
Questa funzione restituisce la versione della libreria XML attualmente utilizzata.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Questa funzione analizza il documento XML contenuto nella stringa str e restituisce il documento analizzato come un albero di oggetti PHP. Questa funzione è isolata rispetto alle altre, ciò significa che non si può accedere all'albero utilizzando le altre funzioni. Modificare l'albero, ad esempio aggiungendovi un nodo, non ha senso poichè al momento non vi è modo di salvare il documento in un file XML. Tuttavia questa funzione può essere utile se si desidera leggere un file ed analizzarne il contenuto.
(PHP 4 >= 4.2.0, PECL)
domxml_xslt_stylesheet_doc -- Crea un oggetto DomXsltStylesheet da un oggetto DomDocument.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche domxsltstylesheet->process(), domxml_xslt_stylesheet() e domxml_xslt_stylesheet_file()
(PHP 4 >= 4.2.0, PECL)
domxml_xslt_stylesheet_file -- Crea un oggetto DomXsltStylesheet da un file con un documento XSLAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche domxsltstylesheet->process(), domxml_xslt_stylesheet() e domxml_xslt_stylesheet_doc().
(PHP 4 >= 4.2.0, PECL)
domxml_xslt_stylesheet -- Crea un oggetto DomXsltStylesheet da un documento XML contenuto in una stringaAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche domxsltstylesheet->process(), domxml_xslt_stylesheet_file() e domxml_xslt_stylesheet_doc()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Vedere anche xpath_eval().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Si può specificare il parametro opzionale contextnode per eseguire delle query XPath relative.
Vedere anche xpath_new_context().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Vedere anche xpath_eval().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Le seguenti sono le funzioni per la gestione degli errori ed il logging. Esse permettono di definire regole personalizzate per la gestione degli errori, e anche di modificarne la modalità della gestione stessa. Ciò permette di cambiare ed integrare i messaggi di errore adattandoli alle vostre esigenze.
Grazie alle funzioni di logging, è possibile inviare messaggi direttamente ad altre macchine, alla posta elettronica (o ad un gateway pager o di posta elettronica!), ai log di sistema, ecc., in modo da effettuare il log e controllare selettivamente le parti più importanti delle vostre applicazioni e siti web.
Le funzioni di restituzione dell'errore consentono la personalizzazione del livello e del tipo di errore, dal semplice avviso sino a funzioni personalizzate restituite durante gli errori.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Parametri di configurazione per la gestione degli errori e dei log
Nome | Default | Modificabile |
---|---|---|
error_reporting | E_ALL & ~E_NOTICE | PHP_INI_ALL |
display_errors | "1" | PHP_INI_ALL |
display_startup_errors | "0" | PHP_INI_ALL |
log_errors | "0" | PHP_INI_ALL |
log_errors_max_len | "1024" | PHP_INI_ALL |
ignore_repeated_errors | "0" | PHP_INI_ALL |
ignore_repeated_source | "0" | PHP_INI_ALL |
report_memleaks | "1" | PHP_INI_ALL |
track_errors | "0" | PHP_INI_ALL |
html_errors | "1" | PHP_INI_ALL |
docref_root | "" | PHP_INI_ALL |
docref_ext | "" | PHP_INI_ALL |
error_prepend_string | NULL | PHP_INI_ALL |
error_append_string | NULL | PHP_INI_ALL |
error_log | NULL | PHP_INI_ALL |
warn_plus_overloading | NULL | PHP_INI?? |
Breve descrizione dei parametri di configurazione.
Imposta il livello di errore da visualizzare. Il parametro è sia un intero rappresentante un campo di bit, o una costante nominale. I livelli ri report degli errori e le costanti previste sono descritte in Costanti Predefinite, e in php.ini. Per impostare il livello in fase di esecuzione utilizzare la funzione error_reporting(). Vedere anche il parametro display_errors.
In PHP 4 e PHP 5 il valore di default è E_ALL & ~E_NOTICE. Questa impostazione non visualizza gli errori di livello E_NOTICE. Tuttavia può essere comodo visualizzare questi messaggi in fase di sviluppo.
Nota: Abilitare E_NOTICE durante la fase di sviluppo ha dei benefici. Ad esempio per scopi di debug: i messaggi di tipo NOTICE avvisano su possibili bug nel codice. L'uso di variabili non assegnate, ad esempio, viene rilevato con questo livello di errore. Particolare che è molto utile per trovare errori di battitura e risparmiare tempo in fase di debug. I messaggi di tipo NOTICE segnalano il codice scritto con un cattivo stile. Ad esempio, $arr[item] è meglio che sia scritto come $arr['item'] poichè il PHP tenta di trattare "item" come costante. Se non esiste una simile costante, il PHP presume che si tratti dell'indice di una matrice.
Nota: Nel PHP 5 è stato introdotto un nuovo livello di errore E_STRICT. Come E_STRICT non viene incluso nel E_ALL e, pertanto, occorre abilitarlo in modo esplicito. Abilitare E_STRICT durante la fase di sviluppo porta alcuni benefici. Questa casistica di messaggi servono ad aiutare le più recenti, e consigliate, metodologie di programamzione, avvisando, ad esempio, sull'uso di funzioni deprecate.
In PHP 3 l'impostazione di default è (E_ERROR | E_WARNING | E_PARSE), che significa la medesima cosa. Occorre rilevare, tuttavia, che le costanti non sono supportate nel php3.ini del PHP 3, e pertanto occorre utilizzare la codifica numerica, che corrisponde a 7.
Questo parametro determina se gli errori devono essere visualizzati sullo schermo come parte dell'output o se devono essere nascosti all'utente.
Nota: Questa opzione è di supporto allo sviluppo, e non deve mai essere utilizzata nei sistemi di produzione (ad esempio collegati ad Internet).
Anche quando è abilitata la visualizzazione degli errori, gli errori che avvengono durante l'avvio del PHP non sono visualizzati. Si raccomanda di mantenere display_startup_errors impostato a off, tranne che nelle fasi di sviluppo.
Indica se i messaggi di errore debbano essere registrati nell'errorlog del server o in error_log. Questo opzione dipende dal server.
Nota: Sui siti di produzione si raccomanda di utilizzare la registrazione degli errori piuttosto che visualizzarli.
Imposta la massima lunghezza del log degli errori in byte. Nell'errorlog error_log viene indicata anche la fonte del messaggio. Il valore di default è 1024 e 0 indica di non applicare alcuna limitazione. Questa dimensione viene applicata agli errori registrati, agli errori visualizzati e anche a $php_errormsg.
When an integer is used, the value is measured in bytes. You may also use shorthand notation as described in this FAQ.
Non registra i messaggi ripetuti. Gli errori ripetutti sono gli errori che si verificano nel medesimo file nella linea, e vengono riportati sino a quando ignore_repeated_source non viene impostato a true.
Ignora la fonte del messaggio quando si ignora i messaggi ripetuti. Quando questa impostazione è a On non saranno registrati messaggi ripetutida differenti linee del codice.
Se questo parametro è impostato a Off, non saranno evidenziate carenze di memoria (o nello stdout o nel log). Questa impostazione ha effetto solo nella compila in modalità di debug, e se error_reporting include E_WARNING nell'elenco degli errori abilitati.
Se abilitato, l'ultimo messaggio di errore sarà sempre presente nella variabile $php_errormsg.
Disabilita i tag HTML nei messaggi di errore. Il nuovo formato per i messaggi in HTML produce un testo cliccabile che dirige l'utente alla pagina che descrive l'errore o la funzione che generato l'errore. Questi riferimenti sono influenzati da docref_root e docref_ext.
Nel nuovo formato degli errori è previsto un riferimento alla pagina che descrive l'errore o alla funzione che ha generato l'errore. Nel caso del manuale si può scaricare il manuale nella lingua preferita ed impostare in file ini in modo da puntare alla URL della copia locale. Se la copia locale è raggiungibile tramite '/manual/' si può utilizzare docref_root=/manual/. In aggiunta si può impostare docref_ext a riconoscere l'estensione dei file nella copia, es. docref_ext=.html. E' possibile utilizzare riferimenti esterni. Ad esempio, si può utilizzare docref_root=http://manual/en/ oppure docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon &url=http%3A%2F%2Fwww.php.net%2F"
Il più delle volte si imposta docref_root ad un valore che termina con value to end with a slash '/'. But see the second example above which does not have nor need it.
Nota: Questa caratteristica è utile nello sviluppo poichè rende facile la ricerca della descrzione delle funzioni. Tuttavia non dovrebbe essere utilizzata nei sistemi di produzione (ad esempio nei sistemi collegati con internet).
Vedere docref_root.
Nota: Il valore di docref_ext deve cominciare con un punto '.'.
Testo da visualizzare prima del messaggio di errore.
Testo da visualizzare dopo il messaggio di errore.
Nome del file in cui gli errori devono essere registrati. Se si indica il nome speciale syslog, gli errori saranno inviati al log di sistema. Sui sistemi Unix, ciò significa syslog(3) e sui sistemi Windows NT indica l'event log. Il log di sistema non è supportato in Windows 95. Vedere anche: syslog().
Se abilitata, questa opzione indica al PHP di visualizzare un warning quando si utilizza il segno (+) nelle stringhe. Questo rende più facile trovare gli script che richiedono di essere modificati nelle operazioni di concatenazione delle stringhe utilizzando (.).
Le costanti qui elencate sono sempre disponibili in quanto parte del core di PHP.
Nota: Si possono utilizzare queste constanti in php.ini ma non all'esterno del PHP, tipo in in httpd.conf, dove occorre utilizzare in valori.
Tabella 2. Errori e log
Valore | Costante | Descrizione | Note |
---|---|---|---|
1 | E_ERROR (integer) | Errori fatali di esecuzione. Questi indicano errori che non si possono ignorare, come, ad esempio, errori di allocazione della memoria. L'esecuzione dello script è bloccata. | |
2 | E_WARNING (integer) | Warning di esecuzione (errori non fatali). L'esecuzione dello script non viene bloccata. | |
4 | E_PARSE (integer) | Errore di parsing in fase di compila. Essendo errori di parsing sono generati dal parser del codice PHP. | |
8 | E_NOTICE (integer) | Informazioni di esecuzione. Questo messaggio indica che lo script ha incontrato qualcosa che potrebbe indicare un errore, ma è una sitauzione che può accadere durante una normale esecuzione di uno script. | |
16 | E_CORE_ERROR (integer) | Errori fatali che accadono durante la fase di inizializzazione del PHP. Questo è come un E_ERROR, tranne che viene generato dall'interno del PHP. | dal PHP 4 |
32 | E_CORE_WARNING (integer) | Warning (errore non fatale) che accade durante la fase di inizializzazione del PHP. Questo è come un E_WARNING, tranne che viene generato dall'interno del PHP. | dal PHP 4 |
64 | E_COMPILE_ERROR (integer) | Errore fatale di compila. Questo è come E_ERROR, tranne che viene generato dal motore Zend. | dal PHP 4 |
128 | E_COMPILE_WARNING (integer) | Warning di compila (errore non fatale). Questo è come E_WARNING, tranne che viene generato dal motore Zend. | dal PHP 4 |
256 | E_USER_ERROR (integer) | Messaggio di errore generato dall'utente. Questo è come E_ERROR, tranne che viene generato dal codice PHP tramite la funzione trigger_error(). | dal PHP 4 |
512 | E_USER_WARNING (integer) | Messaggio di warning generato dall'utente. Questo è come E_WARNING,tranne che viene generato dal codice PHP tramite la funzione trigger_error(). | dal PHP 4 |
1024 | E_USER_NOTICE (integer) | Messaggio di informazione generato dall'utente. Questo è come E_NOTICE, tranne che viene generato dal codice PHP tramite la funzione trigger_error(). | dal PHP 4 |
2047 | E_ALL (integer) | Tutti gli errori ed i warning supportati tranne quelli di livello E_STRICT. | |
2048 | E_STRICT (integer) | Informazione di esecuzione. Abilitare questo messaggio per avere dal PHP suggerimenti sulle modifiche da apportare al codice per avere la migliore interoperabilità e compatibilità del codice. | dal PHP 5 |
I valori precedenti (sia numerici, sia simbolici) possono essere utilizzati per costruire delle maschere di bit che indichino quali errori visualizzare. Si può utilizzare gli operatori sui bit per combinare questi valori o per mascherare certi tipi di errori. Fare attenzione che soltanto '|', '~', '!', '^' e '&' sono compresi dal php.ini, e che nessun operatore sui bit è gestito dal php3.ini.
Di seguito sarà illustrato un esempio di utilizzo delle procedure di gestione dell'errore in PHP. Qui si definisce una funzione di gestione dell'errore che registra le informazioni in un file (in formato XML) e invia tramite e-mail allo sviluppare dei messaggi in caso di errori critici.
Esempio 1. Esempio dell'utilizzo di della gestione degli erorri in uno script
|
debug_backtrace() genera una backtrace PHP e restituisce questa informazione sotto forma di array associativo. Gli elementi che possono venire restituiti sono elencati nella seguente tabella:
Tabella 1. Elementi restituibili dalla funzione debug_backtrace()
Nome | Tipo | Descrizione |
---|---|---|
funzione | string | Il nome della funzione corrente. Vedere anche __FUNCTION__. |
riga | integer | Il numero della linea corrente. Vedere anche __LINE__. |
file | string | Il nome del file corrente. Vedere anche __FILE__. |
classe | string | Il nome della class corrente. Vedere anche __CLASS__ |
tipo | string | Il tipo di chiamata corrente. Se chiamata di metodo, viene restituito "->" is returned. Se chiamata di metodo statico, viene restituito "::". Se chiamata di funzione, non viene restituito niente. |
args | array | Se all'interno di una funzione, elenca gli argomenti della funzione. Se all'interno di un file incluso, elenca i nomi del file incluso. |
Di seguito un semplice esempio.
Esempio 1. debug_backtrace() example
Risultati durante l'esecuzione di /tmp/b.php:
|
Vedere anche trigger_error() and debug_print_backtrace().
debug_print_backtrace() stampa una backtrace PHP. Stampa le chiamate di funzione, i file included/required e tutto cio' che viene valutato dalla funzione eval().
Esempio 1. Esempio di funzione debug_print_backtrace()
Il precedente esempio visualizzerà qualcosa simile a:
|
Invia un messaggio di errore la log del server web, ad una porta TCP o ad un file. Il primo parametro, messaggio, è il messaggio di errore che deve essere registrato. Il secondo parametro, tipo_messaggio indica la destinazione del messaggio:
Tabella 1. error_log() tipi di log
0 | messaggio è inviato al log di sistema di PHP, utilizzando il sistema di log del Sistema Operativo o un file, a seconda di come sia impostata la direttiva di configurazione error_log. |
1 | messaggio è inviato via posta elettronica all'indirizzo indicato nel parametro destinazione parameter. Questo è l'unico tipo di messaggio nel quale viene usato il quarto parametro, headers_extra. Questo tipo di messaggio utilizza la stessa funzione interna di mail(). |
2 | messaggio viene inviato attraverso la connessione di debug di PHP. Questa opzione è disponibile solo nel caso che il debug remoto sia stato abilitato. In questo caso, il parametro destinazione specifica il nome dell'host o l'indirizzo IP e opzionalmente, numero di porta, del socket che riceverà l'informazione di debug. |
3 | messaggio è aggiunto al file destinazione. |
Avvertimento |
Il debug remoto via TCP/IP è una caratteristica di PHP 3 non disponibile in PHP 4. |
Esempio 1. error_log() esempi
|
Definisce il livello di restituzione di errore di PHP e ritorna il vecchio livello. Il livello di restituzione dell'errore può essere una maschera di bit o una costante named. L'utilizzo delle costanti named è caldamente consigliato per assicurare la compatibilità con versioni future. All'aggiungere di livelli di errore, la gamma degli interi viene incrementata, perciò vecchi livelli di errore basati sull'intero non si comporteranno sempre come ci si aspetta.
Esempio 1. Error Integer changes
|
Tabella 1. error_reporting() valori dei bit
valore | costante |
---|---|
1 | E_ERROR |
2 | E_WARNING |
4 | E_PARSE |
8 | E_NOTICE |
16 | E_CORE_ERROR |
32 | E_CORE_WARNING |
64 | E_COMPILE_ERROR |
128 | E_COMPILE_WARNING |
256 | E_USER_ERROR |
512 | E_USER_WARNING |
1024 | E_USER_NOTICE |
2047 | E_ALL |
Esempio 2. esempi error_reporting()
|
(PHP 4 >= 4.0.1, PHP 5)
restore_error_handler -- Ripristina la precedente funzione di gestione dell'erroreUtilizzata dopo la modifica della funzione di gestione degli errori con set_error_handler(), per ripristinare la precedente modalità di gestione (che può essere quella di configurazione o una definita dall'utente).
Vedere anche error_reporting(), set_error_handler(), trigger_error(), user_error()
(PHP 5)
restore_exception_handler -- Ripristina la funzione di gestione delle eccezioni definita in precedenzaUtilizzata, dopo aver cambiato la funzione di gestione delle eccezioni con il comando set_exception_handler(), per tornare al gestore delle eccezioni precedente (che potrebbe essere la funzione incorporata o una funzione definita dall'utente). Questa funzione restituisce sempre TRUE.
Vedere anche set_exception_handler(), set_error_handler(), restore_error_handler() error_reporting()
(PHP 4 >= 4.0.1, PHP 5)
set_error_handler -- Configura una funzione di gestione dell'errore definita dall'utente.Configura una funzione utente (error_handler per gestire gli errori in uno script. Restituisce, se esistente, il precedente gestore degli errori, o FALSE in caso di errore. Questa funzione può essere utilizzata per definire un sistema personalizzato di gestione degli errori durante l'esecuzione, per esempio in applicazioni dove sia necessario svuotare dati o file in caso di un determinato errore critico, o quando sia necessario, in determinate condizioni, attivare un errore (con trigger_error())
La funzione utente richiede 2 parametri: il codice errore e una stringa descrittiva dell'errore. Da PHP 4.0.2, è possibile opzionalmente fornire altri 3 parametri aggiuntivi: il nome del file, il numero di riga e il contesto dove è avvenuto l'errore (un array che punto alla tabella dei simboli attiva nel punto in cui è avvenuto l'errore).
L'esempio sottostante mostra la gestione delle eccezioni interne attivando gli errori e gestendoli tramite una funzione definita dall'utente:
Esempio 1. Gestione errori con set_error_handler() e trigger_error()
|
vector a Array ( [0] => 2 [1] => 3 [2] => foo [3] => 5.5 [4] => 43.3 [5] => 21.11 ) ---- vector b - a warning (b = log(PI) * a) <b>WARNING</b> [1024] Value at position 2 is not a number, using 0 (zero)<br> Array ( [0] => 2.2894597716988 [1] => 3.4341896575482 [2] => 0 [3] => 6.2960143721717 [4] => 49.566804057279 [5] => 24.165247890281 ) ---- vector c - an error <b>ERROR</b> [512] Incorrect input vector, array of values expected<br> NULL ---- vector d - fatal error <b>FATAL</b> [256] log(x) for x <= 0 is undefined, you used: scale = -2.5<br> Fatal error in line 36 of file trigger_error.php, PHP 4.0.2 (Linux)<br> Aborting...<br> |
E' importante ricordare che il gestore degli errori standard di PHP viene completamente saltato. La configurazione di error_reporting() non avrà effetto e il vostro gestore di errore sarà richiamato senza considerarla - in ogni caso sarà possibile leggere il valore corrente di error_reporting() ed agire di conseguenza. E' di particolare rilevanza il fatto che questo valore sarà 0 se la riga che causa l'errore viene precedura dall' operatore di controllo errore @.
Notare anche che è vostra responsabilità definire die() se necessario. Se la funzione di gestione dell'errore ritorna, lo script continerà l'esecuzione con la riga seguente a quella che ha causato l'errore.
Vedere anche error_reporting(), restore_error_handler(), trigger_error(), user_error()
(PHP 5)
set_exception_handler -- Imposta una funzione di gestione delle eccezioni definita dall'utenteImposta la funzione predefinita per la gestione delle eccezioni se un'eccezione non viene individuata all'interno di un blocco try/catch. L'esecuzione sara' terminata dopo la chiamata della funzione exception_handler.
La funzione exception_handler deve essere definita prima di invocare
la funzione set_exception_handler(). A quest'ultima funzione deve essere passato
un solo parametro, che consiste nell'eccezione individuata.
exception_handler ( object exception )
Nome della funzione da invocare in caso di eccezione non individuata.
Nome della funzione da invocare in caso di eccezione non individuata.
Restituisce la funzione di gestione delle eccezioni definita in precedenza, oppure FALSE in caso di errore. Se non era stata definita in precedenza nessuna funzione di gestione delle eccezioni, viene restituita una stringa vuota.
restore_exception_handler(), restore_error_handler(), error_reporting(), information about the callback type, e PHP 5 Exceptions.
(PHP 4 >= 4.0.1, PHP 5)
trigger_error -- Genera un messaggio a livello utente di errore/avviso/avvertimento messageUtilizzata per attivare una condizione di errore utente, può essere usata in congiunzione con il gestore di errore interno, o con una funzione definita dall'utente che sia configurata per essere il nuovo gestore di errore con (set_error_handler()). Funziona soltanto con la famiglia di costanti E_USER, e punta alla predefinita E_USER_NOTICE.
Questa funzione è utile quando sia necessario generare una particolare risposta ad un'eccezione durante l'esecuzione. Per esempio:
Nota: Vedere set_error_handler() per un esempio più esplicativo.
Vedere anche error_reporting(), set_error_handler(), restore_error_handler(), user_error()
Questo è un alias per la funzione trigger_error().
Vedere anche error_reporting(), set_error_handler(), restore_error_handler() e trigger_error()
With the exif extension you are able to work with image meta data. For example, you may use exif functions to read meta data of pictures taken from digital cameras by working with information stored in the headers of the JPEG and TIFF images.
Your PHP must be compiled in with --enable-exif. PHP does not require any additional library for the exif module. Windows users must also have the mbstring extension enabled.
To enable exif-support configure PHP with --enable-exif
Windows users must enable both the php_mbstring.dll and php_exif.dll DLL's in php.ini. The php_mbstring.dll DLL must be loaded before the php_exif.dll DLL so adjust your php.ini accordingly.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Exif supports automatically conversion for Unicode and JIS character encodings of user comments when module mbstring is available. This is done by first decoding the comment using the specified characterset. The result is then encoded with another characterset which should match your HTTP output.
Tabella 1. Exif configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
exif.encode_unicode | "ISO-8859-15" | PHP_INI_ALL | Available since PHP 4.3.0. |
exif.decode_unicode_motorola | "UCS-2BE" | PHP_INI_ALL | Available since PHP 4.3.0. |
exif.decode_unicode_intel | "UCS-2LE" | PHP_INI_ALL | Available since PHP 4.3.0. |
exif.encode_jis | "" | PHP_INI_ALL | Available since PHP 4.3.0. |
exif.decode_jis_motorola | "JIS" | PHP_INI_ALL | Available since PHP 4.3.0. |
exif.decode_jis_intel | "JIS" | PHP_INI_ALL | Available since PHP 4.3.0. |
Breve descrizione dei parametri di configurazione.
exif.encode_unicode defines the characterset UNICODE user comments are handled. This defaults to ISO-8859-15 which should work for most non Asian countries. The setting can be empty or must be an encoding supported by mbstring. If it is empty the current internal encoding of mbstring is used.
exif.decode_unicode_motorola defines the image internal characterset for Unicode encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2BE.
exif.decode_unicode_intel defines the image internal characterset for Unicode encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2LE.
exif.encode_jis defines the characterset JIS user comments are handled. This defaults to an empty value which forces the functions to use the current internal encoding of mbstring.
exif.decode_jis_motorola defines the image internal characterset for JIS encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.
exif.decode_jis_intel defines the image internal characterset for JIS encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
The exif_imagetype() lists several related built-in constants.
exif_imagetype() reads the first bytes of an image and checks its signature.
exif_imagetype() can be used to avoid calls to other exif functions with unsupported file types or in conjunction with $_SERVER['HTTP_ACCEPT'] to check whether or not the viewer is able to see a specific image in the browser.
When a correct signature is found, the appropriate constant value will be returned otherwise the return value is FALSE. The return value is the same value that getimagesize() returns in index 2 but exif_imagetype() is much faster.
The following constants are defined, and represent possible exif_imagetype() return values:
Tabella 1. Imagetype Constants
Value | Constant |
---|---|
1 | IMAGETYPE_GIF |
2 | IMAGETYPE_JPEG |
3 | IMAGETYPE_PNG |
4 | IMAGETYPE_SWF |
5 | IMAGETYPE_PSD |
6 | IMAGETYPE_BMP |
7 | IMAGETYPE_TIFF_II (intel byte order) |
8 | IMAGETYPE_TIFF_MM (motorola byte order) |
9 | IMAGETYPE_JPC |
10 | IMAGETYPE_JP2 |
11 | IMAGETYPE_JPX |
12 | IMAGETYPE_JB2 |
13 | IMAGETYPE_SWC |
14 | IMAGETYPE_IFF |
15 | IMAGETYPE_WBMP |
16 | IMAGETYPE_XBM |
exif_read_data() reads the EXIF headers from a JPEG or TIFF image file. This way you can read meta data generated by digital cameras.
Exif headers tend to be present in JPEG/TIFF images generated by digital cameras, but unfortunately each digital camera maker has a different idea of how to actually tag their images, so you can't always rely on a specific Exif header being present.
Height and Width are computed the same way getimagesize() does so their values must not be part of any header returned. Also, html is a height/width text string to be used inside normal HTML.
When an Exif header contains a Copyright note, this itself can contain two values. As the solution is inconsistent in the Exif 2.10 standard, the COMPUTED section will return both entries Copyright.Photographer and Copyright.Editor while the IFD0 sections contains the byte array with the NULL character that splits both entries. Or just the first entry if the datatype was wrong (normal behaviour of Exif). The COMPUTED will also contain the entry Copyright which is either the original copyright string, or a comma separated list of the photo and editor copyright.
The tag UserComment has the same problem as the Copyright tag. It can store two values. First the encoding used, and second the value itself. If so the IFD section only contains the encoding or a byte array. The COMPUTED section will store both in the entries UserCommentEncoding and UserComment. The entry UserComment is available in both cases so it should be used in preference to the value in IFD0 section.
exif_read_data() also validates EXIF data tags according to the EXIF specification (http://exif.org/Exif2-2.PDF, page 20).
Nota: Windows ME/XP can both wipe the Exif headers when connecting to a camera. More information available at http://www.canon.co.jp/Imaging/NOTICE/011214-e.html.
The name of the image file being read. This cannot be an URL.
Is a comma separated list of sections that need to be present in file to produce a result array. If none of the requested sections could be found the return value is FALSE.
FILE | FileName, FileSize, FileDateTime, SectionsFound |
COMPUTED | html, Width, Height, IsColor, and more if available. Height and Width are computed the same way getimagesize() does so their values must not be part of any header returned. Also, html is a height/width text string to be used inside normal HTML. |
ANY_TAG | Any information that has a Tag e.g. IFD0, EXIF, ... |
IFD0 | All tagged data of IFD0. In normal imagefiles this contains image size and so forth. |
THUMBNAIL | A file is supposed to contain a thumbnail if it has a second IFD. All tagged information about the embedded thumbnail is stored in this section. |
COMMENT | Comment headers of JPEG images. |
EXIF | The EXIF section is a sub section of IFD0. It contains more detailed information about an image. Most of these entries are digital camera related. |
Specifies whether or not each section becomes an array. The sections COMPUTED, THUMBNAIL, and COMMENT always become arrays as they may contain values whose names conflict with other sections.
When set to TRUE the thumbnail itself is read. Otherwise, only the tagged data is read.
It returns an associative array where the array indexes are the header names and the array values are the values associated with those headers. If no data can be returned, exif_read_data() will return FALSE.
Versione | Descrizione |
---|---|
4.3.0 | Can read all embedded IFD data including arrays (returned as such). Also the size of an embedded thumbnail is returned in a THUMBNAIL subarray, and can return thumbnails in TIFF format. Also, there is no longer a maximum length for returned values (not until the memory limit has been reached) |
4.3.0 | If PHP has mbstring support, the user comment can automatically change encoding. Also, if the user comment uses Unicode or JIS encoding this encoding will automatically be changed according to the exif ini settings in php.ini |
4.3.0 | If the image contains any IFD0 data then COMPUTED contains the entry ByteOrderMotorola which is 0 for little-endian (intel) and 1 for big-endian (motorola) byte order. Also, COMPUTED and UserComment no longer only contain the first copyright entry if the datatype was wrong. |
Esempio 1. exif_read_data() example
The first call fails because the image has no header information. Il precedente esempio visualizzerà qualcosa simile a:
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
exif_thumbnail() reads the embedded thumbnail of a TIFF or JPEG image.
If you want to deliver thumbnails through this function, you should send the mimetype information using the header() function.
It is possible that exif_thumbnail() cannot create an image but can determine its size. In this case, the return value is FALSE but width and height are set.
The name of the image file being read. This image contains an embedded thumbnail.
The return width of the returned thumbnail.
The returned height of the returned thumbnail.
The returned image type of the returned thumbnail. This is either TIFF or JPEG.
Esempio 1. exif_thumbnail() example
|
This extension allows to interact with processes through PTY. You may consider using the expect:// wrapper with the filesystem functions which provide a simpler and more intuitive interface.
This module uses the functions of the expect library. You need libexpect version >= 5.43.0.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/expect.
In PHP 4 this PECL extensions source can be found in the ext/ directory within the PHP source or at the PECL link above. In order to use these functions you must compile PHP with expect support by using the --with-expect[=DIR] configure option.
Windows users will enable php_expect.dll inside of php.ini in order to use these functions. In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
In order to configure expect extension, there are configuration options in the configuration file php.ini.
Tabella 1. Expect Opioni di configurazione
Nome | Default | Modificabile | Changelog |
---|---|---|---|
expect.timeout | "10" | PHP_INI_ALL | |
expect.loguser | "On" | PHP_INI_ALL | |
expect.logfile | "" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
The timeout period for waiting for the data, when using the expect_expectl() function.
A value of "-1" disables a timeout from occurring.
Nota: A value of "0" causes the expect_expectl() function to return immediately.
Whether expect should send any output from the spawned process to stdout. Since interactive programs typically echo their input, this usually suffices to show both sides of the conversation.
Name of the file, where the output from the spawned process will be written. If this file doesn't exist, it will be created.
Nota: If this configuration is not empty, the output is written regardless of the value of expect.loguser.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Indicates that the pattern is a glob-style string pattern.
Indicates that the pattern is an exact string.
Indicates that the pattern is a regexp-style string pattern.
Value, returned by expect_expectl(), when EOF is reached.
Value, returned by expect_expectl() upon timeout of seconds, specified in value of expect.timeout
Value, returned by expect_expectl() if no pattern have been matched.
This example connects to the remote host via SSH, and prints the remote uptime.
Esempio 1. Expect Usage Example
|
(no version information, might be only in CVS)
expect_expectl -- Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seenWaits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen.
An Expect stream, previously opened with expect_popen().
An array of expect cases. Each expect case is an indexed array, as described in the following table:
Tabella 1. Expect Case Array
Index Key | Value Type | Description | Is Mandatory | Default Value |
---|---|---|---|---|
0 | string | pattern, that will be matched against the output from the stream | yes | |
1 | mixed | value, that will be returned by this function, if the pattern matches | yes | |
2 | integer | pattern type, one of: EXP_GLOB, EXP_EXACT or EXP_REGEXP | no | EXP_GLOB |
Returns value associated with the pattern that was matched.
On failure this function returns: EXP_EOF, EXP_TIMEOUT or EXP_FULLBUFFER
Esempio 1. expect_expectl() example
|
(no version information, might be only in CVS)
expect_popen -- Exectute command via Bourne shell, and open the PTY stream to the processExecute command via Bourne shell, and open the PTY stream to the process.
Returns an open PTY stream to the process'es stdio, stdout and stderr.
On failure this function returns FALSE.
FAM monitors files and directories, notifying interested applications of changes. More information about FAM is available at http://oss.sgi.com/projects/fam/.
A PHP script may specify a list of files for FAM to monitor using the functions provided by this extension.
The FAM process is started when the first connection from any application to it is opened. It exits after all connections to it have been closed.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.1.0.
Nota: Questo modulo non è disponibile su piattaforme Windows.
This extension uses the functions of the FAM library, developed by SGI. Therefore you have to download and install the FAM library.
To use PHP's FAM support you must compile PHP --with-fam[=DIR] where DIR is the location of the directory containing the lib and include directories.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 1. FAM event constants
Constant | Description |
---|---|
FAMChanged (integer) | Some value which can be obtained with fstat(1) changed for a file or directory. |
FAMDeleted (integer) | A file or directory was deleted or renamed. |
FAMStartExecuting (integer) | An executable file started executing. |
FAMStopExecuting (integer) | An executable file that was running finished. |
FAMCreated (integer) | A file was created in a directory. |
FAMMoved (integer) | This event never occurs. |
FAMAcknowledge (integer) | An event in response to fam_cancel_monitor(). |
FAMExists (integer) | An event upon request to monitor a file or directory. When a directory is monitored, an event for that directory and every file contained in that directory is issued. |
FAMEndExist (integer) | Event after the last FAMEExists event. |
fam_cancel_monitor() terminates monitoring on a resource previously requested using one of the fam_monitor_ functions. In addition an FAMAcknowledge event occurs.
See also fam_monitor_file(), fam_monitor_directory(), fam_monitor_collection(), and fam_suspend_monitor()
fam_close() closes a connection to the FAM service previously opened using fam_open().
fam_monitor_collection() requests monitoring for a collection of files within a directory. The actual files to be monitored are specified by a directory path in dirname, the maximum search depth starting from this directory and a shell pattern mask restricting the file names to look for.
A FAM event will be generated whenever the status of the files change. The possible event codes are described in detail in the constants part of this section.
See also fam_monitor_file(), fam_monitor_directory(), fam_cancel_monitor(), fam_suspend_monitor(), and fam_resume_monitor().
fam_monitor_directory() requests monitoring for a directory and all contained files. A FAM event will be generated whenever the status of the directory (i.e. the result of function stat() on that directory) or its content (i.e. the results of readdir()) change.
The possible event codes are described in detail in the constants part of this section.
See also fam_monitor_file(), fam_monitor_collection(), fam_cancel_monitor(), fam_suspend_monitor(), and fam_resume_monitor().
fam_monitor_file() requests monitoring for a single file. A FAM event will be generated whenever the file status (i.e. the result of function stat() on that file) changes.
The possible event codes are described in detail in the constants part of this section.
See also fam_monitor_directory(), fam_monitor_collection(), fam_cancel_monitor(), fam_suspend_monitor(), and fam_resume_monitor().
fam_next_event() returns the next pending FAM event. The function will block until an event is available which can be checked for using fam_pending().
fam_next_event() will return an array that contains a FAM event code in element 'code', the path of the file this event applies to in element 'filename' and optionally a hostname in element 'hostname'.
The possible event codes are described in detail in the constants part of this section.
See also fam_pending().
fam_open() opens a connection to the FAM service daemon. The optional parameter appname should be set to a string identifying the application for logging reasons.
See also fam_close().
fam_pending() returns non-zero if events are available to be fetched using fam_next_event().
See also fam_next_event().
fam_resume_monitor() resumes monitoring of a resource previously suspend using fam_suspend_monitor().
See also fam_suspend_monitor().
fam_suspend_monitor() temporarily suspend monitoring of a resource previously requested using one of the fam_monitor_ functions. Monitoring can later be continued using fam_resume_monitor() without the need of requesting a complete new monitor.
See also fam_resume_monitor(), and fam_cancel_monitor().
Il Forms Data Format (FDF) è un formato per la gestione di form all'interno di documenti PDF. Si dovrebbe leggere la documentazione al link http://partners.adobe.com/asn/acrobat/forms.jsp per avere maggiori informazioni su cosa sia FDF e su come usarlo in generale.
L'idea di base è che FDF sia simile ai form HTML. Fondamentalmente la differenza consiste nel formato con cui i dati sono inviati al server quando viene premuto il bottone di sottomissione del form (che, ovviamente, è in Form Data Format) e il formato del form stesso (che è il Portable Document Format, PDF). L'elaborazione dei dati FDF è una delle caratteristiche delle funzioni fdf.Ma ve ne sono altre. Una di queste consiste nel prendere un form PDF e compilarne i campi senza modificare il form . In questo caso si dovrebbe creare il documento FDF (fdf_create()) impostare i valori per ciascun campo (fdf_set_value()) e associarlo al form PDF (fdf_set_file()). Infine viene inviato al browser browser con MimeType application/vnd.fdf. Acrobat Reader riconosce il MimeType, legge il form PDF associato e completa i campi con i dati dal documento FDF.
Se si apre un documento FDF con un editor di testo si troveranno degli oggetti con nome FDF. Tali oggetti possono contenere diversi campi tipo Fields, F, Status etc.. I campi più comuni sono Fields che puntano alla lista dei campi di input, e F che contiene il nome del file PDF a cui appartengono questi dati. Questi campi sono definiti dalla documentazione FDF come chiave /F (/F-Key) e chiave /Status (/Status-Key) Le modifiche a questi chiavi posso essere svolte con funzioni tipo fdf_set_file() e fdf_set_status(). I campi sono modificati dalle funzioni fdf_set_value(), fdf_set_opt() etc..
Occorre avere disponibile il toolkit FDF SDK, scaricabile da http://partners.adobe.com/asn/acrobat/forms.jsp. Dal PHP 4.3 occorre avere almeno l'SDK versione 5.0. Le librerie FDF sono disponibili in formato binario solo per le piattaforme supportate da Adobe quali Win32, Linux, Solaris e AIX.
Occorre compilare il PHP con --with-fdftk[=DIR].
Nota: Se si hanno problemi nella configurazione del PHP con supporto fdftk, verificare che i file fdftk.h e libfdftk.so siano nel posto corretto. Lo script di configurazione supporta sia la struttura delle directory della distribuzione FDFSDK, sia l'usuale struttura DIR/include / DIR/lib, pertanto si può puntare o direttamente alla directory della distribuzione decompressa o posizionare il file con l'header e la libreria appropriata per la piattaforma, ad es. /usr/local/include e /usr/local/lib ed eseguire configure con --with-fdftk=/usr/local.
Nota per gli utenti Win32: Per potere abilitare questo modulo sui sistemi Windows, occorre copiare fdftk.dll dalla cartella DLL del rilascio PHP7Win32 alla cartella SYSTEM32 della macchina Windows. (Es. C:\WINNT\SYSTEM32 oppure C:\WINDOWS\SYSTEM32).
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
La maggior parte delle funzioni richiedono una risorsa fdf come primo parametro. La risorsa fdf è un puntatore al file fdf aperto. Le risorse fdf possono essere ottenute dalle funzioni fdf_create(), fdf_open() e fdf_open_string().
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Il seguente esempio illustra l'elaborazione dei dati di un form.
Esempio 1. Elaborazione di un documento FDF
|
Aggiunge degli script al documento FDF, che in seguito Acrobat aggiungerà agli script del documento una volta che l'FDF è importato. Su consiglia di utilizzare '\r' come separatore di riga nel script_code.
Esempio 1. Aggiunta di codice JavaScript ad un documento FDF
Sarà creato un documento come il seguente:
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione fdf_close() chiude un documento FDF.
Vedere anche fdf_open().
La funzione fdf_create() crea un nuovo documento FDF. Questa funzione è necessaria se si desidera compilare dei campi di input di un documento PDF.
Esempio 1. Compila di un documento PDF
|
Vedere anche fdf_close(), fdf_save() e fdf_open().
(PHP 4 >= 4.3.0, PHP 5)
fdf_enum_values -- Richiama una funzione definita dall'utente per ciascun valore del documento
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione fdf_errno() il codice di erore impostato dall'ultima funzione FDF eseguita. Questo può valere zero se è stata eseguita con successo, o diverso da zero in caso di errore. Una descrizione testuale dell'errore può essere ottenuta usando la funzione fdf_error().
Vedere anche fdf_error().
fdf_error() restituisce la descrizione testuale per il codice di errore passato in error_code. Qualora non si fornisca error_code, la funzione utilizzerà il codice di errore interno impostato dall'ultima operazione, in questo modo fdf_error() si presenta come una scorciatoia per fdf_error(fdf_errno()).
Vedere anche fdf_errno().
La funzione fdf_get_ap() ottiene informazioni sul campo field (per es. il valore della chiave /AP) e le memorizza in un file. I possibili valori per face sono FDFNormalAP, FDFRolloverAP e FDFDownAP. Il formato è memorizzato in nel file filename.
La funzione estrae un file indicato dal "selettore di file" fieldname e lo memorizza in savepath. Il parametro savepath può essere il nome di file o una directory esistente nella quale verrà creato il file con il suo nome originale. Eventuali file con il medesimo nome saranno sovrascritti.
Nota: Sembra che non ci sia altro metodo per risalire al nome originale del file se non quello di scaricare il file nella directory indicata da savepath e rilevare il nome con cui viene scritto.
La matrice restituita contiene i seguenti indici:
path - percorso in cui viene archiviato il file
size - dimensione del file in bytes
type - mimetype se dato nel FDF
La funzione fdf_get_encoding() restituisce il valore della chiave /Encoding. Resituisce una stringa vuota se non viene utilizzato lo schema PDFDocEncoding/Unicode.
Vedere anche fdf_set_encoding().
La funzione fdf_set_file() restituisce il valore della chiave /F.
Vedere anche fdf_set_file().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione fdf_get_status() restituisce il valore per la chiave /STATUS.
Vedere anche fdf_set_status().
La funzione fdf_get_value() restituisce il valore per il campo fieldname richiesto.
Gli elementi di una matrice di campi possono essere recuperati passando il parametro opzionale which, iniziando da zero. Per i campi non matrice il parametro which viene ignorato.
Nota: Il supporto delle matrici ed il campo opzionale which sono stati aggiunti in PHP 4.3.
Vedere anche fdf_set_value().
(PHP 4 >= 4.3.0, PHP 5)
fdf_get_version -- Restituisce il numero di versione per le API FDF o un fileQuesta funzione restituisce il numero i versione FDF per il dato documento fdf_document, o il numero di versione per il toolkit API, se il parametro viene omesso.
Per il corrente toolkit FDF 5.0 il numero di versione delle API è il '5.0' e il numero di versione del documento può essere '1.2', '1.3' oppure '1.4'.
Vedere anche fdf_set_version().
Questa è una funzione di comodità per impostare le intestazioni HTTP per inviare documenti FDF. La funzione imposta il campo Content-type: a application/vnd.fdf.
La funzione fdf_next_field_name() restituisce il nome del campo successivo al campo indicato in fieldname o il nome del primo campo se è impostato a NULL.
Vedere anche fdf_enum_fields() e fdf_get_value().
La funzione fdf_open_string() ricava i dati di un form da un stringa. Il parametro fdf_data deve contenere dati restituiti da un form PDF o creati dalle funzioni fdf_create() e fdf_save_string().
Si può usare fdf_open_string() insieme a $HTTP_FDF_DATA per elaborare input in un form fdf da un client remoto.
Vedere anche fdf_open(), fdf_close(), fdf_create() e fdf_save_string().
La funzione fdf_open() apre un documento con i dati del form. Il file deve contenere i dati restituiti da un form PDF o creati tramite le funzioni fdf_create() e fdf_save().
Si può processare i risultati del POST di un form PDF scrivento i dati ricevuti da $HTTP_FDF_DATA in un file e aprendolo con fdf_open(). A partire da PHP 4.3 si può anche utilizzare la funzione fdf_open_string(), la quale utilizza un file temporaneo (che poi viene rimosso).
Vedere anche fdf_open_string(), fdf_close(), fdf_create() e fdf_save().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione fdf_save_string() restituisce il documento FDF come una stringa.
Esempio 1. Recupero di un documento FDF come stringa
Visualizzerà qualcosa tipo
|
Vedere anche: fdf_save(), fdf_open_string(), fdf_create() e fdf_close().
La funzione fdf_save() salva un documento FDF. Il risultante documento FDF sarà scritto in filename. Se si omette il parametro filename, la funzione fdf_save() scriverà il documento FDF nel default output di PHP.
Vedere anche: fdf_save_string(), fdf_create() e fdf_close().
La funzione fdf_set_ap() imposta l'apparire di un campo (per es. il valore della chiave /AP). I possibili valori per face sono FDFNormalAP, FDFRolloverAP e FDFDownAP.
La funzione fdf_set_encoding() imposta la codifica dei caratteri per il documento FDF fdf_document. Il parametro encoding deve essere il nome di un codifica valida. I valori attualmente ammessi sono: "Shift-JIS", "UHC", "GBK","BigFive". Una stringa vuota re-imposta la codifica al valore di default PDFDocEncoding/Unicode.
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
fdf_set_file -- Imposta un documento PDF per visualizzare i dati FDF presentiLa funzione fdf_set_file() selezione un differente documento PDF nel quale visualizzare i dati di un form originati da un'altro. Il parametro url deve essere un URL assoluto.
Il frame nel quale visualizzare il documento può essere impostato tramite il parametro target_frame o tramite la funzione fdf_set_target_frame().
Esempio 1. Passaggio di dati FDF a un secondo form
|
Vedere anche fdf_get_file() e fdf_set_target_frame().
La funzione fdf_set_flags() imposta i flag del campo fieldname passato
Vedere anche fdf_set_opt().
La funzione fdf_set_javascript_action() imposta una azione javascript per il campo fieldname passato.
Vedere anche fdf_set_submit_form_action().
(PHP 4 >= 4.3.0, PHP 5)
fdf_set_on_import_javascript -- Adds javascript code to be executed when Acrobat opens the FDFAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
See also fdf_add_doc_javascript() e fdf_set_javascript_action().
La funzione fdf_set_opt() imposta le opzioni del campo fieldname dato.
Vedere anche fdf_set_flags().
La funzione fdf_set_status() imposta il valore per la chiave /STATUS. Quando un client riceve un documento FDF con lo 'status' impostato, ne visualizzerà il valore in una finestra.
Vedere anche fdf_get_status().
(PHP 4 >= 4.0.2, PHP 5)
fdf_set_submit_form_action -- Imposta un'azione per un campo nell'invio di un formLa funzione fdf_set_submit_form_action() imposta un'azione da eseguire nell'invio del form per il campo fieldname.
Vedere anche fdf_set_javascript_action().
Imposta il frame in cui visualizzare il PDF risultante da fdf_save_file().
Vedere anche fdf_save_file().
La funzione fdf_set_value() imposta il campo fieldname al valore value. Il parametro value sarà memorizzato come stringa a meno che non si tratti di una matrice. In questo caso tutti gli elementi della matrice saranno memorizzati in una matrice di valori.
Nota: Nella vecchia versione del toolkit fdf l'ultimo parametro determinava se il valore del campo doveva essere convertito in un PDF Name (isName = 1) o in una stringa PDF (isName = 0). Questo campo non viene più utilizzato con l'attuale versione 5.0. Per motivi di compatibilità è ancora supportato come parametro opzionale a partire da PHP 4.3, ma viene ignorato.
Il supporto per value come matrice è stato aggiunto in PHP 4.3.
Vedere anche fdf_get_value() e fdf_remove_item().
Questa funzione imposta il numero di versione del file FDF fdf_document a version. Alcune caratteristiche supportate da questo modulo sono soltatnto disponibili nelle più recenti versioni di fdf. L'attuale toolkit FDF (5.0) accetta come versione i valori '1.2', '1.3' or '1.4'.
Vedere anche fdf_get_version().
Queste funzioni permettono l'accesso in sola lettura dei dati del database filePro.
filePro è un marchio registrato della tecnologia fP Technologies, Inc. Per maggiori informazioni su filePro: http://www.fptech.com/.
Il supporto a filePro in PHP non è abilitato per default. Per abilitare la funzioni di sola lettura di filePro occorre impostare il parametro di configurazione --enable-filepro durante la compila del PHP.
Restituisce il numero di campi (colonne) di un database filePro aperto.
Vedere anche filepro().
Restituisce il nome del campo riferito all'indice inserito come parametro field_number.
Restituisce il tipo del campo riferito all'indice inserito come parametro field_number.
Restituisce la lunghezza del campo riferito all'indice inserito come parametro field_number.
Restituisce dei dati da una locazione specificata nel database. Il parametro row_number deve essere tra zero ed il numero complessivo delle righe meno uno (0..filepro_rowcount() - 1). In modo analogo il parametro field_number accetta valori compresi tra 0 ed il numero complessivo dei campi meno uno (0..filepro_fieldcount() - 1)
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Restituisce il numero di righe presenti in un database filePro.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Vedede anche filepro().
Questa funzione legge e verifica la mappa del file, immagazzinando l'indice del campo e le informazioni.
Non viene eseguito nessun locking, si dovrebbe evitare di modificare il database filePro mentre quest'ultimo potrebbe venire aperto in PHP.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Non sono richieste librerie esterne per compilare questo modulo, ma se si desidera avere il supporto per LFS (file di grandi dimensioni) su Linux, occorre avere una versione recente di glibc e occorre compilare il PHP con i seguenti parametri: -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Opzioni di configurazione per Filesystem e Streams
Nome | Default | Modificabile |
---|---|---|
allow_url_fopen | "1" | PHP_INI_SYSTEM |
user_agent | NULL | PHP_INI_ALL |
default_socket_timeout | "60" | PHP_INI_ALL |
from | NULL | ?? |
auto_detect_line_endings | "Off" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
Questa opzione abilita i wrapper URL per fopen, in modo da potere accedere ad oggetti URL come file. Per default sono forniti wrapper per accedere a file remoti usando il protocollo ftp o http, alcune estensioni, tipo zlib, possono registrarne altri.
Nota: Questa impostazione può essere impostata solamente nel php.ini per motivi di sicurezza.
Nota: Questa opzione è stata aggiunta subito dopo il rilascio di PHP 4.0.3. Per le versioni fino a 4.0.3 compresa si può disabilitare questa opzione solo al momento della compila utilizzando il parametro di configurazione --disable-url-fopen-wrapper.
Avvertimento |
Nelle versioni precedenti alla 4.3.0 per i sistemi Windows, le suguenti funzioni non supportano l'accesso a file remoti: include(), include_once(), require(), require_once() e le funzioni imagecreatefromXXX nel modulo Riferimento LVI, Funzioni per le immagini. |
Definisce un agente utente il PHP.
Timeout di default (in secondi) per gli stream sui socket.
Nota: Questa opzione di configurazione è stata inserita in PHP 4.3.0
Imposta la password per l'ftp anonimo (il tuo indirizzo di posta elettronica).
Quando è attivato, il PHP esamina i dati letti da fgets() e file() per vedere se si sta utilizzando le convezioni di Unix, MS-Dos o Macintosh.
Questo permette al PHP di operare con sistemi Macintosh, ma, per default, l'opzione è impostata a Off, poichè vi è una piccola penalizzazione di velocità nel cercare di individuare il tipo di EOL per la prima riga; e anche perchè in alcuni casi si è sperimentato che l'utilizzo del carriage-returns come separatore nei sistemi Unix ha generato comportamenti non compatibili con il passato.
Nota: Questa opzione è stata introdotta in PHP 4.3.0
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Vedere anche le sezioni Directory e Esecuzione di programmi.
Per avere un elenco e le spiegazioni sui vari wrapper URL che possono essere utilizzati sui file remoti, vedere Appendice M.
Data una stringa contenente il percorso di un file, questa funzione restituisce il nome del file. Se il nome del file finisce in suffix quest'ultimo verrà tagliato.
Su Windows, sia gli slash (/) che i backslash (\) vengono utilizzati come carattere di separazione delle directory. In altri ambienti, si usa solo lo slash semplice (/).
Nota: Il parametro suffix è stato aggiunto in PHP 4.1.0.
Vedere anche dirname()
Tenta di cambiare il gruppo del file filename in group (specificato per nome o numero). Solo l'amministratore può cambiare arbitrariamente il gruppo di un file; gli altri utenti possono cambiare il gruppo dei file solo fra gruppi di cui sono membri.
Restituisce TRUE se ha successo; FALSE altrimenti.
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Tenta di cambiare le impostazioni del file filename in quelle date in mode.
Si osservi che mode non viene automaticamente assunto come valore ottale, per cui le stringhe (come "g+w") non verranno elaborate correttamente. Per ottenere l'operazione desiderata, è necessario far precedere mode da uno zero (0):
<?php chmod("/somedir/somefile", 755); // decimale; probabilmente errato chmod("/somedir/somefile", "u+rwx,go+rx"); // stringa; errato chmod("/somedir/somefile", 0755); // ottale; valore corretto di mode (preceduto da uno 0) ?> |
Il parametro mode consiste in tre numeri ottali costituenti le restrizioni dell'accesso per il proprietario, il gruppo utente a cui appartiene il proprietario, e gli altri utenti, nell'ordine dato. Ciascun numero può essere calcolato aggiungendo i permessi al valore base per l'utente. Il numero 1 indica che si abilita all'esecuzione del file, con il numero 2 si assegnano i diritti di scrittura, con il numero 4 si assegna il permesso di lettura del file. Aggiungere questi numeri per ottenere i diritti richiesti. Si possono avere maggiori dettagli sui permessi dei sistemi Unix usando il comando 'man 1 chmod' e 'man 2 chmod'.
<?php // Lettura e scrittura per il proprietario, e nessun permesso per gli altri chmod("/somedir/somefile", 0600); // Lettura e scrittura per il proprietario, e lettura per gli altri chmod("/somedir/somefile", 0644); // Accesso completo per il proprietario, e lettura ed esecuzione per gli altri chmod("/somedir/somefile", 0755); // Accesso completo per il proprietario, e lettura ed esecuzione per il gruppo del proprietario chmod("/somedir/somefile", 0750); ?> |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: L'utente corrente è l'utente con il quale viene eseguito il PHP. Probabilmente non è il medesimo utente che si usa da shell o dall'accesso FTP.
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
Nota: Quando modalità sicura viene abilitato, PHP controlla se i files o le directory su cui si sta operando, hanno il medesimo UID (proprietario) dello script che sta per essere eseguito. In aggiunta, non si può impostare il SUID, SGID e sticky bit.
Tenta di cambiare il proprietario di un file filename in user (specificato per nome o numero). Solo l'amministratore può cambiare il proprietario di un file.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Vedere anche chown() e chmod().
Quando si eseguono le funzioni di sistema stat o lstat o una delle funzioni elencate nella lista delle funzioni coinvolte (vedi sotto), il PHP memorizza le informazioni restituite da queste funzioni in modo da fornire migliori performance. Esistono, tuttavia, casi in cui si desidera rimuovere le informazioni memorizzate. Ad esempio, nel caso in cui un file venga controllato più volte nel medesimo script ed il file si trova in situazioni in cui possa venire rimosso o possa essere variato durante l'esecuzione dello script; in questi casi si può volere cancellare le informazioni memorizzate. Per queste situazioni si può utilizzare la funzione clearstatcache() che cancella le informazioni memorizzate dal PHP sullo stato di un file.
Occorre notare che il PHP non memorizza informazioni su file inesistenti. Pertanto se si esegue la funzione file_exists() su un file che non esiste, questa restituisce FALSE fino a quando il file non viene creato. Un volta ccreato il file, la funzione restituisce TRUE anche se il file viene cancellato.
Nota: Queste funzioni memorizzano informazioni su specifici file, pertanto basta eseguire clearstatcache() nel caso di molteplici operazioni sul medesimo file oppure nel caso sia necessario non memorizzare informazioni su un dato file.
Tale valore viene memorizzato solo per la durata di una singola richiesta.
Le funzioni coinvolte sono stat(), lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype() e fileperms().
Copia il file source in dest. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Come da PHP 4.3.0, sia source che dest potrebbero essere URL se "fopen wrappers" è stato abilitato. Vedere fopen() per ulteriori dettagli. Se il parametro dest punta ad un URL, l'operazione di copia potrebbe fallire se il wrapper non supporta la sovrascrittura di file esistenti.
Avvertimento |
Se il file di destinazione già esiste, esso verrà sovrascritto. |
Nota: Nota di compatibilità con Windows: se viene copiato un file vuoto, copy() restituisce falso, ma il file sarà copiato correttamente.
Vedere anche move_uploaded_file(), rename(), e la sezione del manuale riguardo handling file uploads.
Questa funzione non esiste, la sua presenza nel manuale vuole essere utile a coloro che cercano nel posto sbagliato le funzioni unlink() o unset().
Vedere anche unlink() per cancellare file, unset() per eliminare variabili.
Data una stringa contenente il percorso di un file, questa funzione restituirà il nome della directory.
Su windows sia gli slash (/) che i backslash (\) vengono utilizzati come caratteri di separazione nei percorsi. In altri ambienti, c'è solo lo slash in avanti (/).
Nota: In PHP 4.0.3, la funzione dirname() è stata modificata per essere conforme alle specifiche POSIX. Essenzialmente ciò significa che non ci sono slash nel parametro path , viene restituito un punto ('.') per indicare la directory corrente. In altro modo, la stringa restituita è path senza alcun /component. Occorre notare che ciò implica che spesso dalla funzione dirname() si ottiene uno slash od un punto nei casi in cui la vecchia versione avrebbe restituito una stringa vuota.
dirname() ha modificato il suo comportamento dal PHP 4.3.0. Controllare l'esempio:
<?php //prima del PHP 4.3.0 dirname('c:/'); // restituisce '.' //dopo il PHP 4.3.0 dirname('c:/'); // restituisce 'c:' ?> |
dirname() è sicura con i dati binari dal PHP 5.0.0
Vedere anche: basename(), pathinfo() e realpath().
Data una stringa contenente una directory, questa funzione restituirà il numero di byte disponibili nel corrispondente filesystem o nella partizione corrispondente.
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
Vedere anche disk_total_space()
Data una stringa contenente una directory, questa funzione restituirà il numero totale di byte del filesystem o della partizione corrispondente.
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
Vedere anche disk_free_space()
Chiude il file puntato da handle.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il puntatore al file deve essere valido e deve puntare ad un file aperto correttamente da fopen() o da fsockopen().
Restituisce TRUE se il puntatore al file ha raggiunto la fine del file (EOF) o si è verificato un errore (anche in caso di timeout del socket); altrimenti restituisce FALSE.
Avvertimento |
Se una connessione aperta da fsockopen() non è stata chiusa dal server, feof() attenderà finchè un timeout non sia stato raggiunto e restituisce TRUE. Il valore di timeout di default è 60 secondi. Si può usare stream_set_timeout() per cambiare questo valore. |
The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().
Questa funzione forza la scrittura di tutto l'output bufferizzato sulla risorsa puntata dal puntatore handle. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il puntatore al file deve essere valido e deve puntare ad un file correttamente aperto da fopen(), popen() o fsockopen().
The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().
Restituisce una stringa contenente un singolo carattere letto dal file puntato da handle. Restituisce FALSE alla fine del file (EOF).
The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Vedere anche fread(), fopen(), popen(), fsockopen() e fgets().
(PHP 3 >= 3.0.8, PHP 4, PHP 5)
fgetcsv -- Prende una riga da un puntatore a file e l'analizza in cerca di campi CSV
Un puntatore valido a un file che punta a un file aperto con successo da fopen(), popen(), o fsockopen().
Deve essere più grande della linea più lunga (in caratteri) per essere trovato nel file CSV (permettendo di trascinare il carattere di fine linea). E' diventato opzionale in PHP 5.
Setta il delimitatore di campo (un solo carattere). Virgola per default.
Setta il carattere di inclusione nel campo (un solo carattere). Doppie virgolette per default. Aggiunto in PHP 4.3.0.
Simile a fgets() eccetto per il fatto che fgetcsv() analizza le righe lette alla ricerca di campi in formato CSV e restituisce un vettore contenente i campi letti.
Nota: Il parametro enclosure è stato aggiunto in PHP 4.3.0.
Handle deve essere un puntatore valido ad un file correttamente aperto da fopen(), popen() o fsockopen().
Lunghezza deve essere maggiore della linea più lunga trovata nel file CSV (compresi i caratteri di fine riga).
fgetcsv() restituisce FALSE in caso d'errore e al raggiungimento della fine del file.
Nota: Una riga vuota in un file CVS verrà riportata come un vettore contenente un solo campo vuoto (null) e non verrà trattata come un errore.
Esempio 1. Legge e scrive l'intero contenuto di un file CSV.
|
fgetcsv() è diventata binary safe dal PHP 4.3.5
Nota: Se il PHP ha dei problemi a riconoscere la fine riga nella lettura di file su o creati da computer Macintosh, si può abilitare il parametro di configurazione auto_detect_line_endings.
Restituisce una stringa di length - 1 byte letti dal file puntato da handle. La lettura termina quando sono stati letti length - 1 byte, oppure si incontra il carattere di newline (che viene incluso nel valore restituito), oppure alla fine del file (EOF) qualora giunga prima. Se non si specifica length, si assume come default 1k, o 1024 byte.
Se si verifica un errore, la funzione restituisce FALSE.
Errori comuni:
Le persone abituate alla semantica 'C' di fgets notino la differenza nel trattamento dell'EOF.
The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().
Segue un semplice esempio:
Nota: Il parametro length è diventato opzionale a partire da PHP 4.2.0, se omesso, si assume come lunghezza della linea 1024. A partire dalla versione 4.3, l'omissione del parametro length comporta la lettura del flusso d'ingresso sino al raggiungimento della fine della linea. Se la maggior parte delle righe lette dal file hanno dimensione superiore a 8KB, è più efficiente specificare la lunghezza massima della linea.
Nota: A partire da PHP 4.3 questa funzione è 'binary safe'. Le versioni precedenti non lo sono.
Nota: Se il PHP ha dei problemi a riconoscere la fine riga nella lettura di file su o creati da computer Macintosh, si può abilitare il parametro di configurazione auto_detect_line_endings.
Vedere anche fread(), fgetc(), stream_get_line(), fopen(), popen(), fsockopen() e stream_set_timeout().
Identica a fgets(), eccetto per il fatto che fgetss tenta di eliminare tutti i tag HTML e PHP dal testo che legge.
Puoi utilizzare il terzo parametro (opzionale) per specificare quali tag non devono essere eliminati.
Nota: Il parametro allowable_tags è stato aggiunto in PHP 3.0.13, PHP 4.0.0.
Il parametro length è facoltativo dal PHP 5.
Nota: Se il PHP ha dei problemi a riconoscere la fine riga nella lettura di file su o creati da computer Macintosh, si può abilitare il parametro di configurazione auto_detect_line_endings.
Vedere anche fgets(), fopen(), fsockopen(), popen() e strip_tags().
Restituisce TRUE se il file o la directory specificata da filename esiste; FALSE altrimenti.
Sui sistemi Windows utlizzare //computername/share/filename oppure \\computername\share\filename per verificare file su dischi condivisi.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche is_readable(), is_writable(), is_file() e file().
Simile alla funzione file(), tranne che file_get_contents() restituisce il file in una stringa, iniziando allo specificato offset. Se si verifica un errore file_get_contents() restituirà FALSE
Nota: Il parametrooffset è stato aggiunto nel PHP 5.1.0.
Nota: Se si sta aprendo un URI con caratteri speciali, spazi ad esempio, si ha bisogno di decodificare l' URI con urlencode().
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Nota: Il supporto per il contesto è stato aggiunto in PHP 5.0.0. Per la descrizione del contesto, fare riferimento a Riferimento CXLIV, Stream Functions.
Avvertimento |
When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To workaround this, you should lower your error_reporting level not to include warnings. PHP 4.3.7 and higher can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning for you. If you are using fsockopen() to create an ssl:// socket, you are responsible for detecting and suppressing the warning yourself. |
Vedere anche fgets(), file(), fread(), include(), readfile() e file_put_contents().
Identical to calling fopen(), fwrite(), and fclose() successively.
You can also specify the data parameter as an array (not multi-dimension arrays). This is equivalent to file_put_contents($filename, join('', $array)).
As of PHP 5.1.0, you may also pass a stream resource to the data parameter. In result, the remaining buffer of that stream will be copied to the specified file. This is similar with using stream_copy_to_stream().
The file name where to write the data
The data to write. Can be either a string, an array or a stream resource (explained above).
flags can take FILE_USE_INCLUDE_PATH, FILE_APPEND and/or LOCK_EX (acquire an exclusive lock), however the FILE_USE_INCLUDE_PATH option should be used with caution.
A context resource
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Nota: Il supporto per il contesto è stato aggiunto in PHP 5.0.0. Per la descrizione del contesto, fare riferimento a Riferimento CXLIV, Stream Functions.
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Identica a readfile(), eccetto per il fatto che file() restituisce il file in un vettore. Ogni elemento del vettore corrisponde ad una riga del file, con il carattere di newline ancora inserito. Se la funzione non riesce restituisce FALSE.
Puoi impostare il secondo parametro, use_include_path, (opzionale) ad "1", se vuoi cercare il file nel include_path.
<?php // inserisce una pagina web in un array e la stampa. In questo esempio useremo il protocollo // HTTP per ottenere il sorgente di un URL $lines = file('http://www.example.com/'); // Ciclo attraverso l'array, si visualizzerà il sorgente come html ed i numeri di linea foreach($lines as $line_num => $line) { echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n"; } // Un'altro esempio, inserisce la pagina web in una stringa. Vedere anche file_get_contents(). $html = implode('', file ('http://www.example.com/')); ?> |
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Nota: Ciascuna riga dell'array restituito conterrà il carattere di fine riga, occorre, pertanto, utilizzare rtrim() se si desidera rimuovere il carattere di fine riga.
Nota: Se il PHP ha dei problemi a riconoscere la fine riga nella lettura di file su o creati da computer Macintosh, si può abilitare il parametro di configurazione auto_detect_line_endings.
Nota: A partire da PHP 4.3.0 si può utilizzare file_get_contents() per memorizzare il contenuto di un file in una stringa in formato binario.
Nota: Il supporto per il contesto è stato aggiunto in PHP 5.0.0. Per la descrizione del contesto, fare riferimento a Riferimento CXLIV, Stream Functions.
Avvertimento |
When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To workaround this, you should lower your error_reporting level not to include warnings. PHP 4.3.7 and higher can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning for you. If you are using fsockopen() to create an ssl:// socket, you are responsible for detecting and suppressing the warning yourself. |
Vedere anche readfile(), fopen(), fsockopen(), popen(), file_get_contents() e include().
Restituisce l'ora in cui il file ha ricevuto l'ultimo accesso, o FALSE in caso di errore. L'ora viene restituita come un timestamp Unix.
N.B.: Si suppone che l'atime di un file cambi ogni volta che i blocchi di dati del file vengono letti. Ciò può risultare costoso per le performance quando una applicazione accede con regolarità ad un numero elevato di file o directory. Alcuni filesystem Unix possono essere montati con l'aggiornamento dell'atime disabilitato per aumentare le performance di tali applicazioni; Gli spool delle news USENET costituiscono un esempio frequente. In tali filesystem queste funzioni sono inutili.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche filemtime(), fileinode() e date().
Restituisce l'ora in cui il file è stato cambiato l'ultima volta o FALSE in caso d'errore. L'ora viene restituita come un timestamp di Unix.
Nota: In molti filesystem Unix, si considera un file modificato, quando il suo inode viene cambiato; cioè quando i permessi, il proprietario, il gruppo o altri metadata dell'inode vengono aggiornati. Vedere anche filemtime() (che è ciò che ti serve se vuoi inserire la scritta "Ultima modifica: " nel piede delle tue pagine web) e fileatime().
Sappi anche che in alcuni testi su Unix si fa riferimento al ctime di un file come l'ora di creazione dello stesso. E' sbagliato. Nella maggioranza dei filesystem Unix non esiste un oa di creazione.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Esempio 1. Esempio di uso di fileatime()
|
Vedere anche filemtime().
Restituisce il l'ID del gruppo del file, o FALSE in caso d'errore. L'ID del gruppo viene restituito in formato numerico: usa posix_getgrgid() per trasformarlo nel nome del gruppo. In caso di errore la funzione restituisce FALSE accompagnato da un errore di di livello E_WARNING.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche: fileowner() e safe_mode_gid.
Restituisce il numero di inode del file, o FALSE in caso d'errore.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche stat().
Restituisce l'ora dell'ultima modifica al file o FALSE in caso d'errore. L'ora viene restituita come un timestamp di Unix.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Nota: Questa funzione restituisce l'ora in cui i blocchi di dati di un file vengono scritti, cioè l'ora in cui il contenuto del file è cambiato.
Vedere anche filectime(), stat(), touch() e getlastmod().
Restituisce l'ID dell'utente proprietario del file, o FALSE in caso di errore. L'ID dell'utente viene restituito in formato numerico, usa posix_getpwuid() per trasformarlo nel nome dell'utente stesso.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche stat()
Restituisce i permessi sui file, or FALSE in caso di errore.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Esempio 2. Mostra gli interi permessi
Ciò produrrà il seguente output:
|
Vedi anche is_readable(), e stat()
Restituisce la dimensione di un file, o FALSE in caso d'errore.
Nota: Poichè il PHP tratta i tipi interi con il segno e diverse piattaforme utilizzano interi a 32 bit, filesize() può restituire valori non attendibili con file di dimensioni maggiori di 2GB. Per file con dimensione tra 2GB e 4GB si può tentare di ovviare utilizzando sprintf("%u", filesize($file)).
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche file_exists()
Restituisce il tipo del file. Sono valori possibili fifo, char, dir, block, link, file e unknown.
Restituisce FALSE se si verifica un errore. Inoltre la funzione filetype() genera un errore di livello E_NOTICE se fallisce la chiamata a stat o se il tipo è sconosciuto.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche: is_dir(), is_file(), is_link(), file_exists(), stat() e mime_content_type().
Il PHP supporta un tecnologia portabile per bloccare file completi in modalità advisory (tutti i programmi che vi accedono, devono usare lo stesso tipo di bloccaggio o non funzionerà).
Nota: flock()è obbligatorio sotto Windows.
flock() opera su handle che deve essere un puntatore ad un file aperto. operation può assumere uno dei valori seguenti:
Per acquisire una chiave condivisa (in lettura), imposta operation a LOCK_SH (usa 1 prima di PHP 4.0.1).
Per acquisire una chiave esclusiva (in scrittura), imposta operation a LOCK_EX (usa 2 prima di PHP 4.0.1).
Per rilasciare una chiave (condivisa o esclusiva), imposta operation a LOCK_UN (usa 3 prima PHP 4.0.1).
Se non vuoi che flock() blocchi mentre, imposta come LOCK_NB (4 prima di PHP 4.0.1) operation.
flock() ti permette di utilizzare un semplice modello di lettura/scrittura che in teoria può essere usato su qualsiasi piattaforma (inclusi molti sistemi Unix e anche Windows). Il terzo argomento (opzionale) può essere impostato a TRUE se la chiave puo bloccare (EWOULDBLOCK errno condition). Il blocco è realizzato anche da fclose() (che è anche richiamata automaticamente quando lo script termina).
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Poiché flock() richiede il puntatore ad un file, può occorre utilizzare un speciale file di lock per proteggere l'accesso a eventuali file che si desidera azzerare attraverso l'apertura in modalità di scrittura (usando "w" o "w+" come argomento di fopen()).
Avvertimento |
La funzione flock() non funzione con NFS e con diversi altri file system di rete. Verificare sulla documentazione del proprio sistema operativo. Su molti sistemi operativi flock() è implementato a livello di processo. Usando un server API multithread quale ISAPI non potrai basarti su flock() per proteggere i file da altri script PHP che girino in thread paralleli della stessa istanza del server! La funzione flock() non è supportata su file system antiquati tipo FAT e i suoi derivati e pertanto in tali ambienti restituirà sempre FALSE (questo è vero soprattutto per gli utenti di Windows 98). |
fnmatch() checks if the passed string would match the given shell wildcard pattern.
This is especially useful for filenames, but may also be used on regular strings. The average user may be used to shell patterns or at least in their simplest form to '?' and '*' wildcards so using fnmatch() instead of ereg() or preg_match() for frontend search expression input may be way more convenient for non-programming users.
Avvertimento |
For now this function is not available on Windows or other non-POSIX compliant systems. |
See also glob(), ereg(), preg_match() and the Unix manpage on fnmatch(3) for flag names (as long as they are not documented here ).
La funzione fopen() apre un collegamneto tra una risorsa, indicata dal parametro filename, ed un flusso. Se il parametro filename è del tipo "scheme://...", si assume essere un URL ed il PHP cercherà il modulo di gestione del protocollo (detto anche wrapper) per quello schema. Se non vi sono wrapper registrati per il protocollo richiesto, il PHP genererà un messaggio per aiutare a trovare potenziali problemi nello script e quindi procede considerando filename come un file regolare.
Se il PHP ha stabilito che filename indica un file locale, tenterà di aprire detto file come stream. Il file in oggetto dovrà esere accessibile dal PHP, occorre, pertanto, assicurasi che i permessi di accesso del file lo consentano. Se si è attivato il modalità sicura, oppure open_basedir si avranno ulteriori restrizioni.
Se il PHP ha stabilito che filename indica un protocollo registrato, e che tale protocollo è registrato come un URL di rete, il PHP verificherà che allow_url_fopen sia abilitato.Se fosse disabilitato, il PHP genererà un 'notice' e la funzione fallirà.
Nota: L'elenco dei protocolli supportati si trova in Appendice M. Alcuni protocolli (indicati anche come wrappers) supportano il context e/o le opzioni del php.ini Fare riferimento alle pagine specifiche del protocollo per avere l'elenco delle opzioni che possono essere utilizzate. (Ad esempio il parametro del php.ini user_agent è utilizzato dal wrapper http) Per una descrizione del contexts e del zcontext, fare riferimento a Riferimento CXLIV, Stream Functions.
Nota: Il supporto per il contesto è stato aggiunto in PHP 5.0.0. Per la descrizione del contesto, fare riferimento a Riferimento CXLIV, Stream Functions.
Nota: Come per PHP 4.3.2, la modalità di default è impostata a binarioper tutte le piattaforme che distinguono tra modalità binaria e testuale. Se si hanno problemi con i propri script dopo l'aggiornamento, provare a utilizzare il flag 't' come sostitutivo finchè si ha completato uno script maggiormente portabile come richiesto sopra.
Il parametro mode indica il tipo di accesso richiesto per il flusso. Esso può essere:
Tabella 1. Elenco dei possibili valori usati da fopen() per il parametro mode
mode | Descrizione |
---|---|
'r' | Apre in sola lettura; posiziona il puntatore all'inizio del file. |
'r+' | Apre in lettura e scrittura; posiziona il puntatore all'inizio del file. |
'w' | Apre il file in sola scrittura; posiziona il puntatore all'inizio del file e tronca il file alla lunghezza zero. Se il file non esiste, tenta di crearlo. |
'w+' | Apre in lettura e scrittura; posiziona il puntatore all'inizio del file e tronce il file alla lunghezza zero. Se il file non esiste, tenta di crearlo. |
'a' | Apre in sola scrittura; posiziona il puntatore alla fine del file. Se il file non esiste, tenta di crearlo. |
'a+' | Apre in lettura e scrittura; posiziona il puntatore alla fine del file. Se il file non esiste, tenta di crearlo. |
'x' | Crea ed apre il file in sola scrittura; posiziona il puntatore all'inizio del file. Se il file esiste già la chiamata a fopen() fallirà restituendo FALSE e verrà generato un errore di lievllo E_WARNING. Se il file non esiste si tenterà di crearlo. Questo equivale a specificare i flag O_EXCL|O_CREAT nella sottostante chiamata a open(2) . Questa opzione è supportata a partire dalla versione 4.3.2 di PHP, e funziona solo con i file locali. |
'x+' | Crea ed apre il file in lettura e scrittura; posiziona il puntatore all'inizio del file. Se il file esiste già la chiamata a fopen() fallirà restituendo FALSE e verrà generato un errore di lievllo E_WARNING. Se il file non esiste si tenterà di crearlo. Questo equivale a specificare i flag O_EXCL|O_CREAT nella sottostante chiamata a open(2) . Questa opzione è supportata a partire dalla versione 4.3.2 di PHP, e funziona solo con i file locali. |
Nota: Differenti famiglie di file system hanno differenti tipi di terminatori di riga. Quando si scrive un file di testo e si desidera inserire una interruzione di linea, occorre utilizzare il terminatore appropriato per il sistema operativo utilizzato. I sistemi basati su Unix utilizzano \n come terminatore di riga, i sistemi basati su Windows utilizzano \r\n mentre i sistemi Macintosh utilizzano \r.
Se si utilizza un errato terminatore di riga quando si scrivono i file, si può verificare che altre applicazioni accedendo a questi file abbiano comportamenti bizzarri.
Windows ha un flag di traduzione della modalità testo ('t') che in modo trasparente converte \n in \r\n mentre si lavora sul file. Ovviamente si ha anche il flag 'b' per forzare una modalità binaria, nella quale non si ha la conversione dei dati. Se si usano questi flag, 'b' oppure 't', devono essere posizionati come ultimo carattere del parametro mode.
La modalità di conversione di default dipende dalla SAPI e dalla versione di PHP che si sta utlizzando, pertanto si incoraggia l'uso dei flag appropriati per aumentare la portabilità degli script. Si dovrebbe utilizzare 't' se si lavora con dei file di testo, e si utilizza \n per indicare il fine linea, e ci si aspetta che che altre applicazioni, tipo notepad, leggano il file prodotto. In tutti gli altri casi si dovrebbe utilizzare 'b'
Se non si specifica il flag 'b' quando si lavora con file binari, si possono avere situazioni anomale nei dati, tipo immagini corrotte, e situazioni anomale con i caratteri \r\n.
Nota: Per la portabilità, si consiglia vivamente di usare sempre il flag 'b' quando si aprono files con fopen().
Nota: Inoltre, sempre per la portabilità, è anche fortemente raccomandato di aggiornare il codice che utilizza o che si avvale del mode 't' così da utilizzare il corretto terminatore di linea invece del 'b' mode.
Il terzo parametro opzionale use_include_path può essere impostato a '1' oppure a TRUE se si desidera cercare il file in include_path.
Se la open fallisce, la funzione restituisce FALSE e viene generato un errore di tipo E_WARNING. Si può utilizzare @ per sopprimere questo warning.
Se si dovessero manifestare dei problemi nella lettura o scrittura di file e si sta utilizzando la versione server di PHP, occorre verificare che i file e le directory utilizzate dallo script siano accessibili dal processo del server.
Sulla piattaforma Windows occorre prestare attenzione ai backslash nei percorsi dei file; questi devono essere preceduti dal caratteri di escape '\', oppure utilizzare lo slash '/'.
Avvertimento |
When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To workaround this, you should lower your error_reporting level not to include warnings. PHP 4.3.7 and higher can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning for you. If you are using fsockopen() to create an ssl:// socket, you are responsible for detecting and suppressing the warning yourself. |
Nota: Quando safe-mode è abilitato, PHP controlla che la directory nella quale si sta lavorando, abbia lo stesso UID dello script che è in esecuzione.
Vedere anche Appendice M, fclose(), fgets(), fread(), fwrite(), fsockopen(), file(), file_exists(), is_readable(), stream_set_timeout() e popen().
Legge fino a EOF sul puntatore al file dato e scrive i risultati sul buffer di output.
Se si verifica un errore, fpassthru() restituisce FALSE. In caso positivo fpassthru() restituisce il numero di caratteri letti da handle scritti in output.
The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().
Può essere necessario chiamarerewind() per resettare il puntatore al file all'inizio del file stesso nel caso si abbbia già scritto dai dati nel file. Il file viene chiuso quando si sia chiamata fpassthru() leggendolo (lasciandohandle inutilizzato).
Se desideri semplicemente inviare il contenuto di un file sul buffer di output, senza doverlo modificare o posizionarti in un particolare offset, potresti preferire readfile(), che ti salva la chiamata a fopen().
Nota: Quando si utilizza fpassthru() con file binari su sistemi Windows si dovrebbe essere certi di aprire il file in modalità binaria aggiungendo b alla modalità utilizzata nella chiamata a fopen().
Si incoraggia l'uso del flag b quando si trattano file binari, anche se il sistema non lo richiede; in questo modo si rendono gli script più trasportabili.
Esempio 1. Utilizzo di fpassthru() con file binari
|
Vedere anche readfile(), fopen(), popen() e fsockopen()
fputcsv() formats a line (passed as a fields array) as CSV and write it to the specified file handle. Returns the length of the written string, or FALSE on failure.
The optional delimiter parameter sets the field delimiter (one character only). Defaults as a comma: ,.
The optional enclosure parameter sets the field enclosure (one character only) and defaults to a double quotation mark: ".
Nota: Se il PHP ha dei problemi a riconoscere la fine riga nella lettura di file su o creati da computer Macintosh, si può abilitare il parametro di configurazione auto_detect_line_endings.
See also fgetcsv().
fread() legge fino a length byte dal puntatore al file indicato da handle. La lettura finisce quando sono stati letti length byte o è stata raggiunta EOF, o (nel caso di flussi via rete) quando un pacchetto divnta disponibile, in base a quale evento accada prima.
<?php // copia il contenuto di un file in una stringa $filename = "/usr/local/something.txt"; $handle = fopen($filename, "r"); $contents = fread($handle, filesize($filename)); fclose($handle); ?> |
Avvertimento |
Sui sistemi che differenziano fra file di testo e binari (ad esempio Windows) il file deve essere aperto con il parametro mode di fopen() impostato a 'b'. |
<?php $filename = "c:\\files\\somepic.gif"; $handle = fopen($filename, "rb"); $contents = fread($handle, filesize($filename)); fclose($handle); ?> |
Avvertimento |
Quando si ricevono dati via rete o pipe, tipo quelli ottenuti leggendo da file remoti o da popen() e fsockopen(), la lettura si fermerà dopo avere ricevuto il pacchetto disponibile. Questo significa che i dati sono ricevuti a blocchi che devono essere raggruppati, come illustrato nell'esempio seguente. |
<?php $handle = fopen("http://www.example.com/", "rb"); $contents = ''; while (!feof($handle)) { $contents .=fread($handle, 8192); } $contents .= $data; } while (true); fclose($handle); ?> |
Nota: Se si desidera ottenere il contenuto del file in una stringa, utilizzare la funzione file_get_contents() la quale è ancora più performante del codice precedente.
Vedere anche fwrite(), fopen(), fsockopen(), popen(), fgets(), fgetss(), fscanf(), file() e fpassthru().
La funzione fscanf() è simile a sscanf(), ma prende il proprio input da un file associato con handle e interpreta l'input in accordo con il parametro format, che viene descritto nella documentazione della funzione sprintf(). Se vengono passati solo due parametri a questa funzione, i valori esaminati verranno restituiti in un vettore. Altrimenti, se vengono passati i parametri opzionali, la funzione restituirà il numero dei valori assegnati. I parametri opzionali devono essere passati da reference.
Ogni spazio nella stringa di formato identifica uno spazio nel flusso di input. Questo significa che anche i tab \t presenti nella stringa di formato possono identiicare uno spazio nel flusso di input.
Nota: Nelle versioni di PHP precedenti alla 4.3.0, il numero massimo di caratteri letti da un file era di 512 (o fino al primo \n, dipende da quale si incontra prima). Dal PHP 4.3.0 si possono esaminare linee di lunghezza arbitraria.
Vedere anche fread(), fgets(), fgetss(), sscanf(), printf() e sprintf().
Imposta l'indicatore di posizione del file riferito da handle. La nuova posizione, misurata in byte dall'inizio del file, si ottiene aggiungendo offset alla posizione specificata da whence, i cui valori sono definiti come segue:
SEEK_SET - Imposta la posizione uguale a offset byte. |
SEEK_CUR - Imposta la posizione alla attuale più offset. |
SEEK_END - Imposta la posizione alla fine del file più offset. (To move to a position before the end-of-file, you need to pass a negative value in offset.) |
Se whence non viene specificato, viene assunto come SEEK_SET.
In caso di successo, restituisce 0; altrimenti, restituisce -1. Nota che spostarsi oltre EOF non è considerato un errore.
Non può essere usato su puntatori a file restituiti da fopen() se è in uso il formato "http://" o "ftp://". fseek() da anche risultati non definiti per stream in modalità append-only (aperti con il flag "a").
Nota: L'argomento whence è stato aggiunto dopo PHP 4.0.0.
(PHP 4, PHP 5)
fstat -- Restituisce le informazioni riguardanti un file attraverso un puntatore al file apertoRestituisce le statistiche del file aperto dal puntatore handle. Questa funzione è simile a stat() eccetto per il fatto che opera su un puntatore a file aperto invece che su un nome di file.
Restituisce un vettore con le statistiche del file con il formato del vettore è descritto nella pagina di stat().
Esempio 1. Esempio di uso di fstat()
l'esempio visualizzerà :
|
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
Restituisce la posizione del puntatore al file indicato da handle; cioè, il suo offset all'interno del flusso del file.
Se si verifica un errore, restituisce FALSE.
Il puntatore al file deve essere valido e deve puntare ad un file aperto correttamente da fopen() o da popen(). ftell() da risultati non definiti per stream in modalità append-only (aperti col flag "a").
Prende il puntatore al file handle e tronca il file alla lunghezza indicata da size. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
fwrite() scrive il contenuto di string nel flusso del file puntato da handle. Se l'argomento length è specificato la scrittura si arresterà dopo aver scritto length byte o alla fine di string se si verificasse prima.
fwrite() returns the number of bytes written, or FALSE on error.
Nota che se il parametro length viene specificato, allora l'opzione di configurazione magic_quotes_runtime verrà ignorata e nessuno slash verrà skippato da string.
Nota: Su sistemi che differenzino fra file binari e di testo (come Windows) il file deve essere aperto includendo 'b' nel paramentro mode di fopen().
Esempio 1. Un semplice esempio di fwrite
|
Vedere anche fread(), fopen(), fsockopen(), popen() e file_put_contents().
The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells. No tilde expansion or parameter substitution is done.
Returns an array containing the matched files/directories or FALSE on error.
Valid flags:
GLOB_MARK - Adds a slash to each item returned
GLOB_NOSORT - Return files as they appear in the directory (no sorting)
GLOB_NOCHECK - Return the search pattern if no files matching it were found
GLOB_NOESCAPE - Backslashes do not quote metacharacters
GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c'
GLOB_ONLYDIR - Return only directory entries which match the pattern
Nota: Before PHP 4.3.3 GLOB_ONLYDIR was not available on Windows and other systems not using the GNU C library.
GLOB_ERR - Stop on read errors (like unreadable directories), by default errors are ignored
Nota: GLOB_ERR was added in PHP 5.1
Esempio 1. Convenient way how glob() can replace opendir() and friends.
Output will look something like:
|
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
See also opendir(), readdir(), closedir(), and fnmatch().
Restituisce TRUE se il nome file esiste ed è una directory. Se filename è un nome file relativo, verrà controllato relativamente alla directory di lavoro in uso.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche chdir(), dir, opendir(), is_file() e is_link().
Restituisce TRUE se il filename esiste ed è un eseguibile.
La funzione is_executable() sarà disponibile sui sistemi Windows a partire dalla versione 5.0.0 di PHP.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Restituisce TRUE se il filename esiste ed è un file regolare.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Restituisce TRUE se il filename esiste ed è un link simbolico.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Restituisce TRUE se filename esiste ed è leggibile.
Ricorda che PHP può accedere al file come l'utente che è rappresentato dal server (spesso 'nobody'). Non sono prese in conto limitazione di sicurezza.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche is_writable(), file_exists() e fgets().
(PHP 3 >= 3.0.17, PHP 4 >= 4.0.3, PHP 5)
is_uploaded_file -- Dice se un file fù caricato via HTTP POST.Restituisce TRUE se il file chiamato per filename è stato spedito in upload col metodo HTTP POST. Ciò è utile per rendere sicuro il fatto da un utente malizioso non abbia cercato di forzare uno script ad agire sul file sul quale non dovrebbe essere svolto alcun lavoro--ad esempio, /etc/passwd.
Questo controllo è particolarmente importante in caso esista una qualunque possibilità che una qualunque cosa che viaggia durante l'upload del file, possa rivelarne il contenuto all'utente, o anche ad altri utenti che operano sullo stesso sistema.
is_uploaded_file() è disponibile solo nella versione PHP 3, dopo la 3.0.16, e nella versione 4 dopo la 4.0.2. Se hai delle perplessità nell'usare una versione più recente, puoi utilizzare una delle seguenti funzioni per proteggere te stesso:
Nota: L'esempio seguente not lavorerà con le versioni PHP 4 dopo la 4.0.2. Ciò dipende da funzionalità interne a PHP che sono variate dopo tale versione.
Esempio 1. is_uploaded_file() example
|
Vedi anche move_uploaded_file(), e la sezione Handling file uploads per un semplice esempio di utilizzo.
Restituisce TRUE se filename esiste ed è scrivibile. L'argomento filename può essere un nome di directory che ti permetta di verificare se una directory è scrivibile.
Tieni presente che PHP può accedere al file con lo user id del web server (spesso 'nobody'). Non sono prese in considerazioni limitazioni di sicurezza.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche is_readable(), file_exists() e fwrite().
link() crea un hard link. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
Nota: Questa funzione non è implementata su piattaforme Windows
Vedere anche symlink() per creare soft link, e readlink() assieme a linkinfo().
linkinfo() restituisce il st_dev campo della struttura stat dello Unix C restituita dalla chiamata di sistema lstat. Questa funzione è usata per verificare se un link (puntato da path) esiste davvero (usando lo stesso metodo della macro S_ISLNK definita in stat.h). Restituisce 0 o FALSE in caso di errore.
Nota: Questa funzione non è implementata su piattaforme Windows
Vedere anche symlink(), link() e readlink().
Raccoglie le statistiche del file o del link simbolico chiamato filename.. Questa funzione è identica alla funzione stat() eccetto che se il paramametro filename è un link simbolico valido, viene restituito lo stato del link simbolico, non lo stato del file puntato dal link simbolico.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche stat().
Tenta di creare la directory specificata da pathname.
Nota che probabilmente vuoi specificare mode come un ottale, per cui deve iniziare con uno zero. La modalità è anche modificata dall'umask corrente, che puoi cambiare con umask().
Nota: Il parametro mode è ignorato sui sistemi Windows, ed è opzionale dal PHP 4.2.0.
Il parametro mode viene impostato a 0777 per default; ciò significa dare i maggiori accessi possibili. Per maggiori dettagli sui valori di mode, leggere le pagine relative a chmod().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: A partire da PHP 5.0.0 la funzione mkdir() può anche essere utilizzata con alcuni wrapper URL. Fare riferimento a Appendice M per avere l'elenco dei wrapper supportati da mkdir().
Nota: I parametri recursive e context sono stati aggiunti in PHP 5.0.0.
Nota: Quando safe-mode è abilitato, PHP controlla che la directory nella quale si sta lavorando, abbia lo stesso UID dello script che è in esecuzione.
Vedere anche rmdir().
Questa funzione verifica che il file indicato da filename è un file validamente caricato (nel senso che è stato caricato attraverso il meccanismo di caricamento HTTP POST di PHP). Se il file è valido, verrà spostato nel file dato da destination.
Se filename non è un file validamente caricato, allora non verrà compiuta alcuna azione e move_uploaded_file() restituirà FALSE.
Se filename è un file validamente caricato, ma non può essere mossi per qualche ragione, non verrà compiuto alcunchè e move_uploaded_file() restituirà FALSE. In più verrà visualizzato un avviso di pericolo.
Questo tipo di verifica è particolarmente importante se sussiste la possibilità che qualcosa fatto con i file caricati possa rivelare il loro contenuto agli utenti o ad altri utenti dello stesso sistema.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Nota: move_uploaded_file() non è limitato dalle normali restrizioni del modalità sicura UID. QCiò non è insicuro poichè move_uploaded_file() operara solo sui file uplodati via PHP.
Avvertimento |
Se il file di destinazione esiste, sarà sovrascritto. |
Vedere anche is_uploaded_file() e la sessione Handling file uploads per un semplice esempio.
La funzione parse_ini_file() carica il file ini specificato da filename, e restituisce le impostazioni in un array associativo. Impostando process_sections a TRUE si ottiene una matrice multi-dimensionale con in nomi delle sezioni e le impostazioni ivi incluse. Per default process_sections è impostato a falso FALSE
Nota: Questa funzione non è collegata con il file php.ini. Questo è già elaborato al momento in cui gira lo script. Questa funzione può essere utilizzata per leggere i file ini propri dell'applicazione.
Nota: Se in un valore il file ini contiene caratteri non alfanumerici questi debbono essere delitimitati dai doppi apici (").
Nota: Dalla versione 4.2.1 di PHP questa funzione è limitata da by modalità sicura e da open_basedir.
Nota: Esistono parole riservate che non possono essere utilizzare come chiavi nei file ini. Queste includono: null, yes, no, true, and false.
La struttura del file ini è simile a quella del php.ini.
Le Costanti possono essere definite in un file ini, quindi se si definisce la costante come un valore da file ini prima di eseguire parse_ini_file(), la funzione integrerà nella costante il valore letto. Saranno considerati solo i valori ini. Ad esempio:
Esempio 2. Esempio di uso di parse_ini_file()
L'esempio produrrà:
|
La chiavi e le sezioni composte da numeri come considerate dal PHP come interi quindi i numeri che iniziano con 0 sono trattati come numeri ottali, e inumeri che iniziano con 0x sono considerati esadecimali.
pathinfo() restituisce un vettore associativo contenente informazioni riguardo path. Nel vettore vegono riportati i seguenti elementi: dirname, basename e extension.
Si può specificare quali elementi vengano restituiti con parametri opzionali options. E' composto da PATHINFO_DIRNAME, PATHINFO_BASENAME e PATHINFO_EXTENSION. Assume per defalut la restituzione di tutti gli elementi.
Nota: Per informazioni su come recuperare il path corrente, leggere la sezione su variabili riservate predefinite.
Vedere anche dirname(), basename(), parse_url() e realpath().
Chiude un puntatore ad una pipe aperto da popen().
Il puntatore deve essere valido e deve essere stato restituito da un chiamata a popen() terminata con successo.
Restituisce lo stato di terminazione del processo che stava girando.
Vedere anche popen().
Apre una pipe ad un processo eseguito forzando il comando dato da command.
Restituisce un puntatore a file identico a quello restituito da fopen(), eccetto che per il fatto che è unidirezionale (può solo essere usato per la lettura o la scrittura) e deve essere chiudo con pclose(). Questo puntatore può essere usato con fgets(), fgetss() e fwrite().
Se si verifica un errore, restituisce FALSE.
Nota: Se si sta cercando un supporto bi-direzionale (2 vie), utilizzare proc_open().
Se il comando che deve essere eseguito non è trovato, la funzione restituisce una risorsa valida. Questo sembra strano, ma ha un senso; esso permette di accedere ai messaggi di erore restituiti dalla shell:
<?php error_reporting(E_ALL); /* Aggiunge una redirezione, così possiamo ottenere stderr. */ $handle = popen('/path/to/spooge 2>&1', 'r'); echo "'$handle'; " . gettype($handle) . "\n"; $read = fread($handle, 2096); echo $read; pclose($handle); ?> |
Nota: Quando si abilita la modalità sicura, si può eseguire soltanto gli eseguibili presenti nella directory safe_mode_exec_dir. Per motivi pratici, attualmente, non ` permesso avere .. come componente del percorso di un eseguibile.
Avvertimento |
Con la modalità sicura attivata, tutte le parole che seguono il comando iniziale sono trattate come argomenti. Quindi, echo y | echo x diventa echo "y | echo x". |
Vedere anche pclose(), fopen() e proc_open().
Legge un file e lo scrive nello standard output.
Restituisce il numero di byte letti dal file. Se si verifica un errore viene restituito FALSE e se la funzione non è stata chiamata come @readfile(), un messaggio d'errore verra stampato.
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Puoi settare il secondo parametro opzionale ad TRUE, se vuoi anche cercare il file nella include_path.
Vedere anche fpassthru(), file(), fopen(), include(), require() virtual(), file_get_contents() e Appendice M.
readlink() si comporta analogamente alla funzione readlink di C e restituisce i conenuti del link simbolico path oppure FALSE in caso d'errore.
Nota: Questa funzione non è implementata su piattaforme Windows
Vedere anche symlink(), readlink() e linkinfo().
realpath() espande tutti i link simbolici e risolve i riferimenti a '/./', '/../' ed altri caratteri '/' nell'input path e restituisce il percorso assoluto canonizzato. Il percorso risultante non avrà link simbolici, '/./' o '/../'.
realpath() restituisce FALSE in caso di fallimento, per esempio se il file non esiste.
Vedere anche basename(), dirname() e pathinfo().
Tenta di rinominare oldname in newname.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Nelle versioni di PHP precedenti alla 4.3.3, la funzione rename() non può rinominare file attraverso partizioni nei sistemi *nix.
Nota: Dal PHP 5.0.0 rename() può anche essere utilizzata con qualche wrapper URL. Fare riferimento a Appendice M per avere l'elenco dei wrapper supportati da rename().
Nota: Il wrapper utilizzato per oldname DEVE essere il medesimo utilizzato per newname.
Nota: Il parametro context è stato aggiunto in PHP 5.0.0.
Vedere anche copy(), unlink() e move_uploaded_file().
Pone l'indicatore alla posizione del file per handle all'inizio del flusso del file.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il puntatore al file deve essere valido e deve puntare ad un file aperto con successo da fopen().
Nota: If you have opened the file in append ("a") mode, any data you write to the file will always be appended, regardless of the file position.
Tenta di cancellare la directory indiata da pathname. La directory deve essere vuota e i permessi concessi devono permetterlo. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Dal PHP 5.0.0 rmdir() può anche essere utilizzata con qualche wrapper URL. Fare riferimento a Appendice M per avere l'elenco dei wrapper supportati da rmdir().
Nota: Il parametro context è stato aggiunto in PHP 5.0.0.
Nota: Quando safe-mode è abilitato, PHP controlla che la directory nella quale si sta lavorando, abbia lo stesso UID dello script che è in esecuzione.
Restituisce una serie di informazioni a riguardo del file filename. Se il parametro filename è un link simbolico, le informazioni riguardano il file stesso, e non il file puntato dal link. La funzione lstat() è identica a stat() tranne che dovrebbe restituire il file puntato dal link.
In caso di errore stat() restituisce FALSE. Inoltre genera un warning.
La funzione restituisce un vettore con le informazioni sul file contenente i seguenti elementi. Il vettore parte dall'indice zero. Oltre agli indici numerici il vettore contiene indici associativi, come sarà indicato per ciascun parametro; questo è disponibile dal PHP versione 4.0.6.
Tabella 1. Formato del vettore restituito da stat() e fstat()
Indice numerico | Associativo (da PHP 4.0.6) | Descrizione |
---|---|---|
0 | dev | device |
1 | ino | inode |
2 | mode | modalità di protezione dell'inode |
3 | nlink | numero di link |
4 | uid | ID utente del proprietario |
5 | gid | ID del gruppo del proprietario |
6 | rdev | tipo di device con l'inode device * |
7 | size | dimensione in byte |
8 | atime | ora dell'ultimo accesso (Unix timestamp) |
9 | mtime | ora del'ultima modifica (Unix timestamp) |
10 | ctime | ora dell'ultimo cambiamento di inode(Unix timestamp) |
11 | blksize | dimensione del blocco per l'I/O di filesystem * |
12 | blocks | numero dei blocchi allocati |
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche lstat(), fstat(), filemtime() e filegroup().
symlink() crea un link simbolico dal target esistente con il nome specificato da link.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Questa funzione non è implementata su piattaforme Windows
Vedere anche link() per creare hard link, e readlink() con linkinfo().
Crea un file con filename univoco nella directory specificata. Se la directory non esiste, tempnam() può generare un file in una directory temporanea di sistema, e restituire il nome di quest'ultima.
Precedentemente al PHP 4.0.6, il comportamento della funzione tempnam() dipendeva dal sistema. Su Windows il dispositivo di variabli TMP sovrascrive il dir parametro, su Linux la variabile TMPDIR ha la precedenza, mentre SVR4 utilizzerà sempre il parametro dir se la directory a cui punta, esiste. Consultare la vostra documentazione sulla funzione tempnam(3) in caso di dubbi.
Nota: Se PHP non può creare un file nello specificato dir parametro, ritorna al default di sistema.
Restituisce il nuovo nomefile temporaneo, o FALSE in caso di errore.
Nota: Il funzionamento di questa funzione è cambiato nella 4.0.3. Il file temporaneo è creato inoltre èer evitare un conflitto dove il file dovrebbe apparire nel filesystem tra la volta in cui la stringa viene generata e prima che lo script tenti di creare il file. Notare che se si necessita cancellare il file, se non servisse più, non viene fatto automaticamente.
Crea un file temporaneo con un nome univoco in modalità di lettura-scrittura (w+), restituendo un riferimento al file simile a quello tornato da fopen(). Il file viene automaticamente cancellato una volta chiuso (usando fclose()), o quando lo script termina.
Per dettagli, consulta la documentazione del tuo sistema sulla funzione tmpfile(3), così come il file haeader stdio.h.
Vedere anche tempnam().
Tenta di impostare l'ora di modifica del file indicato da filename. Se il parametro time non è passato, usa l'ora attuale. Ciò equivale a quello che fa utime (a volte indicato come utimes). Se è presente il terzo parametro opzionale atime è presente, viene utilizzato per impostare l'orario di accesso al file indicato. Occorre rilevare che l'orario di accesso è sempre modificato, indipendentemente dal numero dei parametri.
Se il file non esiste, viene creato.
umask() imposta l'umask di PHP a mask & 0777 e restituisce il vecchio umask. Quando PHP è utilizzato come modulo server, l'umask viene ripristinato quando ciascuna richiesta è finita.
umask() senza argomenti restituisce semplicemente l'umask corrente.
Cancella filename. Simile alla funzione C di Unix unlink(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Dal PHP 5.0.0 unlink() potrà essere utilizzata anche con qualche wrapper URL. Fare riferimento a Appendice M per avere la lista di quali wrapper supportano unlink().
Nota: Il parametro context è stato aggiunto in PHP 5.0.0.
Restituisce 0 o FALSE in caso d'errore.
Vedere anche rmdir() per eliminare directory.
Firebird/InterBase è un database relazionale che offre diverse features ANSI SQL-92 che gira su sistemi Linux, Windows, e su diverse piattaforma Unix. Firebird/InterBase offre un'eccellente meccanismo di concorrenza, alte performance, ed un potente linguaggio a supporto per le stored procedure ed i trigger. E' attivo in sistemi di produzione, sotto diversi nomi, dal 1981.
InterBase è il nome della versione protetta di questo RDBMS che fu sviluppata da Borland/Inprise. Maggiori informazioni su InterBase sono disponibili al link http://www.borland.com/interbase/.
Firebird è un progetto commercialmente indipendente di programmatori C e C++, tecnici, supporter che hanno sviluppato e migliorato un database relazionale multi-piattaforma basato sul codice sorgente rilasciato da Inprise Corp (ora nota come Borland Software Corp) under the InterBase Public License v.1.0 on 25 July, 2000. More information about Firebird is available at http://www.firebirdsql.org/.
Nota: Questo modulo supporta la versione 5 e successive di InterBase e tutte le versioni di Firebird. Il supporto per la versione 5.x di InterBase sarà rimosso dalla versione 5 di PHP.
Questo database usa il carattere di singolo apice (') come carattere di escape, un comportamento simile al database Sybase, aggiungere al proprio file php.ini la seguente direttiva:
Per abilitare l'utilizzo di InterBase, configurare il PHP con --with-interbase[=DIR], dove DIR indica la directory di installazione di InterBase; il defualt è /usr/interbase.
Nota per gli utenti Win32: Per abilitare questo modulo nel mondo Windows, occorre copiare gds32.dll dalla cartella DLL della distribuzione PHP/Win32 alla cartella SYSTEM32 della machhina Windows. (Ad esempio: C:\WINNT\SYSTEM32 o C:\WINDOWS\SYSTEM32). Nel caso in cui il server InterBase sia sulla medesima macchina in cui gira il PHP, queste DLL sono già installate. Quindi non occorre copiare gds32.dll dalla cartella DLL.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Parametri di configurazione di InterBase
Nome | Default | Modificabile |
---|---|---|
ibase.allow_persistent | "On" | PHP_INI_SYSTEM |
ibase.max_persistent | "-1" | PHP_INI_SYSTEM |
ibase.max_links | "-1" | PHP_INI_SYSTEM |
ibase.default_db | NULL | PHP_INI_SYSTEM |
ibase.default_user | NULL | PHP_INI_ALL |
ibase.default_password | NULL | PHP_INI_ALL |
ibase.default_charset | NULL | PHP_INI_ALL |
ibase.timestampformat | "%Y-%m-%d %H:%M:%S" | PHP_INI_ALL |
ibase.dateformat | "%Y-%m-%d" | PHP_INI_ALL |
ibase.timeformat | "%H:%M:%S" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
Stabilisce se permettere o meno le connessioni persistenti a Firebird/InterBase.
Indica il numero massimo di connessioni persistenti a Firebird/InterBase per processo. Le ulteriori connessioni create con ibase_pconnect() saranno non persistenti.
Indica il numero massimo di connessioni a Firebird/InterBase per processo, incluse le connessioni persistenti.
Il database di default a cui connettersi quando viene chiamata la funzione ibase_[p]connect() senza specifica del nome del database. Se questo valore è impostato ed è abilitata la modalità sicura SQL, non saranno permesse connessioni ad altri database.
Il nome utente da utilizzarsi per la connessione al database se non viene specificato.
La password da utilizzare per connettersi al database se non viene specificata in fase di connessione.
Il set di caratteri da utilizzare per la connessione al database se non ne viene specificato uno al momento della connessione.
Questo parametro è utilizzato per utilizzato per impostare il formato di data ed ora utilizzato per la restituzione di date ed ore dai set di risultati o per l'impostazione degli argomenti di data ed ora.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Le seguenti costanti possono essere passate alle funzioni ibase_trans() per indicare il comportamento delle transazioni.
Tabella 2. Flag per le transazioni Firebird/InterBase
Costante | Descrizione |
---|---|
IBASE_DEFAULT | Sono utilizzate le impostazioni di default per la transazione. Quale default è determinato dalla libreria client, che, nella maggior parte dei casi, lo definisce come IBASE_WRITE|IBASE_CONCURRENCY|IBASE_WAIT. |
IBASE_READ | Inizia una transazione di sola lettura. |
IBASE_WRITE | Inizia una transazione di lettura/scrittura. |
IBASE_CONSISTENCY | Inizia una transazione con il livello di isolamento impostato a 'consistency', il quale indica che una transazione non leggere da tabelle che stanno per essere modificate da altre transazioni concorrenti. |
IBASE_CONCURRENCY | Inizia una transazione con il livello di isolamento impostato a 'concurrency' (o 'snapshot'), il quale indica che la transazione può accedere a tutte le tabelle, ma non può rilevare modifiche eseguite da altre transazioni dopo la partenza della transazione. |
IBASE_COMMITTED | Inizia una transazione con il livello di isolamento impostato a 'read committed'. Questo flag dovrebbe essere abbinato con IBASE_REC_VERSION oppure con IBASE_REC_NO_VERSION. Questo livello di isolamento permette l'accesso alle modifiche quando queste vengono eseguite dopo l'inizio della transazione. Se si indica IBASE_REC_NO_VERSION, si può accedere solo all'ultima versione della riga. Se si indica IBASE_REC_VERSION, una riga può essere letta anche se vi è una modifica pendente da parte di una transazione concorrente. |
IBASE_WAIT | Indica che la transazione deve attendere e riprovare in caso di conflitto. |
IBASE_NOWAIT | Indica che la transazione deve fallire immadiatamente in caso di conflitto di accesso. |
La seguenti costanti possono essere utilizzate con ibase_fetch_row(), ibase_fetch_assoc() o ibase_fetch_object() per indicare il comportamento nello scarico dei dati.
Tabella 3. Flag di scarico dati in Firebird/InterBase
Costante | Descrizione |
---|---|
IBASE_FETCH_BLOBS | Disponibile anche come IBASE_TEXT per compatibilità verso il passato. Forza lo scarico in linea dei contenuti BLOB, anzichè essere scaricati come indentificatori BLOB. |
IBASE_FETCH_ARRAYS | Forza lo scarico in linea delle matrici. Altrimenti le matrici sarebbero restituite come variabili. La matrici possono essere utilizzate come argomenti solo per le operazioni di INSERT, poichè, al momento, non vi sono funzioni che trattano le matrici. |
IBASE_UNIXTIME | Indica di restituire i dacmpi data e ora non come stringa, ma come UNIX timestamp (il numero dei secondi da una certa data, che è il 1-Gen-1970 0:00 UTC). Possono esserci problemi se utilizzato con date anteriori al 1970 su certi sistemi. |
Le seguenti costanti sono utilizzate per passare richieste ed opzioni alle (ibase_server_info(), ibase_db_info (), ibase_backup(), ibase_restore () e ibase_maintain_db()). Fare riferimento ai manuali di Firebird/InterBase per avere il significato di queste funzioni.
Options to ibase_backup()()
Options to ibase_restore()
Options to ibase_maintain_db()
Options to ibase_db_info()
Opzioni per ibase_server_info()
PHP 4 uses server, dba_user_name and dba_user_password instead of service_handle parameter.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
See also ibase_modify_user() and ibase_delete_user().
This function returns the number of rows that were affected by the previous query (INSERT, UPDATE or DELETE) that was executed from within the transaction context specified by link_identifier. If link_identifier is a connection resource, its default transaction is used.
See also ibase_query() and ibase_execute().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ibase_blob_add() aggiunge dati ad un blob creato con ibase_blob_create().
Vedere anche ibase_blob_cancel(), ibase_blob_close(), ibase_blob_create() e ibase_blob_import().
Questa funzione cancella un BLOB creato da ibase_create_blob() se questo non è già stato chiuso da ibase_blob_close(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche ibase_blob_close(), ibase_blob_create() e ibase_blob_import().
Questa funzione chiude un BLOB aperto in lettura da ibase_open_blob() o aperto in scrittura da ibase_create_blob(). Se il BLOB è stato letto, questa funzione restituisce TRUE se riesce, se il BLOB è stato scritto, questa funzion restituisce la stringa contenente il BLOB id assegnato dal database. Se si verificano errori, questa funzione restituisce FALSE.
Vedere anche ibase_blob_cancel() e ibase_blob_open().
ibase_blob_create() crea un nuovo blob da riempire di dati. La funzione restituisce un puntatore al BLOB da utilizzare successivamente con ibase_blob_add() oppure FALSE se si verifica un errore.
Vedere anche ibase_blob_add(), ibase_blob_cancel(), ibase_blob_close() e ibase_blob_import().
Questa funzione apre un BLOB in lettura ed invia il suo contenuto direttamente allo standard output (prevalentemente il browser). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche ibase_blob_open(), ibase_blob_close() e ibase_blob_get().
Questa funzine restituisce almeno len bytes da un BLOB che è stato aperto in lettura con ibase_blob_open(). Restituisce FALSE se si verifica un errore.
<?php $sql = "SELECT blob_value FROM table"; $result = ibase_query($sql); $data = ibase_fetch_object($result); $blob_data = ibase_blob_info($data->BLOB_VALUE); $blob_hndl = ibase_blob_open($data->BLOB_VALUE); echo ibase_blob_get($blob_hndl, $blob_data[0]); ?> |
Nota: Non è possibile leggere da un BLOB che è stato aperto in scrittura da ibase_blob_create().
Vedere anche ibase_blob_open(), ibase_blob_close() e ibase_blob_echo().
(PHP 3 >= 3.0.7, PHP 4, PHP 5)
ibase_blob_import -- Create un blob, copy il file al suo interno e lo chiudeQuesta funzione crea un BLOB e vi inserisce un file intero, lo chiude e restituisce l'id assegnato al BLOB. file_handle è un puntatore di file restituito da fopen(). La funzione restituisce FALSE se si verifica un errore.
Vedere anche ibase_blob_add(), ibase_blob_cancel(), ibase_blob_close() e ibase_blob_create().
(PHP 3 >= 3.0.7, PHP 4, PHP 5)
ibase_blob_info -- Restituisce la lunghezza del blob e altre informazioni utliliLa funzione restituisce un array contenente informazioni su un BLOB. Le informazioni restituite consistono nella lunghezza del BLOB, il numero di segmenti contenuti, la dimensione del segmento più grande, e se si tratta di un BLOB segmentato o a flusso.
ibase_blob_open() apre un BLOB esistente in lettura. Restituisce un puntatore al BLOB da usarsi successivamente con ibase_blob_get() oppure FALSE se si verifica un errore.
Vedere anche ibase_blob_close(), ibase_blob_echo() e ibase_blob_get().
Chiude il collegamento ad un database InterBase che è stato associato con un id di connessione restituito da ibase_connect(). Se l'id di connessione viene omesso, viene considerato l'ultimo collegamento che è stato aperto. La transazione predefinita sul collegamento viene "committed", le altre transazioni vengono "rolled back".
Vedere anche ibase_connect() e ibase_pconnect().
If called without an argument, this function commits the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be committed. If the argument is a transaction identifier, the corresponding transaction will be committed. The transaction context will be retained, so statements executed from within this transaction will not be invalidated. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Se chiamata senza parametri, la funzione esegue il commit della transazione di default, sul link di default. Se l'argomento identifica una transazione, verrà aseguito il commit della transazione di default su quella connessione. Se l'argomento identifica una transazione verrà eseguito il commit della transazione. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Stabilisce una connessione con un server InterBase. Il parametro database deve essere un percorso valido di un file di database sul server dove risiede. Se il server non fosse locale, bisogna aggiungere prima del percorso o 'hostname:' (TCP/IP), o '//hostname/' (NetBEUI) o 'hostname@' (IPX/SPX), in base al protocollo di connessione utilizzato. username e password possono venire specificati anche con le direttive di configurazione del PHP ibase.default_user e ibase.default_password. charset è il set di caratteri predefinito per un database. buffers è il numero di buffer di database da allocare per la cache dal lato server. Se è 0 o viene omesso, il server usa il suo valore predefinito. dialect seleziona il dialetto SQL predefinito per ogni operazione eseguita all'interno di una connessione, e il suo valore predefinito è il più alto supportato dalle librerie del client.
Nel caso di una seconda chiamata fatta con ibase_connect() con gli stessi parametri, non verrà creato alcun nuovo collegamento, bensì, l'identificatore del collegamento già aperto verrà restituito. Il collegamento al server verrà chiuso appena termina l'esecuzione dello script, a meno che non venga chiuso prima esplicitamente chiamando ibase_close().
Esempio 1. Esempio di ibase_connect()
|
Nota: Il parametro opzionale buffers è stato aggiunto in PHP 4.0.0.
Nota: dialect è stato aggiunto in PHP 4.0.0. E' funzionante solo con InterBase 6 e versioni successive.
Nota: role è stato aggiunto in PHP 4.0.0. E' funzionante solo con InterBase 5 e versioni successive.
Nota: Se si verificano degli errori tipo "arithmetic exception", "numeric overflow", oppure "string truncation. Cannot transliterate character between character sets" (questo capita quando si tenta di usare dei caratteri accentati) questa funzione o dopo la funzione ibase_query(), occorre impostare il set di caratteri (ad esempio ISO8859_1 oppure il set di caratteri corrente).
Vedere anche: ibase_pconnect() e ibase_close().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ibase_delete_user -- Delete a user from a security database (only for IB6 or later)PHP 4 uses server, dba_user_name and dba_user_password instead of service_handle parameter.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
See also ibase_add_user() and ibase_modify_user().
This functions drops a database that was opened by either ibase_connect() or ibase_pconnect(). The database is closed and deleted from the server. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also ibase_connect() and ibase_pconnect().
Returns the error code that resulted from the most recent InterBase function call. Returns FALSE if no error occurred.
See also ibase_errmsg().
Restituisce una stringa contenente un messaggio di errore dalla più recente funzione InterBse eseguita. La funzione restituisce FALSE se non vi sono errori.
Vedere anche ibase_errcode().
Esegue una query preparata da ibase_prepare(). Se la query genera un errore, la funzione restituisce FALSE. Se invece ha successo ed si ha un set di risultati (tipo un query SELECT), la funzione ne restituisce l'identificativo. Se la query ha successo e non vi sono risultati, restituisce TRUE
Ciò è molto più efficace che usare ibase_query() se state ripetendo uno stesso tipo di query molte volte cambiando solo alcuni parametri.
Esempio 1. Esempio di uso di ibase_execute()
|
Nota: In PHP 5.0.0 e successivi, questa funzione restituisce il numero di righe toccate dalla query (se >0 ed è applicabile al tipo di query). Una query che ha successo, ma che non modifica nessuna righa (ad esempio un UPDATE su record che non esistono) restituirà TRUE
Vedere anche ibase_query().
ibase_fetch_assoc() returns an associative array that corresponds to the fetched row. Subsequent calls will return the next row in the result set, or FALSE if there are no more rows.
ibase_fetch_assoc() fetches one row of data from the result. If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using ibase_fetch_row() or use alias names in your query.
fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.
See also ibase_fetch_row() and ibase_fetch_object().
Elabora una riga come un pseudo-oggetto da un result_id ottenuto o da ibase_query() o da ibase_execute().
<?php $dbh = ibase_connect($host, $username, $password); $stmt = 'SELECT * FROM tblname'; $sth = ibase_query($dbh, $stmt); while ($row = ibase_fetch_object($sth)) { echo $row->email . "\n"; } ibase_close($dbh); ?> |
Chiamate successive a ibase_fetch_object() restituiscono la successiva riga dai risultati della query o FALSE se non vi sono ulteriori righe.
Il parametro fetch_flag è una combinazione delle costanti IBASE_TEXT e IBASE_UNIXTIME con l'operatore OR. Passando IBASE_TEXT si forza questa funzione a resituire il contenuto del BLOB anzichè l'identificatore del BLOB. Passando IBASE_UNIXTIME si forza la funzione a restituire i valori di data/ora com Unix timestamp anzichè come stringa formattata.
Vedere anche ibase_fetch_row() e ibase_fetch_assoc().
Restituisce un array che corrisponde alla riga ottenuta o FALSE se non ci sono righe rimanenti.
ibase_fetch_row() prende una riga di dati dai risultati associati allo specificato result_identifier. La riga viene restituita come un array. Ogni colonna risultante viene immagazzinata in un offset dell'array, l'offset inizia da 0.
Chiamate successive a ibase_fetch_row() restituiscono la successiva riga dai risultati della query o FALSE se non vi sono ulteriori righe.
Restituisce un array con informazioni relative a un campo dopo che una query select è stata eseguita. L'array ha la forma name, alias, relation, length e type.
$rs=ibase_query("SELECT * FROM tablename"); $coln = ibase_num_fields($rs); for ($i=0; $i < $coln; $i++) { $col_info = ibase_field_info($rs, $i); echo "name: ".$col_info['name']."\n"; echo "alias: ".$col_info['alias']."\n"; echo "relation: ".$col_info['relation']."\n"; echo "length: ".$col_info['length']."\n"; echo "type: ".$col_info['type']."\n"; } |
This function causes the registered event handler specified by event to be cancelled. The callback function will no longer be called for the events it was registered to handle. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also ibase_set_event_handler().
Libera un result set che è stato creato da ibase_query().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Returns new generator value as integer, or as string if the value is too big.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ibase_modify_user -- Modify a user to a security database (only for IB6 or later)PHP 4 uses server, dba_user_name and dba_user_password instead of service_handle parameter.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
See also ibase_add_user() and ibase_delete_user().
This function assigns a name to a result set. This name can be used later in UPDATE|DELETE ... WHERE CURRENT OF name statements. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
<?php $result = ibase_query("SELECT field1,field2 FROM table FOR UPDATE"); ibase_name_result($result, "my_cursor"); $updateqry = ibase_prepare("UPDATE table SET field2 = ? WHERE CURRENT OF my_cursor"); for ($i = 0; ibase_fetch_row($result); ++$i) { ibase_execute($updateqry, $i); } ?> |
See also ibase_prepare() and ibase_execute().
Restituisce un integer contenente il numero di campi in un result set.
<?php $dbh = ibase_connect ($host, $username, $password); $stmt = 'SELECT * FROM tblname'; $sth = ibase_query ($dbh, $stmt); if (ibase_num_fields($sth) > 0) { while ($row = ibase_fetch_object ($sth)) { print $row->email . "\n"; } } else { die ("Nessun result è stato trovato per la tua query"); } ibase_close ($dbh); ?> |
Vedere anche: ibase_field_info().
This function returns the number of parameters in the prepared query specified by query. This is the number of binding arguments that must be present when calling ibase_execute().
See also ibase_prepare() and ibase_param_info().
Returns an array with information about a parameter after a query has been prepared. The array is in the form of name, alias, relation, length, type.
See also ibase_field_info() and ibase_num_params().
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
ibase_pconnect -- Crea una connessione persistente ad un database Interbaseibase_pconnect() agisce in modo molto simile a ibase_connect() con due differenze principali. Innanzitutto, durante la connessione, la funzione cercherà prima di trovare un collegamento (persistente) che è già stato aperto con gli stessi parametri. Se viene trovato, il suo identificatore verrà restituito al posto di aprire una nuova connessione. In secondo luogo, la connessione al server InterBase non verrà chiusa al termine dell'esecuzione dello script. Invece, il collegamento resterà aperto per un uso futuro (ibase_close() non chiuderà i collegamenti stabiliti da ibase_pconnect()). Questo tipo di collegamento è perciò chiamato 'persistente'.
Nota: buffers è stato aggiunto in PHP4-RC2.
Nota: dialect è stato aggiunto in PHP4-RC2. Funziona soltanto con InterBase 6 e superiori.
Nota: role è stato aggiunto in PHP4-RC2. Funziona soltanto con InterBase 5 e superiori.
Vedere anche ibase_connect() per il significato dei parametri passati a questa funzione. Sono esattamente gli stessi.
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
ibase_prepare -- Prepara una query per un successivo binding dei segnaposto dei parametri ed esecuzionePrepara una query per un successivo binding dei segnaposto dei parametri ed esecuzione (tramite ibase_execute()).
Esegue una query su di un database InterBase. Se la query non ha successo, restituisce FALSE. Se ha successo e vi sono riga di risultato (come si ha ad esempio con le query SELECT), restituisce un identificatore di risorsa. Se la query ha avuto successo, ma non ci sono risultati, restituisce TRUE. Restutuisce FALSE se la query fallisce.
Vedere anche ibase_errmsg(), ibase_fetch_row(), ibase_fetch_object() e ibase_free_result().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
If called without an argument, this function rolls back the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be rolled back. If the argument is a transaction identifier, the corresponding transaction will be rolled back. The transaction context will be retained, so statements executed from within this transaction will not be invalidated. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Rolls back transaction trans_number which was created with ibase_trans().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
This function registers a PHP user function as event handler for the specified events. The callback is called with the event name and the link resource as arguments whenever one of the specified events is posted by the database. The callback must return FALSE if the event handler should be canceled. Any other return value is ignored. This function accepts up to 15 event arguments.
<?php function event_handler($event_name, $link) { if ($event_name=="NEW ORDER") { // process new order ibase_query($link, "UPDATE orders SET status='handled'"); } else if ($event_name=="DB_SHUTDOWN") { // free event handler return false; } } ibase_set_event_handler($link, "event_handler", "NEW_ORDER", "DB_SHUTDOWN"); ?> |
The return value is an event resource. This resource can be used to free the event handler using ibase_free_event_handler().
See also ibase_free_event_handler() and ibase_wait_event().
(PHP 3 >= 3.0.6, PHP 4)
ibase_timefmt -- Imposta il formato delle colonne timestamp, date e time restituite dalle queryImposta il formato delle colonne di tipo timestamp, date o time restituite dalle query. Internamente, le colonne vengono formattate dalla funzione C strftime(), quindi fate riferimento alla sua documentazione riguardo al formato della stringa. columntype è una delle costanti IBASE_TIMESTAMP, IBASE_DATE e IBASE_TIME. Se omessa, è predefinita a IBASE_TIMESTAMP per motivi di compatibilità con il passato.
<?php // Le colonne di tipo TIME di InterBase vengono restituite nella // forma '05 hours 37 minutes'. ibase_timefmt("%H hours %M minutes", IBASE_TIME); ?> |
Potete impostare anche valori predefiniti per questi formati con la direttiva di configurazione ibase.timestampformat, ibase.dateformat e ibase.timeformat.
Nota: columntype è stata aggiunta in PHP 4.0. Ha significato solo con InterBase versione 6 e successive.
Nota: Un'incompatibilità con il passato si è avuta nel PHP 4.0 quando la direttiva di configurazione del PHP ibase.timeformat è stata rinominata in ibase.timestampformat e la direttiva ibase.dateformat e ibase.timeformat sono state aggiunte, così che i loro nomi fossero più simili alle loro funzionalità.
This function suspends execution of the script until one of the specified events is posted by the database. The name of the event that was posted is returned. This function accepts up to 15 event arguments.
See also ibase_set_event_handler() and ibase_free_event_handler().
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
(no version information, might be only in CVS)
PDO_FIREBIRD DSN -- Connecting to Firebird and Interbase databasesThe PDO_FIREBIRD Data Source Name (DSN) is composed of the following elements:
The DSN prefix is firebird:.
The hostname on which the database server resides.
The port number for the server on which the database is running.
The name of the database.
The name of the user that will connect to the database.
The password for the user.
FriBiDi è un'implementazione free del Unicode Bidirectional Algorithm.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/fribidi.
Per abilitare il supporto FriBiDi in PHP occorre compilare il PHP con l'opzione --with-fribidi[=DIR], dove DIR indica la directory di installazione di FriBiDi.
Gli utenti di Windows, per potere utilizzare queste funzioni, devono abilitare php_fribidi.dll dal php.ini. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Queste funzioni permettono di accedere ai servers del database FrontBase. Maggiori informazioni su FrontBase: http://www.frontbase.com/.
Documentazione su FrontBase : http://www.frontbase.com/cgi-bin/WebObjects/FrontBase.woa/wa/productsPage?currentPage=Documentation.
Il supporto Frontbase è stato aggiunto dal PHP 4.0.6.
Per potere utilizzare queste funzioni occorre installare o il server FrontBase o, al limite, le librerie fbsql client. Si può ottenere FrontBase da http://www.frontbase.com/.
Affinché queste funzioni siano disponibili è necessario compilare php con il supporto fbsql usando l' opzione --with-fbsql[=DIR].Se si usa questa opzione senza specificare il percorso a fbsql, php cercherà le librerie client di fbsql nella cartella di default specificata nell'istallazione di FrontBase, a seconda del sistema operativo. Se si installa FrontBase in una cartella non standard è necessario specificare sempre il percorso a fbsql: --with-fbsql=/path/to/fbsql. In questo modo si forzerà php ad usare le librerie client installate da FrontBase, evitando ogni conflitto.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Opzioni di configurazione per FrontBase
Nome | Default | Modificabile |
---|---|---|
fbsql.allow_persistent | "1" | PHP_INI_SYSTEM |
fbsql.generate_warnings | "0" | PHP_INI_SYSTEM |
fbsql.autocommit | "1" | PHP_INI_SYSTEM |
fbsql.max_persistent | "-1" | PHP_INI_SYSTEM |
fbsql.max_links | "128" | PHP_INI_SYSTEM |
fbsql.max_connections | "128" | PHP_INI_SYSTEM |
fbsql.max_results | "128" | PHP_INI_SYSTEM |
fbsql.batchSize | "1000" | PHP_INI_SYSTEM |
fbsql.default_host | NULL | PHP_INI_SYSTEM |
fbsql.default_user | "_SYSTEM" | PHP_INI_SYSTEM |
fbsql.default_password | "" | PHP_INI_SYSTEM |
fbsql.default_database | "" | PHP_INI_SYSTEM |
fbsql.default_database_password | "" | PHP_INI_SYSTEM |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
(PHP 4 >= 4.0.6, PHP 5)
fbsql_affected_rows -- Restituisce il numero di righe (tuple) interessate nella precedente operazione di FrontBasefbsql_affected_rows() restituisce il numero di righe interessate dall'ultima query INSERT, UPDATE or DELETE associata al parametro link_identifier. Se tale parametro non è stato specificato, sarà usata l'ultima connessione aperta da fbsql_connect().
Nota: Se si stanno usando le transazioni, è necessario chiamare la funzione fbsql_affected_rows() dopo una query INSERT, UPDATE, or DELETE, non dopo la chiusura della transazione (commit).
Se l'ultima query è un istruzione DELETE senza clausola WHERE, tutte le righe verranno cancellate dalla tabella e la funzione restituirà il valore 0 (zero).
Nota: Se si utilizza l'istruzione UPDATE, FrontBase non aggiornerà le colonne in cui il valore nuovo è uguale a quello vecchio. Quindi esiste la possibilità che fbsql_affected_rows() sia diverso dal numero di righe realmente interessate dalla query.
Se l'ultima query fallisce la funzione restituisce -1.
Vedere anche: fbsql_num_rows().
fbsql_autocommit() restituisce lo stato corrente di autocommit. Se è stato specificato il parametro opzionale OnOff, lo stato di autocommit verrà cambiato. Impostando il parametro OnOff su TRUE ogni istruzione verrà eseguita automaticamente, in caso di assenza di errori. Impostandolo su FALSE l'utente dovrà eseguire la transazione richiamando le funzioni fbsql_commit() o fbsql_rollback().
Vedere anche: fbsql_commit() e fbsql_rollback()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
fbsql_change_user -- Cambia l'identità dell'utente connesso con una connessione attivafbsql_change_user() Cambia l'identità dell'utente connesso con una connessione attiva, o con la connessione specificata dal parametro opzionale link_identifier. Se è stato specificato un database, dopo che l'identità dell'utente sarà stata cambiata, questo diventerà il database attivo . Se l'autorizzazione del nuovo utente fallisce, rimarrà attiva l'identità dell'utente corrente.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce: TRUE in caso di successo, FALSE in caso di fallimento.
fbsql_close() chiude la connessione al server FrontBase associata ad uno specificato link identifier. Se il link_identifier non fosse specificato, verrebbe chiusa l'ultima connessione aperta.
Non è sempre necessario usare fbsql_close() nel caso di connessioni non permanenti, esse verranno chiuse automaticamente alla fine dell'esecuzione dello script.
Vedere anche: fbsql_connect() e fbsql_pconnect().
restituisce: TRUE in caso di successo, FALSE in caso di fallimento.
fbsql_commit() esegue la transazione corrente scrivendo tutti gli aggiornamenti pendenti, cancella il disco e sblocca tutte le righe della tabella bloccata dalla transazione. Questo comando è necessario solo nel caso in cui autocommit fosse impostato su false.
Vedere anche: fbsql_autocommit() e fbsql_rollback()
Restituisce un valore di link_identifier positivo in caso di successo, o un messaggio di errore in caso di fallimento.
fbsql_connect() Apre una connessione al Server FrontBase.Se i parametri opzionali non sono specificati verranno usati i valori seguenti come default: hostname = 'NULL', username = '_SYSTEM' e password = empty password.
Se si richiamasse, una seconda volta, la funzione fbsql_connect() con gli stessi argomenti, non si creerebbe una nuova connessione,ma verrebbe restituito il valore di link_identifier della connessione già aperta.
La connessione al server si chiuderà alla fine dello script, a meno che non venga chiusa in anticipo richiamando esplicitamente la funzione fbsql_close().
Vedere anche fbsql_pconnect() e fbsql_close().
Restituisce un handle al blob appena creato.
La funzione fbsql_create_blob() crea un campo blob a partire da blob_data. L'handle restituito può essere utilizzato con i comandi di inserimento e di aggiornamento dei blob nel database.
Esempio 1. Esempio di uso di fbsql_create_blob()
|
Vedere anche: fbsql_create_clob(), fbsql_read_blob(), fbsql_read_clob() e fbsql_set_lob_mode().
Restituisce un handle al CLOB appena creato.
La funzione fbsql_create_clob() crea un campo clob a partire da clob_data. L'handle restituito può essere utilizzato con i comandi di inserimento e di aggiornamento dei clob nel database.
Esempio 1. Esempio di uso di fbsql_create_clob()
|
Vedere anche: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob() e fbsql_set_lob_mode().
fbsql_create_db() crea un nuovo database FrontBase sul server, identificato dal parametro link_identifier.
Vedere anche fbsql_drop_db().
Restituisce: TRUE in caso di successo, FALSE in caso di fallimento.
fbsql_data_seek() sposta il puntatore interno al risultato FrontBase associato con uno specificato indice in modo che punti ad un numero di riga specificata . La chiamata successiva alla funzionefbsql_fetch_row() restituirà la riga richiesta.
row_number comincia a contare da 0.
Esempio 1. fbsql_data_seek()
|
(PHP 4 >= 4.0.6, PHP 5)
fbsql_database_password -- Imposta o ricerca la password di un database FrontBase.Restituisce: La password del database identificato dal parametro link_identifier.
fbsql_database_password() imposta e ricerca la password del database corrente. Se il secondo parametro, opzionale (database_password), è stato specificato la funzione imposta, sul server, il valore del parametro come password del database identificato dal parametro link_identifier. Se il link_identifier non è specificato, verrà utilizzata l'ultima connessione aperta. Se nessuna connessione è aperta, la funzione tenterà di aprirne una come se la funzione fbsql_connect() fosse chiamata, e userà quella.
Questa funzione non modifica la password nel database e neppure è in grado ti recuperare la password di un database.
Esempio 1. Esempio di fbsql_create_clob()
|
Vedere anche: fbsql_connect(), fbsql_pconnect() e fbsql_select_db().
(PHP 4 >= 4.0.6, PHP 5)
fbsql_database -- Imposta oppure ottiene il nome del database usato per la connessione
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce: un indice FrontBase positivo come risultato della query, o FALSE in caso di errore.
fbsql_db_query() seleziona un database ed esegue la query su di esso.Se il parametro opzionale link_identifier non è stato specificato, la funzione ne cercherà una già aperta nel FrontBase server, in caso non ne trovasse alcuna aprirà una nuova connessione come se la funzione fbsql_connect() fosse chiamta senza argomenti.
Vedere anche: fbsql_connect().
Restituisce: un valore intero con lo stato corrente.
fbsql_db_status() richiede lo stato corrente del database specificato da database_name. Se il link_identifier viene omesso verrà usato quello in uso.
Il valore restituito potrà essere uno delle seguenti costanti:
FALSE - L'exec handler del host era invalido. Questo errore si presenta quando la connessione avviene direttamente al database, tramite il link_identifier, usando un numero di porta. FBExec può essere disponibile sul server ma nessuna connessione è stata creata.
FBSQL_UNKNOWN - Lo stato è sconosciuto.
FBSQL_STOPPED - Il database non è attivo. Usare fbsql_start_db() per attivare il database.
FBSQL_STARTING - Il database è in fase di attivazione.
FBSQL_RUNNING - Il database è attivo e può essere usato per eseguire operazioni SQL.
FBSQL_STOPPING - Il database é in fase di disattivazione.
FBSQL_NOEXEC - FBExec non è attivo sul server quindi non è possibile conoscere lo stato del database.
Vedere anche: fbsql_start_db() e fbsql_stop_db().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
fbsql_drop_db() procede con l'eliminazione di un intero database dal server associato all'identificatore di link.
(PHP 4 >= 4.0.6, PHP 5)
fbsql_errno -- Ritorna il valore numerico del messaggio di errore emesso dalla precedente operazione FrontBase.Restituisce il numero di errore dell'ultima funzione fbsql, 0 (zero) se non ci sono stati errori.
Gli errori vengono restituiti dal database fbsql senza visualizzare i warnings. Usare fbsql_errno() per ricevere codice dell'errore. Da notare che questa funzione restituisce solamente il codice di errore proveniente dalla più recente esecuzione di una funzione fbsql (escludendo fbsql_error() e fbsql_errno()),così se si vuole usarla, assicurarsi di controllare il valore prima di richiamare un'altra funzione fbsql.
<?php fbsql_connect("marliesle"); echo fbsql_errno().": ".fbsql_error()."<BR>"; fbsql_select_db("nonexistentdb"); echo fbsql_errno().": ".fbsql_error()."<BR>"; $conn = fbsql_query("SELECT * FROM nonexistenttable;"); echo fbsql_errno().": ".fbsql_error()."<BR>"; ?> |
Vedere anche: fbsql_error() e fbsql_warnings().
(PHP 4 >= 4.0.6, PHP 5)
fbsql_error -- Ritorna il testo del messaggio di errore emesso dalla precedente operazione FrontBase.Restituisce il testo del messaggio di errore dell'ultima funzione fbsql, o '' (una stringa vuota) se non ci sono stati errori.
Gli errori vengono restituiti dal database fbsql senza visualizzare i warnings. Usare fbsql_errno() per ricevere codice dell'errore. Da notare che questa funzione restituisce solamente il codice di errore proveniente dalla più recente esecuzione di una funzione fbsql (escludendo fbsql_error() e fbsql_errno()),così se si vuole usarla, assicurarsi di controllare il valore prima di richiamare un'altra funzione fbsql.
<?php fbsql_connect("marliesle"); echo fbsql_errno().": ".fbsql_error()."<BR>"; fbsql_select_db("nonexistentdb"); echo fbsql_errno().": ".fbsql_error()."<BR>"; $conn = fbsql_query("SELECT * FROM nonexistenttable;"); echo fbsql_errno().": ".fbsql_error()."<BR>"; ?> |
Vedere anche: fbsql_errno() e fbsql_warnings().
(PHP 4 >= 4.0.6, PHP 5)
fbsql_fetch_array -- Restituisce una riga (tupla) di risultato in forma di Array associativo, Array enumerato o entrambiRestituisce un array che corrisponde alla riga di risultato, o FALSE se non ci sono righe successive.
fbsql_fetch_array() è una versione estesa di fbsql_fetch_row(). In aggiunta all'inserimento dei dati negli elementi dell'array con indice numerico, li inserisce anche in indici associativi, usando il nome dei campi come chiavi.
Se due o più colonne di risultato hanno lo stesso nome di campo , l'ultima colonna sovrascriverà la precedente con lo stesso nome. Per accedere alle altre colonne con lo stesso nome si deve usare l'indice numerico oppure fare un alias della colonna.
Una cosa importante da notare è che fbsql_fetch_array() NON è singnificativamente più lenta di fbsql_fetch_row(), mentre fornisce un significativo valore aggiunto.
Il secondo parametro opzionale, result_type in fbsql_fetch_array() è una costante che può assumere i seguenti valori: FBSQL_ASSOC, FBSQL_NUM, and FBSQL_BOTH.
Per ulteriori dettagli vedere anche fbsql_fetch_row() e fbsql_fetch_assoc().
Esempio 1. fbsql_fetch_array()
|
(PHP 4 >= 4.0.6, PHP 5)
fbsql_fetch_assoc -- Restituisce una riga (tupla) di risultato in forma di Array associativo.Restituisce un array associativo corrispondente alla riga di risultato, o FALSE se non ci sono righe successive.
fbsql_fetch_assoc() è equivalente ad una chiamata a fbsql_fetch_array() con FBSQL_ASSOC come parametro opzionale. Restituirà solo un array associativo. fbsql_fetch_array() originariamente lavora in questo modo. Se si vuole un indice numerico come pure quello associativo, usare fbsql_fetch_array().
Se due o più colonne di risultato hanno lo stesso nome di campo , l'ultima colonna sovrascriverà la precedente con lo stesso nome. Per accedere alle altre colonne con lo stesso nome si deve usare fbsql_fetch_array() che ritorna un indice numerico.
Una cosa importante da notare è che fbsql_fetch_assoc() NON è singnificativamente più lenta di fbsql_fetch_row(), mentre fornisce un significativo valore aggiunto.
Per maggiori dettagli, vedi anche fbsql_fetch_row() e fbsql_fetch_array().
(PHP 4 >= 4.0.6, PHP 5)
fbsql_fetch_field -- Ottiene informazioni su una colonna da un set di risultati come oggettoRestituisce un oggetto contenente le informazioni del campo.
La funzione fbsql_fetch_field() può essere utilizzata per ottenere informazioni sui campi da un set di risultati. Se non si specifica l'offset del campo, la funzione resituisce i le informazione sul campo successivo non ancora letto da fbsql_fetch_field().
Le proprietà dell'oggetto sono:
name - nome della colonna
table - nome della tabella da cui deriva la colonna
max_length - lunghezza massima della colonna
not_null - 1 se la colonna non può essere NULL
type - tipo di colonna
Esempio 1. Esempio di uso di fbsql_fetch_field()
|
Vedere anche fbsql_field_seek().
(PHP 4 >= 4.0.6, PHP 5)
fbsql_fetch_lengths -- Ottiene la lunghezza di ciascun output in un set di risultatiLa funzione restituisce un array contenente le lunghezze di ciascun campo nell'ultima riga letta da fbsql_fetch_row(), oppure FALSE se si verifica un errore.
fbsql_fetch_lengths() memorizza le lunghezze di ciascuna colonna dall'ultima riga letta da fbsql_fetch_row(), da fbsql_fetch_array() e da fbsql_fetch_object() in un vettore, partendo dall'offset 0.
Vedere anche fbsql_fetch_row().
La funzione restituisce un oggetto le cui properietà corrispondono lla riga letta, oppure FALSE se non vi sono più righe.
La funzione fbsql_fetch_object() è simile a fbsql_fetch_array(), con una differenza, resituisce un oggetto anzichè un array. Indirettamente ciò significa che si può accedere ai dati solo per nome dei campi e non per il loro offset (i numeri non sono nomi di proprietà validi).
Il parametro opzionale result_type è una costante e può assumere i seguenti valori: FBSQL_ASSOC, FBSQL_NUM, and FBSQL_BOTH.
Come performance la funzione è simile a fbsql_fetch_array(), e quasi veloce come fbsql_fetch_row() (le differenza è insignificante).
Vedere anche: fbsql_fetch_array() e fbsql_fetch_row().
Resituisce: una matrice corrispondente alla riga letta, oppure FALSE se non vi sono più righe.
La funzione fbsql_fetch_row() legge una riga del set di risultati indicato dal parametro result. La riga viene restituita come matrice. Ciascuna colonna è memorizzata in un indice della matrice. La matrice parte da 0.
Chiamate successive a fbsql_fetch_row() restituiscono la successiva riga dal set di risultati, oppure FALSE se non vi sono righe successive.
Vedere anche: fbsql_fetch_array(), fbsql_fetch_object(), fbsql_data_seek(), fbsql_fetch_lengths(), and fbsql_result().
La funzione fbsql_field_flags() restituisce i flag del campo indicato. I flag sono restituiti come parola singola per flag separata da spazi, in questo modo i valori restituiti possono essere suddivisi utilizzando explode().
La funzione fbsql_field_len() restituisce la lunghezza del campo indicato.
La funzione fbsql_field_name() restituisce il nome del campo indicato da field_index. Il parametro result deve essere un valido identificatore di un set di risultati e field_index l'indice del campo.
Nota: field_index parte da 0.
Esempio: l'indice del terzo campo sarà 2, l'indice del quarto sarà 3 e così via.
Esempio 1. Esempio di uso di fbsql_field_name()
L'esempio precedente visualizzerà:
|
(PHP 4 >= 4.0.6, PHP 5)
fbsql_field_seek -- Imposta il puntatore del set di risultati ad un specifico indice di campoSposta ad uno specifico indice di campo. Se la successiva chiamata a fbsql_fetch_field() non specifica alcun indice di campo, sarà restituito il campo il cui indice è impostato da fbsql_field_seek().
Vedere anche: fbsql_fetch_field().
Ottiene il nome della tabella in cui si trova il campo.
La funzione fbsql_field_type() è simile a fbsql_field_name(). Gli argomenti sono simili, ma restituisce il tipo di campo. I tipi restituiti saranno "int", "real", "string", "blob", e altri come specificato nella documentazione di FrontBase.
Esempio 1. Esempio di uso di fbsql_field_type()
|
La funzione fbsql_free_result() libera tutta la memoria associata al un set di risultati indicato da result.
Si dovrebbe richiamare la funzione fbsql_free_result() soltanto se si è preoccupati della quantità di memoria utilizzata per le query che restituiscono grosse quantità di dati. Tutta la memoria occupata dal set di risultati sarà liberata, in automatico, alla fine dell'esecuzione dello script.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.0.6, PHP 5)
fbsql_insert_id -- restituisce l'id generato dalla precedente operazione di INSERTLa funzione fbsql_insert_id() restituisce l'ID generato per una colonna definita come DEFAULT UNIQUE da una precedente query INSERT eseguita sulla connessione link_identifier. Se non si specifica link_identifier si assume l'ultimo link aperto.
fbsql_insert_id()restituisce 0 ise la precedente query non ha generato campo impostati a DEFAULT UNIQUE. Se si desidera salvare il valore per usi futuri, occorre essere sicuri di eseguire fbsql_insert_id() immediatamente dopo la query che genera il valore.
Nota: Il valore restituito dalla funzione fbsql_insert_id() di FrontBase SQL contiene sempre il più recente valore DEFAULT UNIQUE prodotto, e non viene azzerato tra le query.
La funzione fbsql_list_dbs() restituirà il puntatore ad un risultato contenente l'elenco dei databse disponibili dal corrente servizio fbsql. Utilizzare la funzione fbsql_tablename() per muoversi tra i risultati del puntatore
Nota: L'esempio precedente sarebbe semplice con fbsql_fetch_row() o altre funzioni simili.
fbsql_list_fields() recupera informazioni sulla tabella data. I parametri passati sono il nome del database ed il nome della tabella. La funzione resituisce un puntatore alle infomrazioni che può essere utilizzato con fbsql_field_flags(), fbsql_field_len(), fbsql_field_name() e fbsql_field_type().
Il valore restituito è un intero positivo. La funzione restituisce FALSE se si verifica un errore. In caso di errore, nel campo $phperrmsg si avrà un testo con la descrizione dell'errore, e, a meno che la funzione non sia richiamata come @fbsql() questo testo sarà visualizzato.
Esempio 1. Esempio di uso di fbsql_list_fields()
L'esempio precedente visualizzerà:
|
La funzione fbsql_list_tables() prende il nome del database e restituisce e restituisce un puntatore come la funzione fbsql_db_query(). A questo punto occorre utilizzare la funzione fbsql_tablename() per ottenere il nome delle tabelle dal puntatore ottenuto.
Quando si invia più di un comando SQL al server o si esegue una 'stored procedure' che generi più risultati, si spinge il server a generare più set di risultati. Questa funzione verifica la disponibilità di set aggiuntivi dal server. Se esiste un set di risultati aggiuntivo, la funzione libererà la memoria del set corrente e si prepare a scaricare il nuovo. La funzione restituisce TRUE se è disponibile un nuovo set di risultati, oppure FALSE se non ve ne sono.
Esempio 1. Esempio di uso di fbsql_next_result()
|
(PHP 4 >= 4.0.6, PHP 5)
fbsql_num_fields -- Ottiene il numero dei campi presenti in un set di risultatifbsql_num_fields() restituisce il numero dei campi in un set di risultati.
Vedere anche: fbsql_db_query(), fbsql_query(), fbsql_fetch_field() e fbsql_num_rows().
(PHP 4 >= 4.0.6, PHP 5)
fbsql_num_rows -- Restituisce il numero di righe presenti in un set di risultatifbsql_num_rows() restituisce il numero di righe presenti in un set di risultati. Questo comando vale solo per le SELECT. Per sapere il numero di righe coinvolte da un INSERT, UPDATE o DELETE, utilizzare fbsql_affected_rows().
Vedere anche: fbsql_affected_rows(), fbsql_connect(), fbsql_select_db() e fbsql_query().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce: un identificatore della connessione come numero positivo se la connessione riesce, oppure FALSE se la connessione non riesce.
La funzione fbsql_pconnect() stabilisce una connessione con un server FrontBase. I seguenti valori saranno usati come defualt per i parametri omessi: host = 'localhost', username = "_SYSTEM" e password = password vuota.
Per impostare il numero di porta del server FrontBase utilzzare fbsql_select_db().
fbsql_pconnect() agisce in modo simile a fbsql_connect() con due differenze.
Primo, durante la connessione la funzione prima tenta di trovare una connessione (persistente) per il medesimo server già aperta, con il medesimo utente e la medesima password. Se si trova una connessione verrà restituito l'identificatore di questa piuttosto che aprire una nuova connessione.
Secondo, la connessione al server SQL non verrà chiusa al termine dello script. Resterà, invece. aperta per usi futuri.
Questo tipo di connessione è, quindi, chiamata 'persistente'.
La funzione fbsql_query() invia una query al database al database attivo sul collegamento identificato da link_identifier. Se non si specifica link_identifier, si utilizzerà l'ultimo collegamento aperto. Se non vi sono collegamenti attivi la funzione tenta di stabilirne uno come se si chiamasse fbsql_connect() senza parametri.
Nota: Il testo della query deve terminare sempre con punto e virgola.
La funzione fbsql_query() restituisce TRUE (non-zero) oppure FALSE per indicare se la query ha avuto successo o meno. Un valore di ritorno pari a TRUE indica che la query è valida e può essere eseguita dal server. Il valore di ritorno non indica nulla su quante sono le righe coinvolte. Pertanto è possibile che una query abbia successo, ma non coinvolga alcuna riga.
La seguente query è errata, pertanto fbsql_query() fallirà e restituirà FALSE:
La seguente query è semanticamente errata se my_col non è una colonna della tabella my_tbl, pertanto fbsql_query() fallirà e restituirà FALSE:
Inoltre fbsql_query() fallirà e restituirà FALSE se non si hanno i permessi per accedere alle tabelle referenziate dalla query.
Quando la query ha successo, si può utilizzare fbsql_num_rows() per sapere quante righe saranno restituite da un'istruzione SELECT, oppure si può utilizzare fbsql_affected_rows() per sapere quante righe sono state toccate da un DELETE, INSERT, REPLACE o UPDATE.
Per i comandi SELECT, la funzione fbsql_query() restituisce l'identificatore ad un nuovo set dirsultati, che può essere passato a fbsql_result(). Quando si è completato il lavoro con un set di risultati, si può liberare le risorse occupate da questo chiamando fbsql_free_result(). Si ricorda, comunque, che la memoria verrà liberata automaticamente al termine dell'esecuzione dello script.
Vedere anche: fbsql_affected_rows(), fbsql_db_query(), fbsql_free_result(), fbsql_result(), fbsql_select_db() e fbsql_connect().
Restituisce: una stringa contenente il BLOB indicato da blob_handle.
La funzione fbsql_read_blob() legge un campo BLOB dal database. Se una istruzione select contiene colonne BLOB e/o CLOB FrontBase restituisce direttamente i dati quando è richiesta la riga. Questo è il comportamento di default, esso può essere variato tramite fbsql_set_lob_mode() in modo che le funzioni di lettura dei dati restituiscano un puntatore ai dati BLOB e CLOB. Se si ottiene il puntatore occorre eseguire fbsql_read_blob() per ottenere i dati BLOB dal database.
Esempio 1. Esempio di uso di fbsql_read_blob()
|
Vedere anche: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob() e fbsql_set_lob_mode().
Restituisce: una stringa contenente il CLOB indicato da clob_handle.
La funzione fbsql_read_clob() legge un campo CLOB dal database. Se una istruzione select contiene colonne BLOB e/o CLOB FrontBase restituisce direttamente i dati quando è richiesta la riga. Questo è il comportamento di default, esso può essere variato tramite fbsql_set_lob_mode() in modo che le funzioni di lettura dei dati restituiscano un puntatore ai dati BLOB e CLOB. Se si ottiene il puntatore occorre eseguire fbsql_read_clob() per ottenere i dati CLOB dal database.
Esempio 1. Esempio di uso di fbsql_read_clob()
|
Vedere anche: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob() e fbsql_set_lob_mode().
La funzione fbsql_result() restituisce il contenuto di una cella da un set di risultati di una query a FrontBase. L'argomento field può essere l'offset del campo, o il nome del campo, oppure nome della tabella del campo punto nome del campo (nometabella.nomecampo). Se il nome della colonna ha un alias ('select foo as bar from...'), usare l'alias al posto del nome della colonna.
Quando si lavora con grandi set di risultati, si può considerare l'utilizzo delle funzioni che restituiscono l'intera riga (elencate di seguito). Poichè queste restituiscono il contenuto di più celle con una singola chiamata, esse sono MOLTO più veloci che fbsql_result(). Occorre far notare, inoltre, che specificando l'offset numerico del campo si ottiene un'esecuzione più veloce rispetto alla specifica del nome del campo o di nometabella.nomecampo.
Le chiamate a fbsql_result() non dovrebbero essere mischiate con con chiamate ad altre funzioni che agiscano sul set di risultati.
Alternative più performanti raccomandate: fbsql_fetch_row(), fbsql_fetch_array() e fbsql_fetch_object().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione fbsql_rollback() termina la transazione corrente eseguendo il rollback di tutte le istruzioni dall'ultimo commit. Questo comando è necessario solo se autocommit è impostato a false.
Vedere anche: fbsql_autocommit() e fbsql_commit()
La funzione fbsql_select_db() attiva il database corrente sul server associato alla connessione specificata da link_identifier Se non si passa link_identifier, si considera l'ultima connessione aperta. Se non vi sono connessioni aperte, la funzione tenta di stabilirne una come se fosse eseguita la funzione fbsql_connect().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il client contatta FBExec per ottenere il numero diporta per stabilire la connessione al database. Se database_name è un numero il sistema userà quel numero come porta e non chiederà un numero di porta a FBExec. Il server FrontBase può essere avviato come FRontBase -FBExec=No -port=<port number> <database name>.
Ogni chiamata successiva a fbsql_query() sarà eseguita sul database attivo.
Se il database è protetto con una password, l'utente deve eseguire fbsql_database_password() prima di selezionare il database.
Vedere anche: fbsql_connect(), fbsql_pconnect(), fbsql_database_password() e fbsql_query().
(PHP 4 >= 4.2.0, PHP 5)
fbsql_set_lob_mode -- Imposta la modalità LOB in un set di risultati FrontBaseRestituisce: TRUE se ha successo, FALSE se si verifica un errore.
La funzione fbsql_set_lob_mode() la modalità per il recupero dei dati LOB dal database. Quando i dati BLOB e CLOB sono memorizzati in FrontBase questi possono essere memorizzati direttamente o indirettamente. I dati LOB archiviati direttamente sono sempre recuperati a prescindere dell'impostazione della modalità LOB. Se i dati LOB sono meno di 512 byte saranno sempre archiviati direttamente.
FBSQL_LOB_DIRECT - I dati LOB sono recuperati direttamente. Quando i dati sono ottenuti dal database con fbsql_fetch_row(), o altre funzioni per il recupero dei dati, tutte le colonne BLOB saranno restituite come colonne ordinarie. Questo è il valore di default in un nuovo set di risultati.
FBSQL_LOB_HANDLE - I dati LOB sono recuperati come puntatori ai dati. Quando si recupera le informazioni da un database con fbsql_fetch_row (), o altre funzioni per il recupero dei dati, i dati LOB saranno restituiti come handle ai dati, se questi sono stati memorizzati indirettamente o saranno restituiti direttamente i dati se questi sono memorizzati in modo diretto. Se la funzione restituisce un handle, questo sarà una stringa di 27 byte con il formato tipo "@'000000000000000000000000'".
Vedere anche: fbsql_create_blob(), fbsql_create_clob(), fbsql_read_blob() e fbsql_read_clob().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
fbsql_start_db()
Vedere anche: fbsql_db_status() e fbsql_stop_db().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
fbsql_stop_db()
Vedere anche: fbsql_db_status() e fbsql_start_db().
La funzione fbsql_tablename() utilizza il puntatore al risultato restituito da fbsql_list_tables() e restituisce il nome della tabella. Si può, inoltre, utilizzare la funzione fbsql_num_rows() per determinare il numero di tabelle presenti in un risultato.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Le funzioni in questa estensione implementano l'accesso client ad un file server utilizzando il File Transfer Protocol (FTP) come definito in http://www.faqs.org/rfcs/rfc959.html.
Usando il modulo FTP vengono definite le seguenti costanti: FTP_ASCII e FTP_BINARY.
Per l'utilizzo delle funzioni FTP con la vostra configurazione PHP, dovrete aggiungere l'opzione --enable-ftp durante l'installazione PHP 4, e --with-ftp nell'installazione di PHP 3.
Esempio 1. FTP
|
Sends an ALLO command to the remote FTP server to allocate space for a file to be uploaded.
Nota: Many FTP servers do not support this command. These servers may return a failure code (FALSE) indicating the command is not supported or a success code (TRUE) to indicate that pre-allocation is not necessary and the client should continue as though the operation were successful. Because of this, it may be best to reserve this function for servers which explicitly require preallocation.
The link identifier of the FTP connection.
The number of bytes to allocate.
A textual representation of the servers response will be returned by reference in result if a variable is provided.
Esempio 1. ftp_alloc() example
|
Passa alla directory superiore.
Esempio 1. ftp_cdup() example
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedi anche ftp_chdir().
Passa dalla directory corrente alla directory specificata.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. esempio ftp_chdir()
|
Vedi anche ftp_cdup().
Sets the permissions on the specified remote file to mode.
The link identifier of the FTP connection.
The new permissions, given as an octal value.
The remote file.
Esempio 1. ftp_chmod() example
|
ftp_close() chiude ftp_stream e rilascia la risorsa. Dopo aver chiamato questa funzione, non e' piu' possibile usare la connessione FTP ed e' necessario crearne una nuova con ftp_connect().
Esempio 1. esempio di funzione ftp_close()
|
Vedere anche ftp_connect()
Restituisce un flusso FTP stream in caso di successo, FALSE in caso di errore.
La funzione ftp_connect() apre una connessione FTP all' host specificato. host non deve essere seguito da barre e non deve essere precedeuto da ftp://. Il parametro port specifica una porta alternativa cui connettersi. Se e' omesso o impostato a zero verra' usata la porta 21, default di FTP.
Il parametro timeout specifica il timeout per tutte le successive operazioni di rete. Se omesso il valore predefinito e' di 90 secondi. Il timeout puo' essere modificato o interrogato in qualsiasi momento con ftp_set_option() e ftp_get_option().
Nota: Il parametro timeout e' disponibile a partire dalla release PHP 4.2.0.
Vedere anche ftp_close(), e ftp_ssl_connect().
ftp_delete() cancella il file specificato da path dal server FTP.
Esempio 1. Esempio di funzione ftp_delete()
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Invia una richiesta SITE EXEC command al server FTP. Restituisce TRUE se il comando viene eseguito correttamente (codice di risposta: 200 da parte del server); altrimenti restituisce FALSE.
Esempio 1. Esempio di funzione ftp_exec()
|
Vedere anche ftp_raw().
(PHP 3 >= 3.0.13, PHP 4, PHP 5)
ftp_fget -- Scarica un file dal server FTP e lo salva su un file apertoftp_fget() recupera remote_file dal server FTP, e lo scrive sul file specificato dal puntatore, handle. Il modo di trasferimento mode specificato deve essere FTP_ASCII oppure FTP_BINARY.
Esempio 1. Esempio di funzione ftp_fget()
|
Nota: Il parametro resumepos e' stato aggiunto in PHP 4.3.0.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche ftp_get(), ftp_nb_get() e ftp_nb_fget().
ftp_fput() carica i dati del file cui fa riferimento il puntatore handle fino a quando viene raggiunta la fine del file. I risultati sono salvati in remote_file sul server FTP. Il modo di trasferimento mode specificato deve essere FTP_ASCII oppure FTP_BINARY.
Esempio 1. Esempio di funzione ftp_fput()
|
Nota: Il parametro startpos e' stato aggiunto in PHP 4.3.0.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche ftp_put(), ftp_nb_fput(), e ftp_nb_put().
(PHP 4 >= 4.2.0, PHP 5)
ftp_get_option -- Recupera diversi comportamenti dello stream FTP durante l'esecuzioneRestituisce il valore in caso di successo oppure FALSE se l'opzione option data non e' supportata. In quest'ultimo caso, viene anche visualizzato un messaggio di avvertimento.
Questa funzione restituisce il valore dell'opzione option richiesta dallo stream FTP ftp_stream specificato. Attualmente sono riconosciute le seguenti opzioni:
Tabella 1. Opzioni di runtime FTP riconosciute
FTP_TIMEOUT_SEC | Restituisce il timeout corrente, usato in operazioni di rete. |
Vedere anche ftp_set_option().
ftp_get() recupera remote_file dal server FTP, e lo salva sul file locale local_file. Il modo di trasferimento mode specificato deve essere FTP_ASCII oppure FTP_BINARY.
Nota: Il parametro resumepos e' stato aggiunto in PHP 4.3.0.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. Esempio di funzione ftp_get()
|
Vedere anche ftp_fget(), ftp_nb_get() e ftp_nb_fget().
Esegue il log allo stream FTP richiesto.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. Esempio di funzione ftp_login()
|
(PHP 3 >= 3.0.13, PHP 4, PHP 5)
ftp_mdtm -- Restituisce l'orario dell'ultima modifica al file correnteLa funzione ftp_mdtm() controlla l'orario dell'ultima modifica ad un file, e lo restituisce in formato timestamp Unix. Se si verifica un errore, o il file non esiste, restituisce -1.
Restituisce un timestamp Unix in caso di successo, o -1 in caso di errore.
Esempio 1. Esempio di funzione ftp_mdtm()
|
Nota: Non tutti i server includono questa funzione!
Nota: La funzione ftp_mdtm() non funziona con le directories.
Crea la directory specificata sul server FTP.
Restituisce la directory appena creata in caso di successo o FALSE in caso di errore.
Esempio 1. Esempio di funzione ftp_mkdir()
|
Vedere anche ftp_rmdir().
(PHP 4 >= 4.3.0, PHP 5)
ftp_nb_continue -- Continua a ricevere/trasmettere un file in modalita' non bloccanteContinua a ricevere/trasmettere un file in modalita' non bloccante.
Esempio 1. Esempio di funzioneftp_nb_continue()
|
Restituisce FTP_FAILED oppure FTP_FINISHED oppure FTP_MOREDATA.
(PHP 4 >= 4.3.0, PHP 5)
ftp_nb_fget -- Recupera un file dal server FTP e lo scrive su un file aperto, in modalita' non bloccanteLa funzione ftp_nb_fget() recupera remote_file dal server FTP, e lo scrive nella posizione cui punta il puntatore a file handle. La modalita' di trasferimento, mode, specificata deve essere FTP_ASCII oppure FTP_BINARY. La differenza tra questa funzione e la funzione ftp_fget() e' che questa funzione recupera il file in modo asincrono, cosicche' il programma puo' eseguire altre operazioni mentre il file viene scaricato.
Esempio 1. Esempio di funzione ftp_nb_fget()
|
Restituisce FTP_FAILED, FTP_FINISHED, oppure FTP_MOREDATA.
Vedere anche ftp_nb_get(), ftp_nb_continue(), ftp_fget(), and ftp_get().
(PHP 4 >= 4.3.0, PHP 5)
ftp_nb_fput -- Salva il contenuto di un file aperto sul server FTP in modalita' non bloccanteLa funzione ftp_nb_fput() carica i dati dalla posizione puntata dal puntatore handle fino a quando non raggiunge la fine del file. Il risultato e' salvato in remote_file sul server FTP. La modalita' di trasferimento, mode specificata deve essere FTP_ASCII oppure FTP_BINARY. La differenza tra questa funzione e la funzione ftp_fput() e' che questa funzione trasferisce il file in modo asincrono, cosicche' il programma puo' eseguire altre operazioni mentre il file viene caricato.
Esempio 1. Esempio di funzione ftp_nb_fput()
|
Restituisce FTP_FAILED, FTP_FINISHED, oppure FTP_MOREDATA.
Vedere anche ftp_nb_put(), ftp_nb_continue(), ftp_put() e ftp_fput().
(PHP 4 >= 4.3.0, PHP 5)
ftp_nb_get -- Recupera un file dal server FTP e lo scrive su un file locale in modalita' non bloccanteLa funzione ftp_nb_get() recupera remote_file dal server FTP, e lo salva localmente su local_file. La modalita' di trasferimento, mode, specificata deve essere FTP_ASCII oppure FTP_BINARY. La differenza tra questa funzione e la funzione ftp_get() e' che questa funzione recupera il file in modo asincrono, cosicche' il programma puo' eseguire altre operazioni mentre il file viene scaricato.
Restituisce FTP_FAILED, FTP_FINISHED, oppure FTP_MOREDATA.
Esempio 1. Esempio di funzione ftp_nb_get()
|
Esempio 2. Ripresa di uno scaricamento con ftp_nb_get()
|
Esempio 3. Ripresa di uno scaricamento dalla posizione 100 su un nuovo file con ftp_nb_get()
|
Nell'esempio precedente, "newfile" e' 100 bytes piu' piccolo di "README" sul server FTP perche' la lettura e' iniziata dall'offset 100. Se FTP_AUTOSEEKnon fosse stata disabilitata, i primi 100 bytes di "newfile" sarebbero stati '\0'.
Vedere anche ftp_nb_fget(), ftp_nb_continue(), ftp_get(), e ftp_fget().
La funzione ftp_nb_put() salva local_file sul server FTP come remote_file. La modalita' di trasferimento, mode specificata deve essere FTP_ASCII oppure FTP_BINARY. La differenza tra questa funzione e la funzione ftp_put() e' che questa funzione trasferisce il file in modo asincrono, cosicche' il programma puo' eseguire altre operazioni durante il trasferimento.
Restituisce FTP_FAILED, FTP_FINISHED, oppure FTP_MOREDATA.
Esempio 1. Esempio di funzione ftp_nb_put()
|
Esempio 2. Ripresa di un trasferimento con ftp_nb_put()
|
Vedere anche ftp_nb_fput(), ftp_nb_continue(), ftp_put(), e ftp_fput().
Restituisce un array di nomi di file dalla directory specificata in caso di corretta esecuzione oppure FALSE in caso di errore.
Esempio 1. Esempio di funzione ftp_nlist()
L'esempio precedente visualizza qualcosa del tipo:
|
Vedere anche ftp_rawlist().
ftp_pasv() attiva il modo passivo se il parametro pasv e' TRUE. Disattiva il modo passivo se pasv e' FALSE. Nel modo passivo, le connessioni sono iniziate dal client piuttosto che dal server.
Esempio 1. Esempio di funzione ftp_pasv()
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
ftp_put() salva local_file sul server FTP come remote_file. Il modo di trasferimento mode specificato deve essere FTP_ASCII oppure FTP_BINARY.
Nota: Il parametro startpos e' stato aggiunto nella release PHP 4.3.0.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. Esempio di funzione ftp_put()
|
Vedere anche ftp_fput(), ftp_nb_fput(), e ftp_nb_put().
Restituisce la directory corrente oppure FALSE in caso di errore.
Esempio 1. Esempio di funzione ftp_pwd()
|
Invia un command di qualsiasi tipo al server FTP. Restituisce la risposta del server sotto forma di un array di stringhe. ftp_raw() non esegue il parsing della stringa di risposta, ne' controlla se il comando e' stato eseguito correttamente.
Vedi anche: ftp_exec()
(PHP 3 >= 3.0.13, PHP 4, PHP 5)
ftp_rawlist -- Restituisce un elenco dettagliato dei files nella directory in esameftp_rawlist() esegue il comando FTP LIST, e restituisce il risultato sotto forma di array. Ogni elemento dell'array corrisponde ad una linea di testo. Sull'output non viene eseguito parsing. L'identificatore di tipo di sistema restituito da ftp_systype() puo' essere utilizzato per interpretare il risultato.
Esempio 1. Esempio di funzione ftp_rawlist()
L'esempio precedente produrra' qualcosa di simile a:
|
Vedere anche ftp_nlist().
ftp_rename() rinomina il file o la directory il cui nome corrente e' from con il nome to, utilizzando lo stream FTP ftp_stream.
Esempio 1. Esempio di funzione ftp_rename()
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Elimina la directory specificata. directory deve essere un percorso assoluto o relativo ad una directory vuota.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. Esempio di funzione ftp_rmdir()
|
Vedere anche ftp_mkdir().
Restituisce TRUE se e'stato possibile impostare l'opzione; FALSE altrimenti. Se l'opzione option non e' supportata o il valore value del parametro passato alla funzione non corrisponde al valore atteso per l'opzione option scelta, viene generato un messaggio di errore.
Questa funzione controlla varie opzioni che hanno effetto durante l'esecuzione dello stream FTP specificato. Il parametro value dipende da quale parametro option viene scelto per essere modificato. Attualmente sono riconosciute le seguenti opzioni:
Tabella 1. Opzioni supportate per l'esecuzione di FTP
FTP_TIMEOUT_SEC | Modifica il timeout in secondi utilizzata per tutte le funzioni di rete. Il parametro value deve essere un intero maggiore di 0. Il timeout predefinito e' di 90 secondi. |
FTP_AUTOSEEK | Quando attivata, richieste GET or PUT con un parametro resumepos o startpos iniziano la ricerca dalla posizione richiesta all'interno del file. This is enabled Questa opzione e' attivata di default. |
Vedere anche ftp_get_option().
La funzione ftp_site() invia al server FTP il comando specificato dal parametro cmd. I comandi SITE non sono standardizzati e sono diversi da server a server. They are Sono utili per operare, ad esempio, sui permessi dei file o sull'appartenenza a gruppi.
Esempio 1. Invio di un comando SITE ad un server ftp
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche: ftp_raw()
La funzione ftp_size() restituisce le dimensioni del file remote_file in bytes. Se si verifica un errore, se il file specificato non esiste, o se e' una directory, viene restituito -1. Non tutti i server supportano questa caratteristica.
Restituisce le dimensioni del file in caso di successo, o -1 in caso di errore.
Esempio 1. Esempio di funzione ftp_size()
|
Vedere anche ftp_rawlist().
Restituisce uno stream SSL-FTP in caso di successo o FALSE in caso di errore.
La funzione ftp_ssl_connect() apre una connessione SSL-FTP verso il server host. Il parametro port specifica una porta alternativa a cui connettersi. Se omesso o impostato a zero allora viene usata la porta 21 standard.
Il parametro timeout specifica il timeout per tutte le operazioni di rete successive. Se omesso il valore predefinito e' di 90 secondi. Il timeout puo' essere interrogato o modificato in qualsiasi momento con le funzioni ftp_set_option() e ftp_get_option().
Esempio 1. Esempio di funzione ftp_ssl_connect()
|
Perche' questa funzione puo' non essere presente: La funzione ftp_ssl_connect() e' disponibile solo se il supporto OpenSSL e' abilitato nella versione corrente di PHP. Se non e' definito ed e' stato incluso il supporto a FTP durante la compilazione, questa e' la ragione per cui la funzione non e' presente.
Vedere anche ftp_connect().
(PHP 3 >= 3.0.13, PHP 4, PHP 5)
ftp_systype -- Restituisce l'identificatore di tipo del server FTP remotoRestituisce il tipo del sistema remoto, o FALSE in caso di errore.
Esempio 1. Esempio di funzioneftp_systype()
L'esempio precedente produrra' in uscita qualosa di simile a:
|
These functions all handle various operations involved in working with functions.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
(PHP 4 >= 4.0.4, PHP 5)
call_user_func_array -- Call a user function given with an array of parametersCall a user defined function given by function, with the parameters in param_arr. For example:
Esempio 1. call_user_func_array() example
|
See also call_user_func(), and information about the callback type
Call a user defined function given by the function parameter. Take the following:
<?php function barber($type) { echo "You wanted a $type haircut, no problem"; } call_user_func('barber', "mushroom"); call_user_func('barber', "shave"); ?> |
Object methods may also be invoked statically using this function by passing array($objectname, $methodname) to the function parameter.
<?php class myclass { function say_hello() { echo "Hello!\n"; } } $classname = "myclass"; call_user_func(array($classname, 'say_hello')); ?> |
Nota: Note that the parameters for call_user_func() are not passed by reference.
See also: is_callable(), call_user_func_array(), e information about the callback type.
Creates an anonymous function from the parameters passed, and returns a unique name for it. Usually the args will be passed as a single quote delimited string, and this is also recommended for the code. The reason for using single quoted strings, is to protect the variable names from parsing, otherwise, if you use double quotes there will be a need to escape the variable names, e.g. \$avar.
You can use this function, to (for example) create a function from information gathered at run time:
Esempio 1. Creating an anonymous function with create_function()
|
Or, perhaps to have general handler function that can apply a set of operations to a list of parameters:
Esempio 2. Making a general processing function with create_function()
and when you run the code above, the output will be:
|
But perhaps the most common use for of lambda-style (anonymous) functions is to create callback functions, for example when using array_walk() or usort()
Esempio 3. Using anonymous functions as callback functions
outputs:
an array of strings ordered from shorter to longer
outputs:
sort it from longer to shorter
outputs:
|
Returns the argument which is at the arg_num'th offset into a user-defined function's argument list. Function arguments are counted starting from zero. func_get_arg() will generate a warning if called from outside of a function definition. This function cannot be used directly as a function parameter. Instead, its result may be assigned to a variable, which can then be passed to the function.
If arg_num is greater than the number of arguments actually passed, a warning will be generated and func_get_arg() will return FALSE.
Nota: Because this function depends on the current scope to determine parameter details, it cannot be used as a function parameter. If you must pass this value, assign the results to a variable, and pass the variable.
<?php function foo() { $numargs = func_num_args(); echo "Number of arguments: $numargs<br />\n"; if ($numargs >= 2) { echo "Second argument is: " . func_get_arg(1) . "<br />\n"; } } foo (1, 2, 3); ?> |
func_get_arg() may be used in conjunction with func_num_args() and func_get_args() to allow user-defined functions to accept variable-length argument lists.
Returns an array in which each element is a copy of the corresponding member of the current user-defined function's argument list. func_get_args() will generate a warning if called from outside of a function definition. This function cannot be used directly as a function parameter. Instead, its result may be assigned to a variable, which can then be passed to the function.
Nota: This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments.
Nota: Because this function depends on the current scope to determine parameter details, it cannot be used as a function parameter. If you must pass this value, assign the results to a variable, and pass the variable.
<?php function foo() { $numargs = func_num_args(); echo "Number of arguments: $numargs<br />\n"; if ($numargs >= 2) { echo "Second argument is: " . func_get_arg(1) . "<br />\n"; } $arg_list = func_get_args(); for ($i = 0; $i < $numargs; $i++) { echo "Argument $i is: " . $arg_list[$i] . "<br />\n"; } } foo(1, 2, 3); ?> |
func_get_args() may be used in conjunction with func_num_args() and func_get_arg() to allow user-defined functions to accept variable-length argument lists.
Returns the number of arguments passed into the current user-defined function. func_num_args() will generate a warning if called from outside of a user-defined function. This function cannot be used directly as a function parameter. Instead, its result may be assigned to a variable, which can then be passed to the function.
Nota: Because this function depends on the current scope to determine parameter details, it cannot be used as a function parameter. If you must pass this value, assign the results to a variable, and pass the variable.
<?php function foo() { $numargs = func_num_args(); echo "Number of arguments: $numargs\n"; } foo(1, 2, 3); // Prints 'Number of arguments: 3' ?> |
func_num_args() may be used in conjunction with func_get_arg() and func_get_args() to allow user-defined functions to accept variable-length argument lists.
Checks the list of defined functions, both built-in (internal) and user-defined, for function_name. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
<?php if (function_exists('imap_open')) { echo "IMAP functions are available.<br />\n"; } else { echo "IMAP functions are not available.<br />\n"; } ?> |
Note that a function name may exist even if the function itself is unusable due to configuration or compiling options (with the image functions being an example). Also note that function_exists() will return FALSE for constructs, such as include_once() and echo().
See also method_exists(), is_callable() and get_defined_functions().
This function returns an multidimensional array containing a list of all defined functions, both built-in (internal) and user-defined. The internal functions will be accessible via $arr["internal"], and the user defined ones using $arr["user"] (see example below).
<?php function myrow($id, $data) { return "<tr><th>$id</th><td>$data</td></tr>\n"; } $arr = get_defined_functions(); print_r($arr); ?> |
Will output something along the lines of:
Array ( [internal] => Array ( [0] => zend_version [1] => func_num_args [2] => func_get_arg [3] => func_get_args [4] => strlen [5] => strcmp [6] => strncmp ... [750] => bcscale [751] => bccomp ) [user] => Array ( [0] => myrow ) ) |
See also function_exists(), get_defined_vars() and get_defined_constants().
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
register_shutdown_function -- Register a function for execution on shutdownRegisters the function named by function to be executed when script processing is complete.
Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called.
In PHP 4.0.6 and earlier under Apache, the registered shutdown functions are called after the request has been completed (including sending any output buffers), so it is not possible to send output to the browser using echo() or print(), or retrieve the contents of any output buffers using ob_get_contents(). Since PHP 4.1, the shutdown functions are called as the part of the request so that it's possible to send the output from them. There is currently no way to process the data with output buffering functions in the shutdown function. Shutdown function is called after closing all opened output buffers thus, for example, its output will not be compressed if zlib.output_compression is enabled.
As of PHP 4, it is possible to pass parameters to the shutdown function by passing additional parameters to register_shutdown_function().
Nota: Typically undefined functions cause fatal errors in PHP, but when the function called with register_shutdown_function() is undefined, an error of level E_WARNING is generated instead. Also, for reasons internal to PHP, this error will refer to Unknown at line #0.
Nota: Working directory of the script can change inside the shutdown function under some web servers, e.g. Apache.
Nota: Shutdown function is called during the script shutdown so headers are always already sent.
See also auto_append_file, exit(), and the section on connection handling.
Registers the function named by func to be executed when a tick is called. Also, you may pass an array consisting of an object and a method as the func.
Avvertimento |
register_tick_function() should not be used with threaded webserver modules. Ticks are not working in ZTS mode and may crash your webserver. |
See also declare and unregister_tick_function().
(PHP 4 >= 4.0.3, PHP 5)
unregister_tick_function -- De-register a function for execution on each tickDe-registers the function named by function_name so it is no longer executed when a tick is called.
The gettext functions implement an NLS (Native Language Support) API which can be used to internationalize your PHP applications. Please see the gettext documentation for your system for a thorough explanation of these functions or view the docs at http://www.gnu.org/software/gettext/manual/gettext.html.
To use these functions you must download and install the GNU gettext package from http://www.gnu.org/software/gettext/gettext.html
To include GNU gettext support in your PHP build you must add the option --with-gettext[=DIR] where DIR is the gettext install directory, defaults to /usr/local.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
(PHP 4 >= 4.2.0, PHP 5)
bind_textdomain_codeset -- Specify the character encoding in which the messages from the DOMAIN message catalog will be returnedWith bind_textdomain_codeset(), you can set in which encoding will be messages from domain returned by gettext() and similar functions.
The bindtextdomain() function sets the path for a domain. It returns the full pathname for the domain currently being set.
This function allows you to override the current domain for a single message lookup. It also allows you to specify a category.
See also gettext().
This function allows you to override the current domain for a single plural message lookup. It also allows you to specify a category.
See also ngettext().
The dgettext() function allows you to override the current domain for a single message lookup.
See also gettext().
The dngettext() function allows you to override the current domain for a single plural message lookup.
See also ngettext().
This function returns a translated string if one is found in the translation table, or the submitted message if not found. You may use the underscore character '_' as an alias to this function.
Esempio 1. gettext()-check
|
See also setlocale().
ngettext() returns correct plural form of message identified by msgid1 and msgid2 for count n. Some languages have more than one form for plural messages dependent on the count.
This function sets the domain to search within when calls are made to gettext(), usually the named after an application.
Queste funzioni permettono di lavorare con numeri interi di lunghezza arbitraria usando le librerie GNU MP.
Queste funzioni sono state aggiunte in PHP 4.0.4.
Nota: Molte funzioni accettano argomenti numerici GMP, definiti come risorsepiù in basso. Comunque, molte di queste funzioni accetteranno anche normali argomenti numerici e stringhe, considerato ciò è quindi possibile convertire queste ultime in numero. Inoltre, se c'è una funzione che può operare velocemente su argomenti interi, questa potrebbe essere usata al posto della più lenta quando l'argomento fornito è un intero. Questo è fatto con chiarezza, così la logica vuole che tu possa utilizzare numeri interi in ogni funzione che richieda un numero GMP. Vedere anche la funzione gmp_init().
Avvertimento |
Se desideri specificare un "large integer" come costante, scrivilo tra virgolette come stringa. Se non lo fai, PHP interpreterà l'"integer literal" immediatamente, con una possibile perdita di precisione, ancora prima che la libreria GMP venga richiamata. |
Nota: Questo modulo non è disponibile su piattaforme Windows.
Puoi scaricare la libreria GMP dal sito http://www.swox.com/gmp/. Dove è possibile anche scaricare il manuale GMP.
Per usare queste funzioni è necessaria la versione 2 o superiore delle librerie GMP.
Per potere utilizzare queste funzioni, occorre compilare il PHP con il supporto GMP utilizzando il parametro --with-gmp.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Ulteriori funzioni matematiche sono elencate nelle sezioni BCMath Funzione Matematiche a Precisione Arbitraria e Funzioni Matematiche.
Somma due numeri GMP. Il risultato, sarà un numero GMP che rappresenta la somma degli argomenti.
Ripulisce (imposta a 0) il bit index in a.
Restituisce un valore positivo se a > b, zero se a = b e negativo se a < b.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Divide a per b e restituisce un numero intero. L'arrotondamento del risultato, è definito dal round, che può avere i seguenti valori:
GMP_ROUND_ZERO: Il risultato è troncato verso 0.
GMP_ROUND_PLUSINF: Il risultato è arrotondato verso +infinito.
GMP_ROUND_MINUSINF: Il risultato è arrotondato verso -infinito.
Questa funzione può anche essere richiamata come gmp_div().
Vedere anche gmp_div_r(), gmp_div_qr()
Questa funzione, esegue la divisione tra n e d , restituendo un array, il primo elemento è, [n/d] (il risultato intero della divisione) il secondo è (n - [n/d] * d) (cioè il resto della divisone).
Vedere la funzione gmp_div_q() per la descrizione dell'argomento round.
Vedere anche gmp_div_q(), gmp_div_r().
Calcola il resto di una divisione intera fra n e d. Se non è zero, il resto ha il segno dell'argomento n.
Vedi la funzione gmp_div_q() per la descrizione dell'argomento round.
Vedere anche gmp_div_q(), gmp_div_qr()
Divide n per d, usando un algoritmo di "esatta divisione". Questa funzione, restituisce un valore corretto solo quando è noto a priori che d divide n.
Calcola il massimo comune divisore (MCD) di a e b. Il risultato è sempre positivo, anche se uno o entrambi gli operatori sono negativi.
Calcola g, s e t, in questo modo a*s + b*t = g = gcd(a,b), dove MCD è il massimo comune divisore. Restituisce un array con i rispettivi argomenti, cioè, g, s e t.
Restituisce la distanza di hamming tra a e b. Entrambe gli operandi dovrebbero essere non-negativi.
Crea un numero GMP partendo da un intero o da una stringa. La stringa può essere decimale o esadecimale. Nell'ultimo caso, la stringa dovrebbe iniziare con 0x.
Nota: Non è necessario chiamare uesta funzione se si vogliono usare interi o stringhe al posto di numeri GMP nelle funzioni GMP, come gmp_add(). Se se questa conversione è possibile e necessaria, gli argomenti delle funzioni vengono automaticamente convertiti in numeri GMP, usando le stesse regole di gmp_init().
Questa funzione converte un numero GMP in un intero.
Avvertimento |
Questa funzione restituisce un risultato utile, solo se il numero attualmente fornito al PHP è un intero (per esempio, un tipo signed long). Se desideri solo stampare il numero GMP, usa gmp_strval(). |
Calcola l'inverso di a modulo b. Restituisce un valore FALSE se l'inversione non esiste.
Calcola il simbolo di Jacobi di a e p. p p potrebbe essere dispari e deve essere positivo.
Calcolo del Legendre symbol di a e p. p potrebbe essere dispari e deve essere positivo.
Calcola il modulo di n rispetto a d. Il risultato è sempre non-negativo, il segno di d viene ignorato.
Moltiplica a per b e restituisce il risultato.
Restituisce un valore vero TRUE se a è un quadrato perfetto,falso FALSE se non lo è.
Vedere anche: gmp_sqrt(), gmp_sqrtrm().
Eleva la base base ad una potenza exp. Nel caso di 0^0 il risultato sarà 1. L'argomento exp non può essere negativo.
Calcola il (base elevato a potenza exp) modulo mod. Se exp è negativo, il risultato sarà indefinito.
Se questa funzione da come risultato 0, a non è primo. Se sarà 1, allora a è "probabilmente" primo. Invece se il risultato è 2, allora a sarà sicuramente primo. I valori "attendibili" di reps possono variare da 5 a 10 (di default 10); un valore più alto fa diminuire la probabilità che un numero non primo passi come "probabile" primo.
La funzione usa il test probabilistico di Miller-Rabin.
Genera un numero casuale. Il numero, sarà lungo un numero di WORD (2 byte) non superiore all'argomento limiter. Se l'argomento limiter è negativo, il numero generato sarà anch'esso negativo.
Cerca in a, partendo dal bit startverso i bit più significativi, fermandosi sul primo bit nullo, di cui restituisce l'indice.
Cerca in a, partendo dal bit start, verso i bit più significativi, fermandosi sul primo bit nullo, di cui restituisce l'indice.
Sets bit index in a. set_clear definisce se il bit è settato su 0 o su 1. Di default il bit è settato a 1.
Restituisce il segno di a : 1 se a è positivo e -1 se è negativo.
Restituisce un array con due valori, il primo è la radice quadrata (fornita come intero) di a (vedere anche gmp_sqrt()), e il secondo è il resto (cioè, la differenza tra a e il primo elemento al quadrato).
Converte un numero GMP in una stringa rappresentato in base base. La base di default è 10. Le basi consentite variano dal 2 al 36.
The gopher protocol, as defined by RFC 1436, is generally considered the ancestor of the modern HTTP protocol. However, gopher was also intended to provide references to non-gopher resources including telnet, wais, nntp, and even http. This extension adds gopher support to PHP's URL Wrappers, and provides a helper function gopher_parsedir() to make sense of gopher formatted directory listings.
Net_Gopher is installed through the usual PECL package installation process.
Prerequisite: PHP 4.3.0.
$ pear install Net_Gopher |
Copy the resulting gopher.so to an appropriate location and add extension=gopher.so to your php.ini file or load it dynamically in your PHP script using dl("gopher.so");
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
While gopher returns text/plain documents for actual document requests. A request to a directory (such as /) will return specially encoded series of lines with each line being one directory entry or information line.
Esempio 1. Hypothetical output from gopher://gopher.example.com/
|
In the example above, the root directory at gopher.example.com knows about one DOCUMENT identified by 0 located at gopher://gopher.example.com:70/allabout.txt. It also knows about two other directory (which have their own listing files) at gopher://gopher.exmaple.com:70/stories and at gopher://gopher.ejemplo.co.es:70/. In addition there is a binary file, a link to an HTTP url, and several informative lines.
By passing each line of the directory listing into gopher_parsedir(), an associative array is formed containing a parsed out version of the data.
Esempio 2. Using gopher_parsedir()
|
The values given by type are associated with the following constants.
Tabella 1. Gopher Constants
Constant | Definition |
---|---|
GOPHER_DOCUMENT | Standard text/plain document. |
GOPHER_DIRECTORY | A resource containing a gopher formatted directory listing. |
GOPHER_BINHEX | A BinHex encoded binary file. |
GOPHER_DOSBINARY | A DOS formatted binary archive. |
GOPHER_UUENCODED | A UUEncoded file. |
GOPHER_BINARY | A generic binary file. |
GOPHER_INFO | An Informational entry |
GOPHER_HTTP | A reference to an HTTP resource. |
GOPHER_UNKNOWN | An unrecognized entry, the line will be returned in data. |
Queste funzioni permettono di modificare l'output inviato verso un browser attraverso manipolazioni a livello di protocollo HTTP.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
header() si utilizza per inviare header HTTP. Per maggiorni informazioni riguardanti gli header HTTP si veda la risorsa HTTP 1.1 specification.
L'argomento opzionale replace indica se l'header inviato deve sostituirne uno simile spedito precedentemente, o accodarsi al primo dello stesso tipo. Per default la funzione sostituisce l'header precedente, ma se viene passato FALSE come secondo argomento vengono forzate intestazioni multiple. Per esempio:
Ci sono due casi speciali di chiamate di header. Il primo è "Location". Location non trasmette solo un header al browser, ma anche un REDIRECT con codice di stato (302).
header("Location: http://www.php.net/"); /* Ridireziona il browser al sito di PHP */ exit; /* Assicura che il codice sottostante non sia eseguito dopo il redirezionamento. */ |
Nota: HTTP/1.1 richiede un URI assoluto come argomento di Location: composto da schema, hostname, e path assoluto, ma alcuni clients possono accettare anche URIs relativi. E' possibile usare $HTTP_SERVER_VARS['HTTP_HOST'], $HTTP_SERVER_VARS['PHP_SELF'] e dirname() per creare URI assoluti da URI relativi in modo automatico:
Il secondo caso speciale è esemplificato dalle intestazioni che iniziano con la stringa, "HTTP/" (le maiuscole non sono discriminanti), che è usato per inviare codici di stato HTTP. Per esempio, se si è configurato Apache per usare script PHP per la manipolazione di richieste fallite (usando la direttiva ErrorDocument), potete desiderare di assicurarvi che il vostro script generi il codice adeguato.
Nota: In PHP 3, questo funziona solo se PHP è compilato come modulo Apache. Potete ottenere lo stesso effetto usando l'header Status.
Spesso gli scrit PHP generano contenuti dinamici, se volete evitare che i contenuti vengano mantenuti nella cache di browser o proxy, potete forzare il loro comportamento con questa direttiva:
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Data passata header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // sempre modificato header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1 header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); // HTTP/1.0 |
Nota: E' possibile che alcune pagine rimangano in chache anche dopo l'uso degli header descritti sopra. Ci sono delle opzioni che l'utente può settare dal browser, capaci di modificare i comportamenti di default del caching. Per trasmettere efficacemente gli header descritti, bisogna che sia inattiva ogni regolazione che può forzare comportamenti contrari.
Inoltre, session_cache_limiter() e e la configurazione session.cache_limiter possono essere usate per generare automaticamente i corretti header relativi al caching durante l'uso delle sessioni.
Bisogna ricordare che la funzioneheader() va chiamata prima di qualsiasi output HTML o PHP (anche righe o spazi vuoti). E' un errore comune leggere files con funzioni include(), o require() (o altre funzioni capaci di accedere a files), che possano emettere in output spazi o linee vuote prima di una chiamata della funzione header(). Lo stesso problema esiste nell'utilizzare file PHP/HTML.
<?php require("user_logging.inc") ?> <?php header ("Content-type: audio/x-pn-realaudio"); ?> // Non funziona, notate le linee vuote sopra |
Nota: In PHP 4, potete usare il buffering dell'output per aggirare questo problema, evitando ogni output al browser trattenedolo al server fino a che non gli si impone l'invio. Si può fare questa operazione chiamando ob_start() e ob_end_flush() nello script, o settando la direttiva di configurazione output_buffering nel file php.ini o nel file di configurazione del server.
Se desiderate che l'utente sia spinto a salvare i dati trasmessi per esempio utilizzando un file PDF, potete usare l'header Content-Disposition, che vi permette di dare un nome al file e forzare il browser a mostrare la finestra di dialogo save.
<?php header("Content-type: application/pdf"); header("Content-Disposition: attachment; filename=downloaded.pdf"); /* ... manda in output un file pdf ... */ |
Nota: Per un bug di Microsoft Internet Explorer 4.01 qusto sistema non funziona. Non ci sono soluzioni. C'è un altro bug in Microsoft Internet Explorer 5.5 che impedisce il giusto funzionamento, ma è possibile risolverlo con l'upgrade del Service Pack 2 o superiore.
Vedi anche headers_sent(), setcookie(), e la sezione Autenticazione HTTP usando PHP.
headers_list() will return a numerically indexed array of headers to be sent to the browser / client. To determine whether or not these headers have been sent yet, use headers_sent().
Esempio 1. Examples using headers_list()
this will output :
|
See Also: headers_sent(), header(), and setcookie().
Questa funzione restituisce TRUE se gli header HTTP sono stati spedite correttamente, FALSE in caso contrario.
Vedi anche header()
setcookie() definisce un cookie da inviare insieme alle altre informazioni di header. I cookie devono essere spediti prima di qualsiasi altra intestazione (questa è una restrizione dei cookies, non di PHP). E' necessario perciò chiamare la funzione setcookie() prima di qualsiasi tags, anche <html> o <head>.
Tutti gli argomenti della funzione eccetto name sono opzionali. Se viene passato alla funzione solo l'argomento name, il cookie registrato con quel nome verrà cancellato dal client su cui è archiviato. E' possibile sostituire gli argomenti che non si intende specificare utitlizzando una stringa vuota (""). Gli argomenti expire e secure che richiedono numeri interi, non possono essere omessi inserendo una stringa vuota, per questo scopo si usa (0). L'argomento expire è un normale intero Unix Timestamp ottenibile grazie alle funzioni time() o mktime(). secure sta ad indicare che il cookie dovrebbe essere trasmesso soltanto attraverso un collegamento sicuro di tipo HTTPS.
Errori comuni:
I cookie diventano disponibili soltanto dalla pagina successiva a quella che li ha generati, o dopo il ricaricamento di questa.
I cookie devono essere cancellati specificando gli stessi parametri con cui sono stati creati.
In PHP 3, chiamate successive di setcookie() nello stesso script sono eseguite in ordine inverso. Se state provando a cancellare un cookie prima dell' inserimento di un altro cookie, dovete creare il secondo prima della cancellazione del primo. In PHP 4, chiamate successive di setcookie() invece, sono eseguite secondo l'ordine di chiamata.
Alcuni esempi sul modo di spedire cookie:
Gli esempi mostrano come cancellare i cookie introdotti nell'esempio precedente:
Si noti che i valori salvati nei cookies sono automaticamente codificati per la trasmissione via URL (urlencoded) quando il cookie viene inviato, e che al momento del richiamo sono automaticamente decodificati e assegnati ad una variabile che ha lo stesso nome del cookie. Per vedere il contenuto di un cookie in uno script, si usa una di queste due sintassi:
Potete registrare array in un cookie usando la notazione degli array al posto del nome del cookie. Questo equivale alla spedizione di tanti cookie quanti sono gli elementi dell'array, ma si ha un vantaggio: quando il cookie è ricevuto, tutti i suoi valori sono ordinati in un singolo array che ha per nome il nome del cookie:
setcookie ("cookie[three]", "cookiethree"); setcookie ("cookie[two]", "cookietwo"); setcookie ("cookie[one]", "cookieone"); if (isset ($cookie)) { while (list ($name, $value) = each ($cookie)) { echo "$name == $value<br>\n"; } } |
Per saperne di più sui cookies, Netscape's cookie specification è la risorsa giusta http://wp.netscape.com/newsref/std/cookie_spec.html.
Microsoft Internet Explorer 4 con Service Pack 1 non crea correttamente cookie che hanno il parametro path specificato.
Netscape Communicator 4.05 e Microsoft Internet Explorer 3.x sembrano utilizzare in modo errato i cookie quando path ed expire non sono specificati.
setrawcookie() is exactly the same as setcookie() except that the cookie value will not be automatically urlencoded when sent to the browser.
See also header(), setcookie() and the cookies section.
Hyperwave has been developed at IICM in Graz. It started with the name Hyper-G and changed to Hyperwave when it was commercialised (in 1996).
Hyperwave is not free software. The current version, 5.5 is available at http://www.hyperwave.com/. A time limited version can be ordered for free (30 days).
See also the Hyperwave API module.
Hyperwave is an information system similar to a database (HIS, Hyperwave Information Server). Its focus is the storage and management of documents. A document can be any possible piece of data that may as well be stored in file. Each document is accompanied by its object record. The object record contains meta data for the document. The meta data is a list of attributes which can be extended by the user. Certain attributes are always set by the Hyperwave server, other may be modified by the user. An attribute is a name/value pair of the form name=value. The complete object record contains as many of those pairs as the user likes. The name of an attribute does not have to be unique, e.g. a title may appear several times within an object record. This makes sense if you want to specify a title in several languages. In such a case there is a convention, that each title value is preceded by the two letter language abbreviation followed by a colon, e.g. 'en:Title in English' or 'ge:Titel in deutsch'. Other attributes like a description or keywords are potential candidates. You may also replace the language abbreviation by any other string as long as it separated by colon from the rest of the attribute value.
Each object record has native a string representation with each name/value pair separated by a newline. The Hyperwave extension also knows a second representation which is an associated array with the attribute name being the key. Multilingual attribute values itself form another associated array with the key being the language abbreviation. Actually any multiple attribute forms an associated array with the string left to the colon in the attribute value being the key. (This is not fully implemented. Only the attributes Title, Description and Keyword are treated properly yet.)
Besides the documents, all hyper links contained in a document are stored as object records as well. Hyper links which are in a document will be removed from it and stored as individual objects, when the document is inserted into the database. The object record of the link contains information about where it starts and where it ends. In order to gain the original document you will have to retrieve the plain document without the links and the list of links and reinsert them. The functions hw_pipedocument() and hw_gettext() do this for you. The advantage of separating links from the document is obvious. Once a document to which a link is pointing to changes its name, the link can easily be modified accordingly. The document containing the link is not affected at all. You may even add a link to a document without modifying the document itself.
Saying that hw_pipedocument() and hw_gettext() do the link insertion automatically is not as simple as it sounds. Inserting links implies a certain hierarchy of the documents. On a web server this is given by the file system, but Hyperwave has its own hierarchy and names do not reflect the position of an object in that hierarchy. Therefore creation of links first of all requires a mapping from the Hyperwave hierarchy and namespace into a web hierarchy respective web namespace. The fundamental difference between Hyperwave and the web is the clear distinction between names and hierarchy in Hyperwave. The name does not contain any information about the objects position in the hierarchy. In the web the name also contains the information on where the object is located in the hierarchy. This leads to two possibles ways of mapping. Either the Hyperwave hierarchy and name of the Hyperwave object is reflected in the URL or the name only. To make things simple the second approach is used. Hyperwave object with name my_object is mapped to http://host/my_object disregarding where it resides in the Hyperwave hierarchy. An object with name parent/my_object could be the child of my_object in the Hyperwave hierarchy, though in a web namespace it appears to be just the opposite and the user might get confused. This can only be prevented by selecting reasonable object names.
Having made this decision a second problem arises. How do you involve PHP? The URL http://host/my_object will not call any PHP script unless you tell your web server to rewrite it to e.g. http://host/php_script/my_object and the script php_script evaluates the $PATH_INFO variable and retrieves the object with name my_object from the Hyperwave server. Their is just one little drawback which can be fixed easily. Rewriting any URL would not allow any access to other document on the web server. A PHP script for searching in the Hyperwave server would be impossible. Therefore you will need at least a second rewriting rule to exclude certain URLs like all e.g. starting with http://host/Hyperwave This is basically sharing of a namespace by the web and Hyperwave server.
Based on the above mechanism links are insert into documents.
It gets more complicated if PHP is not run as a server module or CGI script but as a standalone application e.g. to dump the content of the Hyperwave server on a CD-ROM. In such a case it makes sense to retain the Hyperwave hierarchy and map in onto the file system. This conflicts with the object names if they reflect its own hierarchy (e.g. by choosing names including '/'). Therefore '/' has to be replaced by another character, e.g. '_'.
The network protocol to communicate with the Hyperwave server is called HG-CSP (Hyper-G Client/Server Protocol). It is based on messages to initiate certain actions, e.g. get object record. In early versions of the Hyperwave Server two native clients (Harmony, Amadeus) were provided for communication with the server. Those two disappeared when Hyperwave was commercialised. As a replacement a so called wavemaster was provided. The wavemaster is like a protocol converter from HTTP to HG-CSP. The idea is to do all the administration of the database and visualisation of documents by a web interface. The wavemaster implements a set of placeholders for certain actions to customise the interface. This set of placeholders is called the PLACE Language. PLACE lacks a lot of features of a real programming language and any extension to it only enlarges the list of placeholders. This has led to the use of JavaScript which IMO does not make life easier.
Adding Hyperwave support to PHP should fill in the gap of a missing programming language for interface customisation. It implements all the messages as defined by the HG-CSP but also provides more powerful commands to e.g. retrieve complete documents.
Hyperwave has its own terminology to name certain pieces of information. This has widely been taken over and extended. Almost all functions operate on one of the following data types.
object ID: A unique integer value for each object in the Hyperwave server. It is also one of the attributes of the object record (ObjectID). Object ids are often used as an input parameter to specify an object.
object record: A string with attribute-value pairs of the form attribute=value. The pairs are separated by a carriage return from each other. An object record can easily be converted into an object array with hw_object2array(). Several functions return object records. The names of those functions end with obj.
object array: An associative array with all attributes of an object. The keys are the attribute names. If an attribute occurs more than once in an object record it will result in another indexed or associative array. Attributes which are language depended (like the title, keyword, description) will form an associative array with the keys set to the language abbreviations. All other multiple attributes will form an indexed array. PHP functions never return object arrays.
hw_document: This is a complete new data type which holds the actual document, e.g. HTML, PDF etc. It is somewhat optimized for HTML documents but may be used for any format.
Several functions which return an array of object records do also return an associative array with statistical information about them. The array is the last element of the object record array. The statistical array contains the following entries:
Number of object records with attribute PresentationHints set to Hidden.
Number of object records with attribute PresentationHints set to CollectionHead.
Number of object records with attribute PresentationHints set to FullCollectionHead.
Index in array of object records with attribute PresentationHints set to CollectionHead.
Index in array of object records with attribute PresentationHints set to FullCollectionHead.
Total: Number of object records.
This PECL extension is not bundled with PHP.
In order to use these functions you must compile PHP with Hyperwave support by using the --with-hyperwave[=DIR] configure option.
Windows users will enable php_hyperwave.dll inside of php.ini in order to use these functions. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
The Hyperwave extension is best used when PHP is compiled as an Apache module. In such a case the underlying Hyperwave server can be hidden from users almost completely if Apache uses its rewriting engine. The following instructions will explain this.
Since PHP with Hyperwave support built into Apache is intended to replace the native Hyperwave solution based on Wavemaster, we will assume that the Apache server will only serve as a Hyperwave web interface for these examples. This is not necessary but it simplifies the configuration. The concept is quite simple. First of all you need a PHP script which evaluates the $_ENV['PATH_INFO'] variable and treats its value as the name of a Hyperwave object. Let's call this script 'Hyperwave'. The URL http://your.hostname/Hyperwave/name_of_object would than return the Hyperwave object with the name 'name_of_object'. Depending on the type of the object the script has to react accordingly. If it is a collection, it will probably return a list of children. If it is a document it will return the mime type and the content. A slight improvement can be achieved if the Apache rewriting engine is used. From the users point of view it would be more straight forward if the URL http://your.hostname/name_of_object would return the object. The rewriting rule is quite easy:
Now every URL relates to an object in the Hyperwave server. This causes a simple to solve problem. There is no way to execute a different script, e.g. for searching, than the 'Hyperwave' script. This can be fixed with another rewriting rule like the following: This will reserve the directory /usr/local/apache/htdocs/hw for additional scripts and other files. Just make sure this rule is evaluated before the one above. There is just a little drawback: all Hyperwave objects whose name starts with 'hw/' will be shadowed. So, make sure you don't use such names. If you need more directories, e.g. for images just add more rules or place them all in one directory. Before you put those instructions, don't forget to turn on the rewriting engine with You will need scripts:to return the object itself
to allow searching
to identify yourself
to set your profile
one for each additional function like to show the object attributes, to show information about users, to show the status of the server, etc.
As an alternative to the Rewrite Engine, you can also consider using the Apache ErrorDocument directive, but be aware, that ErrorDocument redirected pages cannot receive POST data.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Hyperwave configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
hyperwave.allow_persistent | "0" | PHP_INI_SYSTEM | Available since PHP 4.3.2. |
hyperwave.default_port | "418" | PHP_INI_ALL |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
There are still some things to do:
The hw_InsertDocument has to be split into hw_insertobject() and hw_putdocument().
The names of several functions are not fixed, yet.
Most functions require the current connection as its first parameter. This leads to a lot of typing, which is quite often not necessary if there is just one open connection. A default connection will improve this.
Conversion form object record into object array needs to handle any multiple attribute.
(PHP 3 >= 3.0.4, PHP 4, PECL)
hw_Array2Objrec -- Convert attributes from object array to object recordConverts an object_array into an object record. Multiple attributes like 'Title' in different languages are treated properly.
See also hw_objrec2array().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Returns an array of object ids. Each id belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.
Returns an array of object records. Each object record belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.
Returns FALSE if connection is not a valid connection index, otherwise TRUE. Closes down the connection to a Hyperwave server with the given connection index.
Opens a connection to a Hyperwave server and returns a connection index on success, or FALSE if the connection could not be made. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple connections open at once. Keep in mind, that the password is not encrypted.
See also hw_pconnect().
(PHP 3 >= 3.0.3, PHP 4, PECL)
hw_connection_info -- Prints information about the connection to Hyperwave server
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Copies the objects with object ids as specified in the second parameter to the collection with the id destination id.
The value return is the number of copied objects.
See also hw_mv().
Deletes the object with the given object id in the second parameter. It will delete all instances of the object.
Returns TRUE if no error occurs otherwise FALSE.
See also hw_mv().
Returns an th object id of the document to which anchorID belongs.
Returns an th object record of the document to which anchorID belongs.
Returns the object record of the document.
For backward compatibility, hw_documentattributes() is also accepted. This is deprecated, however.
See also hw_document_bodytag(), and hw_document_size().
Returns the BODY tag of the document. If the document is an HTML document the BODY tag should be printed before the document.
See also hw_document_attributes(), and hw_document_size().
For backward compatibility, hw_documentbodytag() is also accepted. This is deprecated, however.
Returns the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record.
See also hw_document_attributes(), hw_document_size(), and hw_document_setcontent().
Sets or replaces the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record. If you provide this information in the content of the document too, the Hyperwave server will change the object record accordingly when the document is inserted. Probably not a very good idea. If this functions fails the document will retain its old content.
See also hw_document_attributes(), hw_document_size(), and hw_document_content().
Returns the size in bytes of the document.
See also hw_document_bodytag(), and hw_document_attributes().
For backward compatibility, hw_documentsize() is also accepted. This is deprecated, however.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Uploads the text document to the server. The object record of the document may not be modified while the document is edited. This function will only works for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.
See also hw_pipedocument(), hw_free_document(), hw_document_bodytag(), hw_document_size(), hw_output_document(), and hw_gettext().
Returns the last error number. If the return value is 0 no error has occurred. The error relates to the last command.
Returns a string containing the last error message or 'No Error'. If FALSE is returned, this function failed. The message relates to the last command.
Frees the memory occupied by the Hyperwave document.
Returns an array of object ids with anchors of the document with object ID objectID.
Returns an array of object records with anchors of the document with object ID objectID.
Returns the object record for the object with ID objectID. It will also lock the object, so other users cannot access it until it is unlocked.
See also hw_unlock(), and hw_getobject().
Returns an array of object ids. Each object ID belongs to a child collection of the collection with ID objectID. The function will not return child documents.
See also hw_children(), and hw_getchilddoccoll().
Returns an array of object records. Each object records belongs to a child collection of the collection with ID objectID. The function will not return child documents.
See also hw_childrenobj(), and hw_getchilddoccollobj().
Returns array of object ids for child documents of a collection.
See also hw_children(), and hw_getchildcoll().
(PHP 3 >= 3.0.3, PHP 4, PECL)
hw_GetChildDocCollObj -- Object records of child documents of collectionReturns an array of object records for child documents of a collection.
See also hw_childrenobj(), and hw_getchildcollobj().
Returns the object record for the object with ID objectID if the second parameter is an integer. If the second parameter is an array of integer the function will return an array of object records. In such a case the last parameter is also evaluated which is a query string.
The query string has the following syntax:
<expr> ::= "(" <expr> ")" |
"!" <expr> | /* NOT */
<expr> "||" <expr> | /* OR */
<expr> "&&" <expr> | /* AND */
<attribute> <operator> <value>
<attribute> ::= /* any attribute name (Title, Author, DocumentType ...) */
<operator> ::= "=" | /* equal */
"<" | /* less than (string compare) */
">" | /* greater than (string compare) */
"~" /* regular expression matching */
The query allows to further select certain objects from the list of given objects. Unlike the other query functions, this query may use not indexed attributes. How many object records are returned depends on the query and if access to the object is allowed.
See also hw_getandlock(), and hw_getobjectbyquery().
Searches for objects on the whole server and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.
The query will only work with indexed attributes.
See also hw_getobjectbyqueryobj().
Searches for objects in collection with ID objectID and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.
The query will only work with indexed attributes.
See also hw_getobjectbyquerycollobj().
Searches for objects in collection with ID objectID and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.
The query will only work with indexed attributes.
See also hw_getobjectbyquerycoll().
Searches for objects on the whole server and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.
The query will only work with indexed attributes.
See also hw_getobjectbyquery().
Returns an indexed array of object ids. Each object id belongs to a parent of the object with ID objectID.
Returns an indexed array of object records plus an associated array with statistical information about the object records. The associated array is the last entry of the returned array. Each object record belongs to a parent of the object with ID objectID.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Returns a remote document. Remote documents in Hyperwave notation are documents retrieved from an external source. Common remote documents are for example external web pages or queries in a database. In order to be able to access external sources through remote documents Hyperwave introduces the HGI (Hyperwave Gateway Interface) which is similar to the CGI. Currently, only ftp, http-servers and some databases can be accessed by the HGI. Calling hw_getremote() returns the document from the external source. If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.
See also hw_getremotechildren().
Returns the children of a remote document. Children of a remote document are remote documents itself. This makes sense if a database query has to be narrowed and is explained in Hyperwave Programmers' Guide. If the number of children is 1 the function will return the document itself formatted by the Hyperwave Gateway Interface (HGI). If the number of children is greater than 1 it will return an array of object record with each maybe the input value for another call to hw_getremotechildren(). Those object records are virtual and do not exist in the Hyperwave server, therefore they do not have a valid object ID. How exactly such an object record looks like is up to the HGI. If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.
See also hw_getremote().
Returns the object records of all anchors pointing to the object with ID objectID. The object can either be a document or an anchor of type destination.
See also hw_getanchors().
Returns the document with object ID objectID. If the document has anchors which can be inserted, they will be inserted already. The optional parameter rootID/prefix can be a string or an integer. If it is an integer it determines how links are inserted into the document. The default is 0 and will result in links that are constructed from the name of the link's destination object. This is useful for web applications. If a link points to an object with name 'internet_movie' the HTML link will be <A HREF="/internet_movie">. The actual location of the source and destination object in the document hierarchy is disregarded. You will have to set up your web browser, to rewrite that URL to for example '/my_script.php3/internet_movie'. 'my_script.php3' will have to evaluate $PATH_INFO and retrieve the document. All links will have the prefix '/my_script.php3/'. If you do not want this you can set the optional parameter rootID/prefix to any prefix which is used instead. Is this case it has to be a string.
If rootID/prefix is an integer and unequal to 0 the link is constructed from all the names starting at the object with the id rootID/prefix separated by a slash relative to the current object. If for example the above document 'internet_movie' is located at 'a-b-c-internet_movie' with '-' being the separator between hierarchy levels on the Hyperwave server and the source document is located at 'a-b-d-source' the resulting HTML link would be: <A HREF="../c/internet_movie">. This is useful if you want to download the whole server content onto disk and map the document hierarchy onto the file system.
This function will only work for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.
See also hw_pipedocument(), hw_free_document(), hw_document_bodytag(), hw_document_size(), and hw_output_document().
Identifies as user with username and password. Identification is only valid for the current session. I do not think this function will be needed very often. In most cases it will be easier to identify with the opening of the connection.
See also hw_connect().
Checks whether a set of objects (documents or collections) specified by the object_id_array is part of the collections listed in collection_id_array. When the fourth parameter return_collections is 0, the subset of object ids that is part of the collections (i.e., the documents or collections that are children of one or more collections of collection ids or their subcollections, recursively) is returned as an array. When the fourth parameter is 1, however, the set of collections that have one or more objects of this subset as children are returned as an array. This option allows a client to, e.g., highlight the part of the collection hierarchy that contains the matches of a previous query, in a graphical overview.
Returns information about the current connection. The returned string has the following format: <Serverstring>, <Host>, <Port>, <Username>, <Port of Client>, <Byte swapping>
Inserts a new collection with attributes as in object_array into collection with object ID objectID.
Inserts a new document with attributes as in object_record into collection with object ID parentID. This function inserts either an object record only or an object record and a pure ascii text in text if text is given. If you want to insert a general document of any kind use hw_insertdocument() instead.
See also hw_insertdocument(), and hw_inscoll().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Uploads a document into the collection with parent_id. The document has to be created before with hw_new_document(). Make sure that the object record of the new document contains at least the attributes: Type, DocumentType, Title and Name. Possibly you also want to set the MimeType. The functions returns the object id of the new document or FALSE.
See also hw_pipedocument().
Inserts an object into the server. The object can be any valid hyperwave object. See the HG-CSP documentation for a detailed information on how the parameters have to be.
Note: If you want to insert an Anchor, the attribute Position has always been set either to a start/end value or to 'invisible'. Invisible positions are needed if the annotation has no corresponding link in the annotation text.
See also hw_pipedocument(), hw_insertdocument(), hw_insdoc(), and hw_inscoll().
Maps a global object id on any hyperwave server, even those you did not connect to with hw_connect(), onto a virtual object id. This virtual object id can then be used as any other object id, e.g. to obtain the object record with hw_getobject(). The server id is the first part of the global object id (GOid) of the object which is actually the IP number as an integer.
Note: In order to use this function you will have to set the F_DISTRIBUTED flag, which can currently only be set at compile time in hg_comm.c. It is not set by default. Read the comment at the beginning of hg_comm.c
This command allows to remove, add, or modify individual attributes of an object record. The object is specified by the Object ID object_to_change. The first array remove is a list of attributes to remove. The second array add is a list of attributes to add. In order to modify an attribute one will have to remove the old one and add a new one. hw_modifyobject() will always remove the attributes before it adds attributes unless the value of the attribute to remove is not a string or array.
The last parameter determines if the modification is performed recursively. 1 means recursive modification. If some of the objects cannot be modified they will be skipped without notice. hw_error() may not indicate an error though some of the objects could not be modified.
The keys of both arrays are the attributes name. The value of each array element can either be an array, a string or anything else. If it is an array each attribute value is constructed by the key of each element plus a colon and the value of each element. If it is a string it is taken as the attribute value. An empty string will result in a complete removal of that attribute. If the value is neither a string nor an array but something else, e.g. an integer, no operation at all will be performed on the attribute. This is necessary if you want to add a completely new attribute not just a new value for an existing attribute. If the remove array contained an empty string for that attribute, the attribute would be tried to be removed which would fail since it doesn't exist. The following addition of a new value for that attribute would also fail. Setting the value for that attribute to e.g. 0 would not even try to remove it and the addition will work.
If you would like to change the attribute 'Name' with the current value 'books' into 'articles' you will have to create two arrays and call hw_modifyobject().
Nota: Multilingual attributes, e.g. 'Title', can be modified in two ways. Either by providing the attributes value in its native form 'language':'title' or by providing an array with elements for each language as described above. The above example would than be:
Nota: This will remove all attributes with the name 'Title' and adds a new 'Title' attribute. This comes in handy if you want to remove attributes recursively.
Nota: If you need to delete all attributes with a certain name you will have to pass an empty string as the attribute value.
Nota: Only the attributes 'Title', 'Description' and 'Keyword' will properly handle the language prefix. If those attributes don't carry a language prefix, the prefix 'xx' will be assigned.
Nota: The 'Name' attribute is somewhat special. In some cases it cannot be complete removed. You will get an error message 'Change of base attribute' (not clear when this happens). Therefore you will always have to add a new Name first and than remove the old one.
Nota: You may not surround this function by calls to hw_getandlock() and hw_unlock(). hw_modifyobject() does this internally.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Moves the objects with object ids as specified in the second parameter from the collection with id source_id to the collection with the id destination_id. If the destination id is 0 the objects will be unlinked from the source collection. If this is the last instance of that object it will be deleted. If you want to delete all instances at once, use hw_deleteobject().
The value returned is the number of moved objects.
See also hw_cp(), and hw_deleteobject().
Returns a new Hyperwave document with document data set to document_data and object record set to object_record. The length of the document_data has to passed in document_sizeThis function does not insert the document into the Hyperwave server.
See also hw_free_document(), hw_document_size(), hw_document_bodytag(), hw_output_document(), and hw_insertdocument().
(PHP 3 >= 3.0.3, PHP 4, PECL)
hw_objrec2array -- Convert attributes from object record to object arrayConverts an object_record into an object array. The keys of the resulting array are the attributes names. Multi-value attributes like 'Title' in different languages form its own array. The keys of this array are the left part to the colon of the attribute value. This left part must be two characters long. Other multi-value attributes without a prefix form an indexed array. If the optional parameter is missing the attributes 'Title', 'Description' and 'Keyword' are treated as language attributes and the attributes 'Group', 'Parent' and 'HtmlAttr' as non-prefixed multi-value attributes. By passing an array holding the type for each attribute you can alter this behaviour. The array is an associated array with the attribute name as its key and the value being one of HW_ATTR_LANG or HW_ATTR_NONE.
See also hw_array2objrec().
Prints the document without the BODY tag.
For backward compatibility, hw_outputdocument() is also accepted. This is deprecated, however.
Returns a connection index on success, or FALSE if the connection could not be made. Opens a persistent connection to a Hyperwave server. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple persistent connections open at once.
See also hw_connect().
Returns the Hyperwave document with object ID objectID. If the document has anchors which can be inserted, they will have been inserted already. The document will be transferred via a special data connection which does not block the control connection.
See also hw_gettext() for more on link insertion, hw_free_document(), hw_document_size(), hw_document_bodytag(), and hw_output_document().
Returns the object ID of the hyperroot collection. Currently this is always 0. The child collection of the hyperroot is the root collection of the connected server.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Unlocks a document, so other users regain access.
See also hw_getandlock().
Returns an array of users currently logged into the Hyperwave server. Each entry in this array is an array itself containing the elements id, name, system, onSinceDate, onSinceTime, TotalTime and self. 'self' is 1 if this entry belongs to the user who initiated the request.
Hyperwave has been developed at IICM in Graz. It started with the name Hyper-G and changed to Hyperwave when it was commercialised (in 1996).
Hyperwave is not free software. The current version, 5.5, is available at http://www.hyperwave.com/. A time limited version can be ordered for free (30 days).
See also the Hyperwave module.
Hyperwave is an information system similar to a database (HIS, Hyperwave Information Server). Its focus is the storage and management of documents. A document can be any possible piece of data that may as well be stored in file. Each document is accompanied by its object record. The object record contains meta data for the document. The meta data is a list of attributes which can be extended by the user. Certain attributes are always set by the Hyperwave server, other may be modified by the user.
Since 2001 there is a Hyperwave SDK available. It supports Java, JavaScript and C++. This PHP Extension is based on the C++ interface. In order to activate the hwapi support in PHP you will have to install the Hyperwave SDK first.
The integration with Apache and possible other servers is already described in the Hyperwave module which has been the first extension to connect a Hyperwave Server.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Hyperwave API configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
hwapi.allow_persistent | "0" | PHP_INI_SYSTEM |
The API provided by the HW_API extension is fully object oriented. It is very similar to the C++ interface of the Hyperwave SDK. It consist of the following classes.
HW_API
HW_API_Object
HW_API_Attribute
HW_API_Error
HW_API_Content
HW_API_Reason
Each class has certain method, whose names are identical to its counterparts in the Hyperwave SDK. Passing arguments to this function differs from all the other PHP extensions but is close to the C++ API of the HW SDK. Instead of passing several parameters they are all put into an associated array and passed as one parameter. The names of the keys are identical to those documented in the HW SDK. The common parameters are listed below. If other parameters are required they will be documented if needed.
objectIdentifier The name or id of an object, e.g. "rootcollection", "0x873A8768 0x00000002".
parentIdentifier The name or id of an object which is considered to be a parent.
object An instance of class HW_API_Object.
parameters An instance of class HW_API_Object.
version The version of an object.
mode An integer value determine the way an operation is executed.
attributeSelector Any array of strings, each containing a name of an attribute. This is used if you retrieve the object record and want to include certain attributes.
objectQuery A query to select certain object out of a list of objects. This is used to reduce the number of objects which was delivered by a function like hw_api->children() or hw_api->find().
Nota: Methods returning boolean can return TRUE, FALSE or HW_API_Error object.
Returns the name of the attribute.
See also hwapi_attribute_value().
(no version information, might be only in CVS)
hw_api_attribute->langdepvalue -- Returns value for a given languageReturns the value in the given language of the attribute.
See also hwapi_attribute_value().
(no version information, might be only in CVS)
hw_api_attribute->value -- Returns value of the attributeReturns the value of the attribute.
See also hwapi_attribute_key(), hwapi_attribute_values().
(no version information, might be only in CVS)
hw_api_attribute->values -- Returns all values of the attributeReturns all values of the attribute as an array of strings.
See also hwapi_attribute_value().
(no version information, might be only in CVS)
hw_api_attribute -- Creates instance of class hw_api_attributeCreates a new instance of hw_api_attribute with the given name and value.
This function checks in an object or a whole hierarchy of objects. The parameters array contains the required element 'objectIdentifier' and the optional element 'version', 'comment', 'mode' and 'objectQuery'. 'version' sets the version of the object. It consists of the major and minor version separated by a period. If the version is not set, the minor version is incremented. 'mode' can be one of the following values:
Checks in and commits the object. The object must be a document.
If the object to check in is a collection, all children will be checked in recursively if they are documents. Trying to check in a collection would result in an error.
Checks in an object even if it is not under version control.
Check if the new version is different from the last version. Unless this is the case the object will be checked in.
Keeps the time modified from the most recent object.
The object is not automatically committed on check-in.
See also hwapi_checkout().
This function checks out an object or a whole hierarchy of objects. The parameters array contains the required element 'objectIdentifier' and the optional element 'version', 'mode' and 'objectQuery'. 'mode' can be one of the following values:
Checks out an object. The object must be a document.
If the object to check out is a collection, all children will be checked out recursively if they are documents. Trying to check out a collection would result in an error.
See also hwapi_checkin().
Retrieves the children of a collection or the attributes of a document. The children can be further filtered by specifying an object query. The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.
The return value is an array of objects of type HW_API_Object or HW_API_Error.
See also hwapi_parents().
Reads len bytes from the content into the given buffer.
This function returns the content of a document as an object of type hw_api_content. The parameter array contains the required elements 'objectidentifier' and the optional element 'mode'. The mode can be one of the constants HW_API_CONTENT_ALLLINKS, HW_API_CONTENT_REACHABLELINKS or HW_API_CONTENT_PLAIN. HW_API_CONTENT_ALLLINKS means to insert all anchors even if the destination is not reachable. HW_API_CONTENT_REACHABLELINKS tells hw_api_content() to insert only reachable links and HW_API_CONTENT_PLAIN will lead to document without any links.
This function will make a physical copy including the content if it exists and returns the new object or an error object. The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. The optional parameter is 'attributeSelector'`
See also hwapi_move(), hwapi_link().
(no version information, might be only in CVS)
hw_api->dbstat -- Returns statistics about database server
See also hwapi_dcstat(), hwapi_hwstat(), hwapi_ftstat().
(no version information, might be only in CVS)
hw_api->dcstat -- Returns statistics about document cache server
See also hwapi_hwstat(), hwapi_dbstat(), hwapi_ftstat().
(no version information, might be only in CVS)
hw_api->dstanchors -- Returns a list of all destination anchorsRetrieves all destination anchors of an object. The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.
See also hwapi_srcanchors().
(no version information, might be only in CVS)
hw_api->dstofsrcanchor -- Returns destination of a source anchorRetrieves the destination object pointed by the specified source anchors. The destination object can either be a destination anchor or a whole document. The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.
See also hwapi_srcanchors(), hwapi_dstanchors(), hwapi_objectbyanchor().
Returns the number of error reasons.
See also hwapi_error_reason().
Returns the first error reason.
See also hwapi_error_count().
This functions searches for objects either by executing a key or/and full text query. The found objects can further be filtered by an optional object query. They are sorted by their importance. The second search operation is relatively slow and its result can be limited to a certain number of hits. This allows to perform an incremental search, each returning just a subset of all found documents, starting at a given index. The parameter array contains the 'keyquery' or/and 'fulltextquery' depending on who you would like to search. Optional parameters are 'objectquery', 'scope', 'languages' and 'attributeselector'. In case of an incremental search the optional parameters 'startIndex', numberOfObjectsToGet' and 'exactMatchUnit' can be passed.
(no version information, might be only in CVS)
hw_api->ftstat -- Returns statistics about fulltext server
See also hwapi_dcstat(), hwapi_dbstat(), hwapi_hwstat().
Opens a connection to the Hyperwave server on host hostname. The protocol used is HGCSP. If you do not pass a port number, 418 is used.
See also hwapi_hwtp().
(no version information, might be only in CVS)
hw_api->hwstat -- Returns statistics about Hyperwave server
See also hwapi_dcstat(), hwapi_dbstat(), hwapi_ftstat().
Logs into the Hyperwave Server. The parameter array must contain the elements 'username' and 'password'.
The return value will be an object of type HW_API_Error if identification failed or TRUE if it was successful.
(no version information, might be only in CVS)
hw_api->info -- Returns information about server configuration
See also hwapi_dcstat(), hwapi_dbstat(), hwapi_ftstat(), hwapi_hwstat().
Insert a new object. The object type can be user, group, document or anchor. Depending on the type other object attributes has to be set. The parameter array contains the required elements 'object' and 'content' (if the object is a document) and the optional parameters 'parameters', 'mode' and 'attributeSelector'. The 'object' must contain all attributes of the object. 'parameters' is an object as well holding further attributes like the destination (attribute key is 'Parent'). 'content' is the content of the document. 'mode' can be a combination of the following flags:
The object in inserted into the server.
See also hwapi_replace().
(no version information, might be only in CVS)
hw_api->insertanchor -- Inserts a new object of type anchorThis function is a shortcut for hwapi_insert(). It inserts an object of type anchor and sets some of the attributes required for an anchor. The parameter array contains the required elements 'object' and 'documentIdentifier' and the optional elements 'destinationIdentifier', 'parameter', 'hint' and 'attributeSelector'. The 'documentIdentifier' specifies the document where the anchor shall be inserted. The target of the anchor is set in 'destinationIdentifier' if it already exists. If the target does not exists the element 'hint' has to be set to the name of object which is supposed to be inserted later. Once it is inserted the anchor target is resolved automatically.
See also hwapi_insertdocument(), hwapi_insertcollection(), hwapi_insert().
(no version information, might be only in CVS)
hw_api->insertcollection -- Inserts a new object of type collectionThis function is a shortcut for hwapi_insert(). It inserts an object of type collection and sets some of the attributes required for a collection. The parameter array contains the required elements 'object' and 'parentIdentifier' and the optional elements 'parameter' and 'attributeSelector'. See hwapi_insert() for the meaning of each element.
See also hwapi_insertdocument(), hwapi_insertanchor(), hwapi_insert().
(no version information, might be only in CVS)
hw_api->insertdocument -- Inserts a new object of type documentThis function is a shortcut for hwapi_insert(). It inserts an object with content and sets some of the attributes required for a document. The parameter array contains the required elements 'object', 'parentIdentifier' and 'content' and the optional elements 'mode', 'parameter' and 'attributeSelector'. See hwapi_insert() for the meaning of each element.
See also hwapi_insert() hwapi_insertanchor(), hwapi_insertcollection().
Creates a link to an object. Accessing this link is like accessing the object to links points to. The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. 'destinationParentIdentifier' is the target collection.
The function returns TRUE on success or an error object.
See also hwapi_copy().
Locks an object for exclusive editing by the user calling this function. The object can be only unlocked by this user or the system user. The parameter array contains the required element 'objectIdentifier' and the optional parameters 'mode' and 'objectquery'. 'mode' determines how an object is locked. HW_API_LOCK_NORMAL means, an object is locked until it is unlocked. HW_API_LOCK_RECURSIVE is only valid for collection and locks all objects within the collection and possible subcollections. HW_API_LOCK_SESSION means, an object is locked only as long as the session is valid.
See also hwapi_unlock().
(no version information, might be only in CVS)
hw_api_content -- Create new instance of class hw_api_contentCreates a new content object from the string content. The mimetype is set to mimetype.
(no version information, might be only in CVS)
hw_api_object->attreditable -- Checks whether an attribute is editableAdds an attribute to the object. Returns TRUE on success and otherwise FALSE.
See also hwapi_object_remove().
(no version information, might be only in CVS)
hw_api_object -- Creates a new instance of class hw_api_objectRemoves the attribute with the given name. Returns TRUE on success and otherwise FALSE.
See also hwapi_object_insert().
Returns the value of the attribute with the given name or FALSE if an error occurred.
This function retrieves the attribute information of an object of any version. It will not return the document content. The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'version'.
The returned object is an instance of class HW_API_Object on success or HW_API_Error if an error occurred.
This simple example retrieves an object and checks for errors.
Esempio 1. Retrieve an object
|
See also hwapi_content().
(no version information, might be only in CVS)
hw_api->objectbyanchor -- Returns the object an anchor belongs toThis function retrieves an object the specified anchor belongs to. The parameter array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.
See also hwapi_dstofsrcanchor(), hwapi_srcanchors(), hwapi_dstanchors().
Retrieves the parents of an object. The parents can be further filtered by specifying an object query. The parameter array contains the required elements 'objectidentifier' and the optional elements 'attributeselector' and 'objectquery'.
The return value is an array of objects of type HW_API_Object or HW_API_Error.
See also hwapi_children().
(no version information, might be only in CVS)
hw_api_reason->description -- Returns description of reasonRemoves an object from the specified parent. Collections will be removed recursively. You can pass an optional object query to remove only those objects which match the query. An object will be deleted physically if it is the last instance. The parameter array contains the required elements 'objectidentifier' and 'parentidentifier'. If you want to remove a user or group 'parentidentifier' can be skipped. The optional parameter 'mode' determines how the deletion is performed. In normal mode the object will not be removed physically until all instances are removed. In physical mode all instances of the object will be deleted immediately. In removelinks mode all references to and from the objects will be deleted as well. In nonrecursive the deletion is not performed recursive. Removing a collection which is not empty will cause an error.
See also hwapi_move().
Replaces the attributes and the content of an object The parameter array contains the required elements 'objectIdentifier' and 'object' and the optional parameters 'content', 'parameters', 'mode' and 'attributeSelector'. 'objectIdentifier' contains the object to be replaced. 'object' contains the new object. 'content' contains the new content. 'parameters' contain extra information for HTML documents. HTML_Language is the letter abbreviation of the language of the title. HTML_Base sets the base attribute of the HTML document. 'mode' can be a combination of the following flags:
The object on the server is replace with the object passed.
See also hwapi_insert().
(no version information, might be only in CVS)
hw_api->setcommittedversion -- Commits version other than last versionCommits a version of a document. The committed version is the one which is visible to users with read access. By default the last version is the committed version.
See also hwapi_checkin(), hwapi_checkout(), hwapi_revert().
(no version information, might be only in CVS)
hw_api->srcanchors -- Returns a list of all source anchorsRetrieves all source anchors of an object. The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.
See also hwapi_dstanchors().
(no version information, might be only in CVS)
hw_api->srcsofdst -- Returns source of a destination objectRetrieves all the source anchors pointing to the specified destination. The destination object can either be a destination anchor or a whole document. The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector' and 'objectQuery'. The function returns an array of objects or an error.
See also hwapi_dstofsrcanchor().
Unlocks a locked object. Only the user who has locked the object and the system user may unlock an object. The parameter array contains the required element 'objectIdentifier' and the optional parameters 'mode' and 'objectquery'. The meaning of 'mode' is the same as in function hwapi_lock().
Returns TRUE on success or an object of class HW_API_Error.
See also hwapi_lock().
These functions enable you to access IBM DB2 Universal Database, IBM Cloudscape, and Apache Derby databases using the DB2 Call Level Interface (DB2 CLI).
To connect to IBM DB2 Universal Database for Linux, UNIX, and Windows, or IBM Cloudscape, or Apache Derby, you must install an IBM DB2 Universal Database client on the same computer on which you are running PHP. The extension has been developed and tested with DB2 Version 8.2.
To connect to IBM DB2 Universal Database for z/OS or iSeries, you also require IBM DB2 Connect or the equivalent DRDA gateway software.
The user invoking the PHP executable or SAPI must specify the DB2 instance before accessing these functions. You can set the name of the DB2 instance in php.ini using the ibm_db2.instance_name configuration option, or you can source the DB2 instance profile before invoking the PHP executable.
If you created a DB2 instance named db2inst1 in /home/db2inst1/, for example, you can add the following line to php.ini:
ibm_db2.instance_name=db2inst1 |
bash$ source /home/db2inst1/sqllib/db2profile |
To build the ibm_db2 extension, the DB2 application development header files and libraries must be installed on your system. DB2 does not install these by default, so you may have to return to your DB2 installer and add this option. The header files are included with the DB2 Application Development Client freely available for download from the IBM DB2 Universal Database support site.
If you add the DB2 application development header files and libraries to a Linux or Unix operating system on which DB2 was already installed, you must issue the command db2iupdt -e to update the symbolic links to the header files and libraries in your DB2 instances.
ibm_db2 is a PECL extension, so follow the instructions in Capitolo 7 to install the ibm_db2 extension for PHP. Issue the configure command to point to the location of your DB2 header files and libraries as follows:
bash$ ./configure --with-IBM_DB2=/path/to/DB2 |
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. ibm_db2 Opioni di configurazione
Nome | Default | Modificabile | Changelog |
---|---|---|---|
ibm_db2.binmode | "1" | PHP_INI_ALL | |
ibm_db2.instance_name | NULL | PHP_INI_SYSTEM |
Breve descrizione dei parametri di configurazione.
This option controls the mode used for converting to and from binary data in the PHP application.
1 (DB2_BINARY)
2 (DB2_CONVERT)
3 (DB2_PASSTHRU)
On Linux and UNIX operating systems, this option defines the name of the instance to use for cataloged database connections. If this option is set, its value overrides the DB2INSTANCE environment variable setting.
This option is ignored on Windows operating systems.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Specifies that binary data shall be returned as is. This is the default mode.
Specifies that binary data shall be converted to a hexadecimal encoding and returned as an ASCII string.
Specifies that binary data shall be converted to a NULL value.
Specifies a scrollable cursor for a statement resource. This mode enables random access to rows in a result set, but currently is supported only by IBM DB2 Universal Database.
Specifies a forward-only cursor for a statement resource. This is the default cursor type and is supported on all database servers.
Specifies the PHP variable should be bound as an IN parameter for a stored procedure.
Specifies the PHP variable should be bound as an OUT parameter for a stored procedure.
Specifies the PHP variable should be bound as an INOUT parameter for a stored procedure.
Specifies that the column should be bound directly to a file for input or output.
Specifies that autocommit should be turned on.
Specifies that autocommit should be turned off.
Specifies that the variable should be bound as a DOUBLE, FLOAT, or REAL data type.
Specifies that the variable should be bound as a SMALLINT, INTEGER, or BIGINT data type.
Specifies that the variable should be bound as a CHAR or VARCHAR data type.
The ibm_db2 extension returns connection resources, statement resources, and result set resources.
Sets or gets the AUTOCOMMIT behavior of the specified connection resource.
A valid database connection resource variable as returned from db2_connect() or db2_pconnect().
One of the following constants:
Turns AUTOCOMMIT off.
Turns AUTOCOMMIT on.
When db2_autocommit() receives only the connection parameter, it returns the current state of AUTOCOMMIT for the requested connection as an integer value. A value of 0 indicates that AUTOCOMMIT is off, while a value of 1 indicates that AUTOCOMMIT is on.
When db2_autocommit() receives both the connection parameter and autocommit parameter, it attempts to set the AUTOCOMMIT state of the requested connection to the corresponding state. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. Retrieving the AUTOCOMMIT value for a connection In the following example, a connection which has been created with AUTOCOMMIT turned off is tested with the db2_autocommit() function.
Il precedente esempio visualizzerà:
|
Esempio 2. Setting the AUTOCOMMIT value for a connection In the following example, a connection which was initially created with AUTOCOMMIT turned off has its behavior changed to turn AUTOCOMMIT on.
Il precedente esempio visualizzerà:
|
Binds a PHP variable to an SQL statement parameter in a statement resource returned by db2_prepare(). This function gives you more control over the parameter type, data type, precision, and scale for the parameter than simply passing the variable as part of the optional input array to db2_execute().
A prepared statement returned from db2_prepare().
Specifies the 1-indexed position of the parameter in the prepared statement.
A string specifying the name of the PHP variable to bind to the parameter specified by parameter-number.
A constant specifying whether the PHP variable should be bound to the SQL parameter as an input parameter (DB2_PARAM_IN), an output parameter (DB2_PARAM_OUT), or as a parameter that accepts input and returns output (DB2_PARAM_INOUT).
A constant specifying the SQL data type that the PHP variable should be bound as: one of DB2_BINARY, DB2_CHAR, DB2_DOUBLE, or DB2_LONG .
Specifies the precision with which the variable should be bound to the database.
Specifies the scale with which the variable should be bound to the database.
Esempio 1. Binding PHP variables to a prepared statement The SQL statement in the following example uses two input parameters in the WHERE clause. We call db2_bind_param() to bind two PHP variables to the corresponding SQL parameters. Notice that the PHP variables do not have to be declared or assigned before the call to db2_bind_param(); in the example, $lower_limit is assigned a value before the call to db2_bind_param(), but $upper_limit is assigned a value after the call to db2_bind_param(). The variables must be bound and, for parameters that accept input, must have any value assigned, before calling db2_execute().
Il precedente esempio visualizzerà:
|
Esempio 2. Calling stored procedures with IN and OUT parameters The stored procedure match_animal in the following example accepts three different parameters:
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
db2_client_info -- Returns an object with properties that describe the DB2 database clientThis function returns an object with read-only properties that return information about the DB2 database client. The following table lists the DB2 client properties:
Tabella 1. DB2 client properties
Property name | Return type | Description |
---|---|---|
APPL_CODEPAGE | int | The application code page. |
CONN_CODEPAGE | int | The code page for the current connection. |
DATA_SOURCE_NAME | string | The data source name (DSN) used to create the current connection to the database. |
DRIVER_NAME | string | The name of the library that implements the DB2 Call Level Interface (CLI) specification. |
DRIVER_ODBC_VER | string | The version of ODBC that the DB2 client supports. This returns a string "MM.mm" where MM is the major version and mm is the minor version. The DB2 client always returns "03.51". |
DRIVER_VER | string | The version of the client, in the form of a string "MM.mm.uuuu" where MM is the major version, mm is the minor version, and uuuu is the update. For example, "08.02.0001" represents major version 8, minor version 2, update 1. |
ODBC_SQL_CONFORMANCE | string | The level of ODBC SQL grammar supported by the client:
|
ODBC_VER | string | The version of ODBC that the ODBC driver manager supports. This returns a string "MM.mm.rrrr" where MM is the major version, mm is the minor version, and rrrr is the release. The DB2 client always returns "03.01.0000". |
Esempio 1. A db2_client_info() example To retrieve information about the client, you must pass a valid database connection resource to db2_client_info().
Il precedente esempio visualizzerà:
|
This function closes a DB2 client connection created with db2_connect() and returns the corresponding resources to the database server.
If you attempt to close a persistent DB2 client connection created with db2_pconnect(), the close request is ignored and the persistent DB2 client connection remains available for the next caller.
Esempio 1. Closing a connection The following example demonstrates a successful attempt to close a connection to an IBM DB2, Cloudscape, or Apache Derby database.
Il precedente esempio visualizzerà:
|
(PECL)
db2_column_privileges -- Returns a result set listing the columns and associated privileges for a tableReturns a result set listing the columns and associated privileges for a table.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema which contains the tables. To match all schemas, pass NULL or an empty string.
The name of the table or view. To match all tables in the database, pass NULL or an empty string.
The name of the column. To match all columns in the table, pass NULL or an empty string.
Returns a statement resource with a result set containing rows describing the column privileges for columns matching the specified parameters. The rows are composed of the following columns:
Column name | Description |
---|---|
TABLE_CAT | Name of the catalog. The value is NULL if this table does not have catalogs. |
TABLE_SCHEM | Name of the schema. |
TABLE_NAME | Name of the table or view. |
COLUMN_NAME | Name of the column. |
GRANTOR | Authorization ID of the user who granted the privilege. |
GRANTEE | Authorization ID of the user to whom the privilege was granted. |
PRIVILEGE | The privilege for the column. |
IS_GRANTABLE | Whether the GRANTEE is permitted to grant this privilege to other users. |
db2_columns() |
db2_foreign_keys() |
db2_primary_keys() |
db2_procedure_columns() |
db2_procedures() |
db2_special_columns() |
db2_statistics() |
db2_table_privileges() |
db2_tables() |
Returns a result set listing the columns and associated metadata for a table.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema which contains the tables. To match all schemas, pass '%'.
The name of the table or view. To match all tables in the database, pass NULL or an empty string.
The name of the column. To match all columns in the table, pass NULL or an empty string.
Returns a statement resource with a result set containing rows describing the columns matching the specified parameters. The rows are composed of the following columns:
Column name | Description |
---|---|
TABLE_CAT | Name of the catalog. The value is NULL if this table does not have catalogs. |
TABLE_SCHEM | Name of the schema. |
TABLE_NAME | Name of the table or view. |
COLUMN_NAME | Name of the column. |
DATA_TYPE | The SQL data type for the column represented as an integer value. |
TYPE_NAME | A string representing the data type for the column. |
COLUMN_SIZE | An integer value representing the size of the column. |
BUFFER_LENGTH | Maximum number of bytes necessary to store data from this column. |
DECIMAL_DIGITS | The scale of the column, or NULL where scale is not applicable. |
NUM_PREC_RADIX | An integer value of either 10 (representing an exact numeric data type), 2 (representing an approximate numeric data type), or NULL (representing a data type for which radix is not applicable). |
NULLABLE | An integer value representing whether the column is nullable or not. |
REMARKS | Description of the column. |
COLUMN_DEF | Default value for the column. |
SQL_DATA_TYPE | An integer value representing the size of the column. |
SQL_DATETIME_SUB | Returns an integer value representing a datetime subtype code, or NULL for SQL data types to which this does not apply. |
CHAR_OCTET_LENGTH | Maximum length in octets for a character data type column, which matches COLUMN_SIZE for single-byte character set data, or NULL for non-character data types. |
ORDINAL_POSITION | The 1-indexed position of the column in the table. |
IS_NULLABLE | A string value where 'YES' means that the column is nullable and 'NO' means that the column is not nullable. |
db2_column_privileges() |
db2_foreign_keys() |
db2_primary_keys() |
db2_procedure_columns() |
db2_procedures() |
db2_special_columns() |
db2_statistics() |
db2_table_privileges() |
db2_tables() |
Commits an in-progress transaction on the specified connection resource and begins a new transaction. PHP applications normally default to AUTOCOMMIT mode, so db2_commit() is not necessary unless AUTOCOMMIT has been turned off for the connection resource.
Nota: If the specified connection resource is a persistent connection, all transactions in progress for all applications using that persistent connection will be committed. For this reason, persistent connections are not recommended for use in applications that require transactions.
A valid database connection resource variable as returned from db2_connect() or db2_pconnect().
(PECL)
db2_conn_error -- Returns a string containing the SQLSTATE returned by the last connection attemptdb2_conn_error() returns an SQLSTATE value representing the reason the last attempt to connect to a database failed. As db2_connect() returns FALSE in the event of a failed connection attempt, you do not pass any parameters to db2_conn_error() to retrieve the SQLSTATE value.
If, however, the connection was successful but becomes invalid over time, you can pass the connection parameter to retrieve the SQLSTATE value for a specific connection.
To learn what the SQLSTATE value means, you can issue the following command at a DB2 Command Line Processor prompt: db2 '? sqlstate-value'. You can also call db2_conn_errormsg() to retrieve an explicit error message and the associated SQLCODE value.
A connection resource associated with a connection that initially succeeded, but which over time became invalid.
Returns the SQLSTATE value resulting from a failed connection attempt. Returns an empty string if there is no error associated with the last connection attempt.
Esempio 1. Retrieving an SQLSTATE value for a failed connection attempt The following example demonstrates how to return an SQLSTATE value after deliberately passing invalid parameters to db2_connect().
Il precedente esempio visualizzerà:
|
db2_conn_errormsg() returns an error message and SQLCODE value representing the reason the last database connection attempt failed. As db2_connect() returns FALSE in the event of a failed connection attempt, do not pass any parameters to db2_conn_errormsg() to retrieve the associated error message and SQLCODE value.
If, however, the connection was successful but becomes invalid over time, you can pass the connection parameter to retrieve the associated error message and SQLCODE value for a specific connection.
A connection resource associated with a connection that initially succeeded, but which over time became invalid.
Returns a string containing the error message and SQLCODE value resulting from a failed connection attempt. If there is no error associated with the last connection attempt, db2_conn_errormsg() returns an empty string.
Esempio 1. Retrieving the error message returned by a failed connection attempt The following example demonstrates how to return an error message and SQLCODE value after deliberately passing invalid parameters to db2_connect().
Il precedente esempio visualizzerà:
|
Creates a new connection to an IBM DB2 Universal Database, IBM Cloudscape, or Apache Derby database.
For a cataloged connection to a database, database represents the database alias in the DB2 client catalog.
For an uncataloged connection to a database, database represents a complete connection string in the following format: DRIVER={IBM DB2 ODBC DRIVER};DATABASE=database;HOSTNAME=hostname;PORT=port;PROTOCOL=TCPIP;UID=username;PWD=password; where the parameters represent the following values:
The name of the database.
The hostname or IP address of the database server.
The TCP/IP port on which the database is listening for requests.
The username with which you are connecting to the database.
The password with which you are connecting to the database.
The username with which you are connecting to the database.
For uncataloged connections, you must pass a NULL value or empty string.
The password with which you are connecting to the database.
For uncataloged connections, you must pass a NULL value or empty string.
An associative array of connection options that affect the behavior of the connection, where valid array keys include:
Passing the DB2_AUTOCOMMIT_ON value turns autocommit on for this connection handle.
Passing the DB2_AUTOCOMMIT_OFF value turns autocommit off for this connection handle.
Returns a connection handle resource if the connection attempt is successful. If the connection attempt fails, db2_connect() returns FALSE.
Esempio 1. Creating a cataloged connection Cataloged connections require you to have previously cataloged the target database through the DB2 Command Line Processor (CLP) or DB2 Configuration Assistant.
Il precedente esempio visualizzerà:
|
Esempio 2. Creating an uncataloged connection An uncataloged connection enables you to dynamically connect to a database.
Il precedente esempio visualizzerà:
|
Esempio 3. Creating a connection with autocommit off by default Passing an array of options to db2_connect() enables you to modify the default behavior of the connection handle.
Il precedente esempio visualizzerà:
|
Returns the cursor type used by a statement resource. Use this to determine if you are working with a forward-only cursor or scrollable cursor.
Returns either DB2_FORWARD_ONLY if the statement resource uses a forward-only cursor or DB2_SCROLLABLE if the statement resource uses a scrollable cursor.
Prepares and executes an SQL statement.
If you plan to interpolate PHP variables into the SQL statement, understand that this is one of the more common security exposures. Consider calling db2_prepare() to prepare an SQL statement with parameter markers for input values. Then you can call db2_execute() to pass in the input values and avoid SQL injection attacks.
If you plan to repeatedly issue the same SQL statement with different parameters, consider calling db2_prepare() and db2_execute() to enable the database server to reuse its access plan and increase the efficiency of your database access.
A valid database connection resource variable as returned from db2_connect() or db2_pconnect().
An SQL statement. The statement cannot contain any parameter markers.
An associative array containing statement options. You can use this parameter to request a scrollable cursor on database servers that support this functionality.
Passing the DB2_FORWARD_ONLY value requests a forward-only cursor for this SQL statement. This is the default type of cursor, and it is supported by all database servers. It is also much faster than a scrollable cursor.
Passing the DB2_SCROLLABLE value requests a scrollable cursor for this SQL statement. This type of cursor enables you to fetch rows non-sequentially from the database server. However, it is only supported by DB2 servers, and is much slower than forward-only cursors.
Returns a statement resource if the SQL statement was issued successfully, or FALSE if the database failed to execute the SQL statement.
Esempio 1. Creating a table with db2_exec() The following example uses db2_exec() to issue a set of DDL statements in the process of creating a table.
Il precedente esempio visualizzerà:
|
Esempio 2. Executing a SELECT statement with a scrollable cursor The following example demonstrates how to request a scrollable cursor for an SQL statement issued by db2_exec().
Il precedente esempio visualizzerà:
|
db2_execute() executes an SQL statement that was prepared by db2_prepare().
If the SQL statement returns a result set, for example, a SELECT statement or a CALL to a stored procedure that returns one or more result sets, you can retrieve a row as an array from the stmt resource using db2_fetch_assoc(), db2_fetch_both(), or db2_fetch_array(). Alternatively, you can use db2_fetch_row() to move the result set pointer to the next row and fetch a column at a time from that row with db2_result().
Refer to db2_prepare() for a brief discussion of the advantages of using db2_prepare() and db2_execute() rather than db2_exec().
A prepared statement returned from db2_prepare().
An array of input parameters matching any parameter markers contained in the prepared statement.
Esempio 1. Preparing and executing an SQL statement with parameter markers The following example prepares an INSERT statement that accepts four parameter markers, then iterates over an array of arrays containing the input values to be passed to db2_execute().
Il precedente esempio visualizzerà:
|
Esempio 2. Calling a stored procedure with an OUT parameter The following example prepares a CALL statement that accepts one parameter marker representing an OUT parameter, binds the PHP variable $my_pets to the parameter using db2_bind_param(), then issues db2_execute() to execute the CALL statement. After the CALL to the stored procedure has been made, the value of $num_pets changes to reflect the value returned by the stored procedure for that OUT parameter.
Il precedente esempio visualizzerà:
|
db2_exec() |
db2_fetch_array() |
db2_fetch_assoc() |
db2_fetch_both() |
db2_fetch_row() |
db2_prepare() |
db2_result() |
(PECL)
db2_fetch_array -- Returns an array, indexed by column position, representing a row in a result setReturns an array, indexed by column position, representing a row in a result set. The columns are 0-indexed.
A valid stmt resource containing a result set.
Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.
Returns a 0-indexed array with column values indexed by the column position representing the next or requested row in the result set. Returns FALSE if there are no rows left in the result set, or if the row requested by row_number does not exist in the result set.
Esempio 1. Iterating through a forward-only cursor If you call db2_fetch_array() without a specific row number, it automatically retrieves the next row in the result set.
Il precedente esempio visualizzerà:
|
Esempio 2. Retrieving specific rows with db2_fetch_assoc() from a scrollable cursor If your result set uses a scrollable cursor, you can call db2_fetch_assoc() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.
Il precedente esempio visualizzerà:
|
(PECL)
db2_fetch_assoc -- Returns an array, indexed by column name, representing a row in a result setReturns an array, indexed by column name, representing a row in a result set.
A valid stmt resource containing a result set.
Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.
Returns an associative array with column values indexed by the column name representing the next or requested row in the result set. Returns FALSE if there are no rows left in the result set, or if the row requested by row_number does not exist in the result set.
Esempio 1. Iterating through a forward-only cursor If you call db2_fetch_assoc() without a specific row number, it automatically retrieves the next row in the result set.
Il precedente esempio visualizzerà:
|
Esempio 2. Retrieving specific rows with db2_fetch_assoc() from a scrollable cursor If your result set uses a scrollable cursor, you can call db2_fetch_assoc() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.
Il precedente esempio visualizzerà:
|
(PECL)
db2_fetch_both -- Returns an array, indexed by both column name and position, representing a row in a result setReturns an array, indexed by both column name and position, representing a row in a result set. Note that the row returned by db2_fetch_both() requires more memory than the single-indexed arrays returned by db2_fetch_assoc() or db2_fetch_array().
A valid stmt resource containing a result set.
Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.
Returns an associative array with column values indexed by both the column name and 0-indexed column number. The array represents the next or requested row in the result set. Returns FALSE if there are no rows left in the result set, or if the row requested by row_number does not exist in the result set.
Esempio 1. Iterating through a forward-only cursor If you call db2_fetch_both() without a specific row number, it automatically retrieves the next row in the result set. The following example accesses columns in the returned array by both column name and by numeric index.
Il precedente esempio visualizzerà:
|
Esempio 2. Retrieving specific rows with db2_fetch_both() from a scrollable cursor If your result set uses a scrollable cursor, you can call db2_fetch_both() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.
Il precedente esempio visualizzerà:
|
Returns an object in which each property represents a column returned in the row fetched from a result set.
A valid stmt resource containing a result set.
Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.
Returns an object representing a single row in the result set. The properties of the object map to the names of the columns in the result set.
The IBM DB2, Cloudscape, and Apache Derby database servers typically fold column names to upper-case, so the object properties will reflect that case.
If your SELECT statement calls a scalar function to modify the value of a column, the database servers return the column number as the name of the column in the result set. If you prefer a more descriptive column name and object property, you can use the AS clause to assign a name to the column in the result set.
Returns FALSE if no row was retrieved.
Esempio 1. A db2_fetch_object() example The following example issues a SELECT statement with a scalar function, RTRIM, that removes whitespace from the end of the column. Rather than creating an object with the properties "BREED" and "2", we use the AS clause in the SELECT statement to assign the name "name" to the modified column. The database server folds the column names to upper-case, resulting in an object with the properties "BREED" and "NAME".
Il precedente esempio visualizzerà:
|
Use db2_fetch_row() to iterate through a result set, or to point to a specific row in a result set if you requested a scrollable cursor.
To retrieve individual fields from the result set, call the db2_result() function.
Rather than calling db2_fetch_row() and db2_result(), most applications will call one of db2_fetch_assoc(), db2_fetch_both(), or db2_fetch_array() to advance the result set pointer and return a complete row as an array.
A valid stmt resource.
With scrollable cursors, you can request a specific row number in the result set. Row numbering is 1-indexed.
Returns TRUE if the requested row exists in the result set. Returns FALSE if the requested row does not exist in the result set.
Esempio 1. Iterating through a result set The following example demonstrates how to iterate through a result set with db2_fetch_row() and retrieve columns from the result set with db2_result().
Il precedente esempio visualizzerà:
|
Returns the maximum number of bytes required to display a column in a result set.
Specifies a statement resource containing a result set.
Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.
Returns an integer value with the maximum number of bytes required to display the specified column. If the column does not exist in the result set, db2_field_display_size() returns FALSE.
db2_field_name() |
db2_field_num() |
db2_field_precision() |
db2_field_scale() |
db2_field_type() |
db2_field_width() |
Returns the name of the specified column in the result set.
Specifies a statement resource containing a result set.
Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.
Returns a string containing the name of the specified column. If the specified column does not exist in the result set, db2_field_name() returns FALSE.
db2_field_display_size() |
db2_field_num() |
db2_field_precision() |
db2_field_scale() |
db2_field_type() |
db2_field_width() |
Returns the position of the named column in a result set.
Specifies a statement resource containing a result set.
Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.
Returns an integer containing the 0-indexed position of the named column in the result set. If the specified column does not exist in the result set, db2_field_num() returns FALSE.
db2_field_display_size() |
db2_field_name() |
db2_field_precision() |
db2_field_scale() |
db2_field_type() |
db2_field_width() |
Returns the precision of the indicated column in a result set.
Specifies a statement resource containing a result set.
Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.
Returns an integer containing the precision of the specified column. If the specified column does not exist in the result set, db2_field_precision() returns FALSE.
db2_field_display_size() |
db2_field_name() |
db2_field_num() |
db2_field_scale() |
db2_field_type() |
db2_field_width() |
Returns the scale of the indicated column in a result set.
Specifies a statement resource containing a result set.
Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.
Returns an integer containing the scale of the specified column. If the specified column does not exist in the result set, db2_field_scale() returns FALSE.
db2_field_display_size() |
db2_field_name() |
db2_field_num() |
db2_field_precision() |
db2_field_type() |
db2_field_width() |
Returns the data type of the indicated column in a result set.
Specifies a statement resource containing a result set.
Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.
Returns a string containing the defined data type of the specified column. If the specified column does not exist in the result set, db2_field_type() returns FALSE.
db2_field_display_size() |
db2_field_name() |
db2_field_num() |
db2_field_precision() |
db2_field_scale() |
db2_field_width() |
(PECL)
db2_field_width -- Returns the width of the current value of the indicated column in a result setReturns the width of the current value of the indicated column in a result set. This is the maximum width of the column for a fixed-length data type, or the actual width of the column for a variable-length data type.
Specifies a statement resource containing a result set.
Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.
Returns an integer containing the width of the specified character or binary data type column in a result set. If the specified column does not exist in the result set, db2_field_width() returns FALSE.
db2_field_display_size() |
db2_field_name() |
db2_field_num() |
db2_field_precision() |
db2_field_scale() |
db2_field_type() |
Returns a result set listing the foreign keys for a table.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema which contains the tables. If schema is NULL, db2_foreign_keys() matches the schema for the current connection.
The name of the table.
Returns a statement resource with a result set containing rows describing the foreign keys for the specified table. The result set is composed of the following columns:
Column name | Description |
---|---|
PKTABLE_CAT | Name of the catalog for the table containing the primary key. The value is NULL if this table does not have catalogs. |
PKTABLE_SCHEM | Name of the schema for the table containing the primary key. |
PKTABLE_NAME | Name of the table containing the primary key. |
PKCOLUMN_NAME | Name of the column containing the primary key. |
FKTABLE_CAT | Name of the catalog for the table containing the foreign key. The value is NULL if this table does not have catalogs. |
FKTABLE_SCHEM | Name of the schema for the table containing the foreign key. |
FKTABLE_NAME | Name of the table containing the foreign key. |
FKCOLUMN_NAME | Name of the column containing the foreign key. |
KEY_SEQ | 1-indexed position of the column in the key. |
UPDATE_RULE | Integer value representing the action applied to the foreign key when the SQL operation is UPDATE. |
DELETE_RULE | Integer value representing the action applied to the foreign key when the SQL operation is DELETE. |
FK_NAME | The name of the foreign key. |
PK_NAME | The name of the primary key. |
DEFERRABILITY | An integer value representing whether the foreign key deferrability is SQL_INITIALLY_DEFERRED, SQL_INITIALLY_IMMEDIATE, or SQL_NOT_DEFERRABLE. |
db2_column_privileges() |
db2_columns() |
db2_primary_keys() |
db2_procedure_columns() |
db2_procedures() |
db2_special_columns() |
db2_statistics() |
db2_table_privileges() |
db2_tables() |
Frees the system and database resources that are associated with a result set. These resources are freed implicitly when a script finishes, but you can call db2_free_result() to explicitly free the result set resources before the end of the script.
Frees the system and database resources that are associated with a statement resource. These resources are freed implicitly when a script finishes, but you can call db2_free_stmt() to explicitly free the statement resources before the end of the script.
A stored procedure can return zero or more result sets. While you handle the first result set in exactly the same way you would handle the results returned by a simple SELECT statement, to fetch the second and subsequent result sets from a stored procedure you must call the db2_next_result() function and return the result to a uniquely named PHP variable.
Returns a new statement resource containing the next result set if the stored procedure returned another result set. Returns FALSE if the stored procedure did not return another result set.
Esempio 1. Calling a stored procedure that returns multiple result sets In the following example, we call a stored procedure that returns three result sets. The first result set is fetched directly from the same statement resource on which we invoked the CALL statement, while the second and third result sets are fetched from statement resources returned from our calls to the db2_next_result() function.
Il precedente esempio visualizzerà:
|
Returns the number of fields contained in a result set. This is most useful for handling the result sets returned by dynamically generated queries, or for result sets returned by stored procedures, where your application cannot otherwise know how to retrieve and use the results.
Returns an integer value representing the number of fields in the result set associated with the specified statement resource. Returns FALSE if the statement resource is not a valid input value.
Esempio 1. Retrieving the number of fields in a result set The following example demonstrates how to retrieve the number of fields returned in a result set.
Il precedente esempio visualizzerà:
|
db2_execute() |
db2_field_display_size() |
db2_field_name() |
db2_field_num() |
db2_field_precision() |
db2_field_scale() |
db2_field_type() |
db2_field_width() |
Returns the number of rows deleted, inserted, or updated by an SQL statement.
To determine the number of rows that will be returned by a SELECT statement, issue SELECT COUNT(*) with the same predicates as your intended SELECT statement and retrieve the value.
If your application logic checks the number of rows returned by a SELECT statement and branches if the number of rows is 0, consider modifying your application to attempt to return the first row with one of db2_fetch_assoc(), db2_fetch_both(), db2_fetch_array(), or db2_fetch_row(), and branch if the fetch function returns FALSE.
Nota: If you issue a SELECT statement using a scrollable cursor, db2_num_rows() returns the number of rows returned by the SELECT statement. However, the overhead associated with scrollable cursors significantly degrades the performance of your application, so if this is the only reason you are considering using scrollable cursors, you should use a forward-only cursor and either call SELECT COUNT(*) or rely on the boolean return value of the fetch functions to achieve the equivalent functionality with much better performance.
Returns the number of rows affected by the last SQL statement issued by the specified statement handle.
Returns a persistent connection to an IBM DB2 Universal Database, IBM Cloudscape, or Apache Derby database. For more information on persistent connections, refer to Capitolo 41.
Calling db2_close() on a persistent connection always returns TRUE, but the underlying DB2 client connection remains open and waiting to serve the next matching db2_pconnect() request.
Note that you are strongly urged to only use persistent connections on connections with autocommit turned on. If you attempt to combine transactions with persistent connections, issuing db2_commit() or db2_rollback() against a persistent connection will affect every persistent connection that is currently using the same underlying DB2 client connection. You may also rapidly experience locking escalation if you do not use autocommit for your persistent connections.
The database alias in the DB2 client catalog.
The username with which you are connecting to the database.
The password with which you are connecting to the database.
An associative array of connection options that affect the behavior of the connection, where valid array keys include:
Passing the DB2_AUTOCOMMIT_ON value turns autocommit on for this connection handle.
Passing the DB2_AUTOCOMMIT_OFF value turns autocommit off for this connection handle.
Returns a connection handle resource if the connection attempt is successful. db2_pconnect() tries to reuse an existing connection resource that exactly matches the database, username, and password parameters. If the connection attempt fails, db2_pconnect() returns FALSE.
Esempio 1. A db2_pconnect() example In the following example, the first call to db2_pconnect() returns a new persistent connection resource. The second call to db2_pconnect() returns a persistent connection resource that simply reuses the first persistent connection resource.
Il precedente esempio visualizzerà:
|
db2_prepare() creates a prepared SQL statement which can include 0 or more parameter markers (? characters) representing parameters for input, output, or input/output. You can pass parameters to the prepared statement using db2_bind_param(), or for input values only, as an array passed to db2_execute().
There are three main advantages to using prepared statements in your application:
Performance: when you prepare a statement, the database server creates an optimized access plan for retrieving data with that statement. Subsequently issuing the prepared statement with db2_execute() enables the statements to reuse that access plan and avoids the overhead of dynamically creating a new access plan for every statement you issue.
Security: when you prepare a statement, you can include parameter markers for input values. When you execute a prepared statement with input values for placeholders, the database server checks each input value to ensure that the type matches the column definition or parameter definition.
Advanced functionality: Parameter markers not only enable you to pass input values to prepared SQL statements, they also enable you to retrieve OUT and INOUT parameters from stored procedures using db2_bind_param().
A valid database connection resource variable as returned from db2_connect() or db2_pconnect().
An SQL statement, optionally containing one or more parameter markers..
An associative array containing statement options. You can use this parameter to request a scrollable cursor on database servers that support this functionality.
Passing the DB2_FORWARD_ONLY value requests a forward-only cursor for this SQL statement. This is the default type of cursor, and it is supported by all database servers. It is also much faster than a scrollable cursor.
Passing the DB2_SCROLLABLE value requests a scrollable cursor for this SQL statement. This type of cursor enables you to fetch rows non-sequentially from the database server. However, it is only supported by DB2 servers, and is much slower than forward-only cursors.
Returns a statement resource if the SQL statement was successfully parsed and prepared by the database server. Returns FALSE if the database server returned an error. You can determine which error was returned by calling db2_stmt_error() or db2_stmt_errormsg().
Esempio 1. Preparing and executing an SQL statement with parameter markers The following example prepares an INSERT statement that accepts four parameter markers, then iterates over an array of arrays containing the input values to be passed to db2_execute().
|
Returns a result set listing the primary keys for a table.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema which contains the tables. If schema is NULL, db2_primary_keys() matches the schema for the current connection.
The name of the table.
Returns a statement resource with a result set containing rows describing the primary keys for the specified table. The result set is composed of the following columns:
Column name | Description |
---|---|
TABLE_CAT | Name of the catalog for the table containing the primary key. The value is NULL if this table does not have catalogs. |
TABLE_SCHEM | Name of the schema for the table containing the primary key. |
TABLE_NAME | Name of the table containing the primary key. |
COLUMN_NAME | Name of the column containing the primary key. |
KEY_SEQ | 1-indexed position of the column in the key. |
PK_NAME | The name of the primary key. |
db2_column_privileges() |
db2_columns() |
db2_foreign_keys() |
db2_procedure_columns() |
db2_procedures() |
db2_special_columns() |
db2_statistics() |
db2_table_privileges() |
db2_tables() |
Returns a result set listing the parameters for one or more stored procedures.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema which contains the procedures. This parameter accepts a search pattern containing _ and % as wildcards.
The name of the procedure. This parameter accepts a search pattern containing _ and % as wildcards.
The name of the parameter. This parameter accepts a search pattern containing _ and % as wildcards. If this parameter is NULL, all parameters for the specified stored procedures are returned.
Returns a statement resource with a result set containing rows describing the parameters for the stored procedures matching the specified parameters. The rows are composed of the following columns:
Column name | Description |
---|---|
PROCEDURE_CAT | The catalog that contains the procedure. The value is NULL if this table does not have catalogs. |
PROCEDURE_SCHEM | Name of the schema that contains the stored procedure. |
PROCEDURE_NAME | Name of the procedure. |
COLUMN_NAME | Name of the parameter. |
COLUMN_TYPE |
An integer value representing the type of the parameter: |
DATA_TYPE | The SQL data type for the parameter represented as an integer value. |
TYPE_NAME | A string representing the data type for the parameter. |
COLUMN_SIZE | An integer value representing the size of the parameter. |
BUFFER_LENGTH | Maximum number of bytes necessary to store data for this parameter. |
DECIMAL_DIGITS | The scale of the parameter, or NULL where scale is not applicable. |
NUM_PREC_RADIX | An integer value of either 10 (representing an exact numeric data type), 2 (representing an approximate numeric data type), or NULL (representing a data type for which radix is not applicable). |
NULLABLE | An integer value representing whether the parameter is nullable or not. |
REMARKS | Description of the parameter. |
COLUMN_DEF | Default value for the parameter. |
SQL_DATA_TYPE | An integer value representing the size of the parameter. |
SQL_DATETIME_SUB | Returns an integer value representing a datetime subtype code, or NULL for SQL data types to which this does not apply. |
CHAR_OCTET_LENGTH | Maximum length in octets for a character data type parameter, which matches COLUMN_SIZE for single-byte character set data, or NULL for non-character data types. |
ORDINAL_POSITION | The 1-indexed position of the parameter in the CALL statement. |
IS_NULLABLE | A string value where 'YES' means that the parameter accepts or returns NULL values and 'NO' means that the parameter does not accept or return NULL values. |
db2_column_privileges() |
db2_columns() |
db2_foreign_keys() |
db2_primary_keys() |
db2_procedures() |
db2_special_columns() |
db2_statistics() |
db2_table_privileges() |
db2_tables() |
Returns a result set listing the stored procedures registered in a database.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema which contains the procedures. This parameter accepts a search pattern containing _ and % as wildcards.
The name of the procedure. This parameter accepts a search pattern containing _ and % as wildcards.
Returns a statement resource with a result set containing rows describing the stored procedures matching the specified parameters. The rows are composed of the following columns:
Column name | Description |
---|---|
PROCEDURE_CAT | The catalog that contains the procedure. The value is NULL if this table does not have catalogs. |
PROCEDURE_SCHEM | Name of the schema that contains the stored procedure. |
PROCEDURE_NAME | Name of the procedure. |
NUM_INPUT_PARAMS | Number of input (IN) parameters for the stored procedure. |
NUM_OUTPUT_PARAMS | Number of output (OUT) parameters for the stored procedure. |
NUM_RESULT_SETS | Number of result sets returned by the stored procedure. |
REMARKS | Any comments about the stored procedure. |
PROCEDURE_TYPE | Always returns 1, indicating that the stored procedure does not return a return value. |
db2_column_privileges() |
db2_columns() |
db2_foreign_keys() |
db2_primary_keys() |
db2_procedure_columns() |
db2_special_columns() |
db2_statistics() |
db2_table_privileges() |
db2_tables() |
Use db2_result() to return the value of a specified column in the current row of a result set. You must call db2_fetch_row() before calling db2_result() to set the location of the result set pointer.
A valid stmt resource.
Either an integer mapping to the 0-indexed field in the result set, or a string matching the name of the column.
Returns the value of the requested field if the field exists in the result set. Returns NULL if the field does not exist, and issues a warning.
Esempio 1. A db2_result() example The following example demonstrates how to iterate through a result set with db2_fetch_row() and retrieve columns from the result set with db2_result().
Il precedente esempio visualizzerà:
|
Rolls back an in-progress transaction on the specified connection resource and begins a new transaction. PHP applications normally default to AUTOCOMMIT mode, so db2_rollback() normally has no effect unless AUTOCOMMIT has been turned off for the connection resource.
Nota: If the specified connection resource is a persistent connection, all transactions in progress for all applications using that persistent connection will be rolled back. For this reason, persistent connections are not recommended for use in applications that require transactions.
A valid database connection resource variable as returned from db2_connect() or db2_pconnect().
Esempio 1. Rolling back a DELETE statement In the following example, we count the number of rows in a table, turn off AUTOCOMMIT mode on a database connection, delete all of the rows in the table and return the count of 0 to prove that the rows have been removed. We then issue db2_rollback() and return the updated count of rows in the table to show that the number is the same as before we issued the DELETE statement. The return to the original state of the table demonstrates that the roll back of the transaction succeeded.
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
db2_server_info -- Returns an object with properties that describe the DB2 database serverThis function returns an object with read-only properties that return information about the IBM DB2, Cloudscape, or Apache Derby database server. The following table lists the database server properties:
Tabella 1. Database server properties
Property name | Return type | Description |
---|---|---|
DBMS_NAME | string | The name of the database server to which you are connected. For DB2 servers this is a combination of DB2 followed by the operating system on which the database server is running. |
DBMS_VER | string | The version of the database server, in the form of a string "MM.mm.uuuu" where MM is the major version, mm is the minor version, and uuuu is the update. For example, "08.02.0001" represents major version 8, minor version 2, update 1. |
DB_CODEPAGE | int | The code page of the database to which you are connected. |
DB_NAME | string | The name of the database to which you are connected. |
DFT_ISOLATION | string | The default transaction isolation level supported by the
server:
|
IDENTIFIER_QUOTE_CHAR | string | The character used to delimit an identifier. |
INST_NAME | string | The instance on the database server that contains the database. |
ISOLATION_OPTION | array | An array of the isolation options supported by the database server. The isolation options are described in the DFT_ISOLATION property. |
KEYWORDS | array | An array of the keywords reserved by the database server. |
LIKE_ESCAPE_CLAUSE | bool | TRUE if the database server supports the use of % and _ wildcard characters. FALSE if the database server does not support these wildcard characters. |
MAX_COL_NAME_LEN | int | Maximum length of a column name supported by the database server, expressed in bytes. |
MAX_IDENTIFIER_LEN | int | Maximum length of an SQL identifier supported by the database server, expressed in characters. |
MAX_INDEX_SIZE | int | Maximum size of columns combined in an index supported by the database server, expressed in bytes. |
MAX_PROC_NAME_LEN | int | Maximum length of a procedure name supported by the database server, expressed in bytes. |
MAX_ROW_SIZE | int | Maximum length of a row in a base table supported by the database server, expressed in bytes. |
MAX_SCHEMA_NAME_LEN | int | Maximum length of a schema name supported by the database server, expressed in bytes. |
MAX_STATEMENT_LEN | int | Maximum length of an SQL statement supported by the database server, expressed in bytes. |
MAX_TABLE_NAME_LEN | int | Maximum length of a table name supported by the database server, expressed in bytes. |
NON_NULLABLE_COLUMNS | bool | TRUE if the database server supports columns that can be defined as NOT NULL, FALSE if the database server does not support columns defined as NOT NULL. |
PROCEDURES | bool | TRUE if the database server supports the use of the CALL statement to call stored procedures, FALSE if the database server does not support the CALL statement. |
SPECIAL_CHARS | string | A string containing all of the characters other than a-Z, 0-9, and underscore that can be used in an identifier name. |
SQL_CONFORMANCE | string | The level of conformance to the ANSI/ISO SQL-92 specification
offered by the database server:
|
Esempio 1. A db2_server_info() example To retrieve information about the server, you must pass a valid database connection resource to db2_server_info().
Il precedente esempio visualizzerà:
|
(PECL)
db2_special_columns -- Returns a result set listing the unique row identifier columns for a tableReturns a result set listing the unique row identifier columns for a table.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema which contains the tables.
The name of the table.
Integer value representing the minimum duration for which the unique row identifier is valid. This can be one of the following values:
Returns a statement resource with a result set containing rows with unique row identifier information for a table. The rows are composed of the following columns:
Column name | Description |
---|---|
SCOPE |
|
COLUMN_NAME | Name of the unique column. |
DATA_TYPE | SQL data type for the column. |
TYPE_NAME | Character string representation of the SQL data type for the column. |
COLUMN_SIZE | An integer value representing the size of the column. |
BUFFER_LENGTH | Maximum number of bytes necessary to store data from this column. |
DECIMAL_DIGITS | The scale of the column, or NULL where scale is not applicable. |
NUM_PREC_RADIX | An integer value of either 10 (representing an exact numeric data type), 2 (representing an approximate numeric data type), or NULL (representing a data type for which radix is not applicable). |
PSEUDO_COLUMN | Always returns 1. |
db2_column_privileges() |
db2_columns() |
db2_foreign_keys() |
db2_primary_keys() |
db2_procedure_columns() |
db2_procedures() |
db2_statistics() |
db2_table_privileges() |
db2_tables() |
Returns a result set listing the index and statistics for a table.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema that contains the targeted table. If this parameter is NULL, the statistics and indexes are returned for the schema of the current user.
The name of the table.
An integer value representing the type of index information to return.
Return only the information for unique indexes on the table.
Return the information for all indexes on the table.
Returns a statement resource with a result set containing rows describing the statistics and indexes for the base tables matching the specified parameters. The rows are composed of the following columns:
Column name | Description | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
TABLE_CAT | The catalog that contains the table. The value is NULL if this table does not have catalogs. | ||||||||||
TABLE_SCHEM | Name of the schema that contains the table. | ||||||||||
TABLE_NAME | Name of the table. | ||||||||||
NON_UNIQUE |
An integer value representing whether the index prohibits unique values, or whether the row represents statistics on the table itself: | ||||||||||
INDEX_QUALIFIER | A string value representing the qualifier that would have to be prepended to INDEX_NAME to fully qualify the index. | ||||||||||
INDEX_NAME | A string representing the name of the index. | ||||||||||
TYPE |
An integer value representing the type of information contained in this row of the result set:
| ||||||||||
ORDINAL_POSITION | The 1-indexed position of the column in the index. NULL if the row contains statistics information about the table itself. | ||||||||||
COLUMN_NAME | The name of the column in the index. NULL if the row contains statistics information about the table itself. | ||||||||||
ASC_OR_DESC | A if the column is sorted in ascending order, D if the column is sorted in descending order, NULL if the row contains statistics information about the table itself. | ||||||||||
CARDINALITY |
If the row contains information about an index, this column contains an integer value representing the number of unique values in the index. If the row contains information about the table itself, this column contains an integer value representing the number of rows in the table. | ||||||||||
PAGES |
If the row contains information about an index, this column contains an integer value representing the number of pages used to store the index. If the row contains information about the table itself, this column contains an integer value representing the number of pages used to store the table. | ||||||||||
FILTER_CONDITION | Always returns NULL. |
db2_column_privileges() |
db2_columns() |
db2_foreign_keys() |
db2_primary_keys() |
db2_procedure_columns() |
db2_procedures() |
db2_special_columns() |
db2_table_privileges() |
db2_tables() |
Returns a string containing the SQLSTATE value returned by an SQL statement.
If you do not pass a statement resource as an argument to db2_stmt_error(), the driver returns the SQLSTATE value associated with the last attempt to return a statement resource, for example, from db2_prepare() or db2_exec().
To learn what the SQLSTATE value means, you can issue the following command at a DB2 Command Line Processor prompt: db2 '? sqlstate-value'. You can also call db2_stmt_errormsg() to retrieve an explicit error message and the associated SQLCODE value.
Returns a string containing the last SQL statement error message.
If you do not pass a statement resource as an argument to db2_stmt_errormsg(), the driver returns the error message associated with the last attempt to return a statement resource, for example, from db2_prepare() or db2_exec().
Returns a string containing the error message and SQLCODE value for the last error that occurred issuing an SQL statement.
(PECL)
db2_table_privileges -- Returns a result set listing the tables and associated privileges in a databaseReturns a result set listing the tables and associated privileges in a database.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema which contains the tables. This parameter accepts a search pattern containing _ and % as wildcards.
The name of the table. This parameter accepts a search pattern containing _ and % as wildcards.
Returns a statement resource with a result set containing rows describing the privileges for the tables that match the specified parameters. The rows are composed of the following columns:
Column name | Description |
---|---|
TABLE_CAT | The catalog that contains the table. The value is NULL if this table does not have catalogs. |
TABLE_SCHEM | Name of the schema that contains the table. |
TABLE_NAME | Name of the table. |
GRANTOR | Authorization ID of the user who granted the privilege. |
GRANTEE | Authorization ID of the user to whom the privilege was granted. |
PRIVILEGE | The privilege that has been granted. This can be one of ALTER, CONTROL, DELETE, INDEX, INSERT, REFERENCES, SELECT, or UPDATE. |
IS_GRANTABLE | A string value of "YES" or "NO" indicating whether the grantee can grant the privilege to other users. |
db2_column_privileges() |
db2_columns() |
db2_foreign_keys() |
db2_primary_keys() |
db2_procedure_columns() |
db2_procedures() |
db2_special_columns() |
db2_statistics() |
db2_tables() |
Returns a result set listing the tables and associated metadata in a database.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema which contains the tables. This parameter accepts a search pattern containing _ and % as wildcards.
The name of the table. This parameter accepts a search pattern containing _ and % as wildcards.
A list of comma-delimited table type identifiers. To match all table types, pass NULL or an empty string. Valid table type identifiers include: ALIAS, HIERARCHY TABLE, INOPERATIVE VIEW, NICKNAME, MATERIALIZED QUERY TABLE, SYSTEM TABLE, TABLE, TYPED TABLE, TYPED VIEW, and VIEW.
Nota: Icap will be removed in near future. Neither this module, nor those versions of icap library are supported any longer. If you want to use calendar capabilities in PHP, use mcal instead.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
icap_delete_event() deletes the calendar event specified by the uid.
Returns TRUE.
icap_fetch_event() fetches an event from the calendar stream specified by event_id.
Returns an event object consisting of:
int id - ID of that event.
int public - TRUE if the event if public, FALSE if it is private.
string category - Category string of the event.
string title - Title string of the event.
string description - Description string of the event.
int alarm - number of minutes before the event to send an alarm/reminder.
object start - Object containing a datetime entry.
object end - Object containing a datetime entry.
int year - year
int month - month
int mday - day of month
int hour - hour
int min - minutes
int sec - seconds
(PHP 4 <= 4.2.3)
icap_list_alarms -- Return a list of events that has an alarm triggered at the given datetimeReturns an array of event ID's that has an alarm going off at the given datetime.
icap_list_alarms() function takes in a datetime for a calendar stream. An array of event id's that has an alarm should be going off at the datetime are returned.
All datetime entries consist of an object that contains:
int year - year
int month - month
int mday - day of month
int hour - hour
int min - minutes
int sec - seconds
Returns an array of event ID's that are between the two given datetimes.
icap_list_events() function takes in a beginning datetime and an end datetime for a calendar stream. An array of event id's that are between the given datetimes are returned.
All datetime entries consist of an object that contains:
int year - year
int month - month
int mday - day of month
int hour - hour
int min - minutes
int sec - seconds
Returns an ICAP stream on success, FALSE on error.
icap_open() opens up an ICAP connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
icap_snooze() turns on an alarm for a calendar event specified by the uid.
Returns TRUE.
icap_store_event() Stores an event into an ICAP calendar. An event object consists of:
int public - 1 if public, 0 if private;
string category - Category string of the event.
string title - Title string of the event.
string description - Description string of the event.
int alarm - Number of minutes before the event to send out an alarm.
datetime start - datetime object of the start of the event.
datetime end - datetime object of the end of the event.
All datetime entries consist of an object that contains:
int year - year
int month - month
int mday - day of month
int hour - hour
int min - minutes
int sec - seconds
Returns TRUE on success and FALSE on error.
Questo modulo contiene un'interfaccia al tool di conversione dei caratteri iconv. Tramite questo modulo si può convertire una stringa dal set di caratteri locale ad un'altro. I set di caratteri supportati dipendono dalla implementazione di iconv installata. Occorre rilevare che le funzioni iconv, in alcuni sistemi, possono non fornire le risposte attese. In questi casi è una buona idea installarela libreria GNU libiconv, la quale fornisce risultati più consistenti.
Dalla versione 5.0.0 di PHP, questa versione viene rilasciata con diverse funzioni che aiutano a realizzare script in più lingue. Guardare nelle sezioni seguenti per scoprire queste nuove caratteristiche.
Non occorre nulla se il sistema che si sta utilizzando è un sistema recente compatibile POSIX, poichè le librerie C standard fornite con la macchina forniscono le funzioni iconv. Negli altri casi occorre installare sul sistema la libreria libiconv
Per potere utilizzare le funzioni fornite da questo modulo, occorre compila il PHP con la seguente linea di configurazione: --with-iconv[=DIR].
Note per gli utenti Windows®: Per potere abilitare questo modulo nei sistemi Windows® occorre posizionare la DLL iconv.dll o iconv-1.3.dll (nelle versioni precedenti alla 4.2.1), rilasciata con il pacchetto PHP/Win32 nella directory indicata dalla variabile d'ambiente PATH oppure in una directory di installazione di Windows®.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Parametri di configurazione di Iconv
Nome | Default | Modificabile |
---|---|---|
iconv.input_encoding | ICONV_INPUT_ENCODING | PHP_INI_ALL |
iconv.output_encoding | ICONV_OUTPUT_ENCODING | PHP_INI_ALL |
iconv.internal_encoding | ICONV_INTERNAL_ENCODING | PHP_INI_ALL |
Dalla versione 4.3.0 di PHP è possibile identificare da untime quale implementazione di iconv è adottata da questo modulo.
Tabella 2. Costanti iconv
Nome | Tipo | Descrizione |
---|---|---|
ICONV_IMPL | string | Il nome dell'implementazione |
ICONV_VERSION | string | Versione dell'implementazione |
Nota: La scrittura di codice che utilizzi tali costanti per identificare l'implementazione è scoraggiata.
Dalla versione 5.0.0 di PHP saranno disponibili le seguenti costanti:
Tabella 3. Costanti iconv dispèonibili da PHP 5.0.0
Nome | Tipo | Descrizione |
---|---|---|
ICONV_MIME_DECODE_STRICT | integer | Maschera di bit utilizzata da iconv_mime_decode() |
ICONV_MIME_DECODE_CONTINUE_ON_ERROR | integer | Maschera di bit utilizzata per iconv_mime_decode() |
(PHP 4 >= 4.0.5, PHP 5)
iconv_get_encoding -- Visualizza l'attuale impostazione per la conversione dei caratteri codificatiRestituisce l'attuale impostazione di ob_iconv_handler() come array o FALSE in caso di insuccesso.
Vedere anche: iconv_set_encoding() e ob_iconv_handler().
Returns an associative array that holds a whole set of MIME header fields specified by encoded_headers on success, or FALSE if an error occurs during the decoding.
Each key of the return value represents an individual field name and the corresponding element represents a field value. If more than one field of the same name are present, iconv_mime_decode_headers() automatically incorporates them into a numerically indexed array in the order of occurrence.
mode determines the behaviour in the event iconv_mime_decode_headers() encounters a malformed MIME header field. You can specify any combination of the following bitmasks.
Tabella 1. Bitmasks acceptable to iconv_mime_decode_headers()
Value | Constant | Description |
---|---|---|
1 | ICONV_MIME_DECODE_STRICT | If set, the given header is decoded in full conformance with the standards defined in RFC2047. This option is disabled by default because there are a lot of broken mail user agents that don't follow the specification and don't produce correct MIME headers. |
2 | ICONV_MIME_DECODE_CONTINUE_ON_ERROR | If set, iconv_mime_decode_headers() attempts to ignore any grammatical errors and continue to process a given header. |
The optional charset parameter specifies the character set to represent the result by. If omitted, iconv.internal_charset will be used.
Esempio 1. iconv_mime_decode_headers() example
Il precedente esempio visualizzerà:
|
See also iconv_mime_decode(), mb_decode_mimeheader(), imap_mime_header_decode(), imap_base64() and imap_qprint().
Returns a decoded MIME field on success, or FALSE if an error occurs during the decoding.
mode determines the behaviour in the event iconv_mime_decode() encounters a malformed MIME header field. You can specify any combination of the following bitmasks.
Tabella 1. Bitmasks acceptable to iconv_mime_decode()
Value | Constant | Description |
---|---|---|
1 | ICONV_MIME_DECODE_STRICT | If set, the given header is decoded in full conformance with the standards defined in RFC2047. This option is disabled by default because there are a lot of broken mail user agents that don't follow the specification and don't produce correct MIME headers. |
2 | ICONV_MIME_DECODE_CONTINUE_ON_ERROR | If set, iconv_mime_decode() attempts to continue to process the given header even though an error occurs. |
The optional charset parameter specifies the character set to represent the result by. If omitted, iconv.internal_charset will be used.
See also iconv_mime_decode_headers(), mb_decode_mimeheader(), imap_mime_header_decode(), imap_base64() and imap_qprint().
Composes and returns a string that represents a valid MIME header field, which looks like the following:
Subject: =?ISO-8859-1?Q?Pr=FCfung_f=FCr?= Entwerfen von einer MIME kopfzeile |
You can control the behaviour of iconv_mime_encode() by specifying an associative array that contains configuration items to the optional third parameter preferences. The items supported by iconv_mime_encode() are listed below. Note that item names are treated case-sensitive.
Tabella 1. Configuration items supported by iconv_mime_encode()
Item | Type | Description | Default value | Example |
---|---|---|---|---|
scheme | boolean | Specifies the method to encode a field value by. The value of this item may be either "B" or "Q", where "B" stands for base64 encoding scheme and "Q" stands for quoted-printable encoding scheme. | B | B |
input-charset | string | Specifies the character set in which the first parameter field_name and the second parameter field_value are presented. If not given, iconv_mime_encode() assumes those parameters are presented to it in the iconv.internal_charset ini setting. | iconv.internal_charset | ISO-8859-1 |
output-charset | string | Specifies the character set to use to compose the MIME header. If not given, the same value as input-charset will be used. | the same value as input-charset | UTF-8 |
line-length | integer | Specifies the maximum length of the header lines. The resulting header is "folded" to a set of multiple lines in case the resulting header field would be longer than the value of this parameter, according to RFC2822 - Internet Message Format. If not given, the length will be limited to 76 characters. | 76 | 996 |
line-break-chars | string | Specifies the sequence of characters to append to each line as an end-of-line sign when "folding" is performed on a long header field. If not given, this defaults to "\r\n" (CR LF). Note that this parameter is always treated as an ASCII string regardless of the value of input-charset. | \r\n | \n |
Esempio 1. iconv_mime_encode() example:
|
See also imap_binary(), mb_encode_mimeheader() and imap_8bit().
(PHP 4 >= 4.0.5, PHP 5)
iconv_set_encoding -- Setta l'attuale impostazione per la conversione dei caratteri codificatiCambia il valore di type in charset e restituisc TRUE in caso di successo o FALSE in caso di fallimento.
Vedere anche: iconv_get_encoding() e ob_iconv_handler().
Returns the character count of str.
In contrast to strlen(), iconv_strlen() counts the occurrences of characters in the given byte sequence str on the basis of the specified character set, the result of which is not necessarily identical to the length of the string in byte.
If charset parameter is omitted, str is assumed to be encoded in iconv.internal_charset.
See also strlen() and mb_strlen().
Returns the numeric position of the first occurrence of needle in haystack.
The optional offset parameter specifies the position from which the search should be performed.
If needle is not found, iconv_strpos() will return FALSE.
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
If haystack or needle is not a string, it is converted to a string and applied as the ordinal value of a character.
In contrast to strpos(), the return value of iconv_strpos() is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found. The characters are counted on the basis of the specified character set charset.
If charset parameter is omitted, string are assumed to be encoded in iconv.internal_charset.
See also strpos(), iconv_strrpos() and mb_strpos().
(PHP 5)
iconv_strrpos -- Finds the last occurrence of a needle within the specified range of haystackReturns the numeric position of the last occurrence of needle in haystack.
If needle is not found, iconv_strrpos() will return FALSE.
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
If haystack or needle is not a string, it is converted to a string and applied as the ordinal value of a character.
In contrast to strpos(), the return value of iconv_strrpos() is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found. The characters are counted on the basis of the specified character set charset.
See also strrpos(), iconv_strpos() and mb_strrpos().
Returns the portion of str specified by the start and length parameters.
If start is non-negative, iconv_substr() cuts the portion out of str beginning at start'th character, counting from zero.
If start is negative, iconv_substr() cuts out the portion beginning at the position, start characters away from the end of str.
If length is given and is positive, the return value will contain at most length characters of the portion that begins at start (depending on the length of string). If str is shorter than start characters long, FALSE will be returned.
If negative length is passed, iconv_substr() cuts the portion out of str from the start'th character up to the character that is length characters away from the end of the string. In case start is also negative, the start position is calculated beforehand according to the rule explained above.
Note that offset and length parameters are always deemed to represent offsets that are calculated on the basis of the character set determined by charset, whilst the counterpart substr() always takes these for byte offsets. If charset is not given, the character set is determined by the iconv.internal_encoding ini setting.
See also substr(), mb_substr() and mb_strcut().
Converte la stringa codificata nel parametro stringa in in_charset nella stringa codificata in out_charset. Restituisce la stringa convertita o FALSE, se fallisce.
(PHP 4 >= 4.0.5, PHP 5)
ob_iconv_handler -- Converte caratteri codificati come un output buffer handlerConverte la stringa codificata del parametro internal_encoding in output_encoding.
internal_encoding e output_encoding dovrebbero essere definite da iconv_set_encoding() o nel file di configurazione.
Vedere anche: iconv_get_encoding() e iconv_set_encoding().
These functions let you read and manipulate ID3 tags. ID3 tags are used in MP3 files to store title of the song, as well as information about the artist, album, genre, year and track number.
Since version 0.2 it is also possible to extract text frames from ID3 v2.2+ tags.
id3 is part of PECL and can be installed using the PEAR installer. To compile PHP with id3 support, download the sourcecode, put it in php-src/ext/id3 and compile PHP using --enable-id3.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Most of the id3 functions either let you specify or return a tag version. In order to specify the version please use on of these constants.
ID3_V1_0 is used if you are working with ID3 V1.0 tags. These tags may contain the fields title, artist, album, genre, year and comment.
ID3_V1_1 is used if you are working with ID3 V1.1 tags. These tags may all information contained in v1.0 tags plus the track number.
ID3_V2_1 is used if you are working with ID3 V2.1 tags.
ID3_V2_2 is used if you are working with ID3 V2.2 tags.
ID3_V2_3 is used if you are working with ID3 V2.3 tags.
ID3_V2_4 is used if you are working with ID3 V2.4 tags.
ID3_BEST is used if would like to let the id3 functions determine which tag version should be used.
id3_get_frame_long_name() returns the long name for an ID3v2 frame.
See also id3_get_frame_short_name().
id3_get_frame_short_name() returns the short name for an ID3v2 frame.
The values returned by id3_get_short_name() are used in the array returned by id3_get_tag().
See also id3_get_frame_long_name().
id3_get_genre_id() returns the id for a genre. If the specified genre is not available in the genre list, id3_get_genre_id() will return FALSE
In an ID3 tag, the genre is stored using a integer ranging from 0 to 147.
See also id3_get_genre_list() and id3_get_genre_name().
id3_get_genre_list() returns an array containing all possible genres that may be stored in an ID3 tag. This list has been created by Eric Kemp and later extended by WinAmp.
This function is useful to provide you users a list of genres from which they may choose one. When updating the ID3 tag you will always have to specify the genre as an integer ranging from 0 to 147.
Esempio 1. id3_get_genre_list() example
This will output:
|
See also id3_get_genre_name() and id3_get_genre_id().
id3_get_genre_name() returns the name for a genre id.
In an ID3 tag, the genre is stored using a integer ranging from 0 to 147.
See also id3_get_genre_list() and id3_get_genre_id().
id3_get_tag() is used to get all information stored in the id3 tag of the specified file.
Nota: Instead of a filename you may also pass a valid stream resource.
The optional version parameter allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags.
The key genre will contain an integer between 0 and 147. You may use id3_get_genre_name() to convert it to a human readable string.
Since version 0.2 id3_get_tag() also supports ID3 tags of version 2.2, 2.3 and 2.4. To extract information from these tags, pass one of the constants ID3_V2_2, ID3_V2_3 or ID3_V2_4 as the second parameter.
Esempio 2. id3_get_tag() example
This will output something like:
|
ID3 v2.x tags can contain a lot more information about the MP3 file than ID3 v1.x tags.
See also id3_set_tag(), id3_remove_tag() and id3_get_version().
id3_get_version() retrieves the version(s) of the ID3 tag(s) in the MP3 file. As a tag can contain ID3 v1.x and v2.x tags, the return value of this function should be bitwise compared with the predefined constants ID3_V1_0, ID3_V1_1 and ID3_V2.
Nota: Instead of a filename you may also pass a valid stream resource.
Esempio 1. id3_get_version() example
This will output something like:
|
If a file contains an ID3 v1.1 tag, it always contains a 1.0 tag, as version 1.1 is just an extension of 1.0.
See also id3_get_tag(), id3_set_tag() and id3_remove_tag().
id3_remove_tag() is used to remove the information stored of an ID3 tag. If no tag has been present, it will return FALSE and leave the file as it was.
Nota: Instead of a filename you may also pass a valid stream resource.
The optional version parameter allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags.
Nota: Currently id3_remove_tag() only supports version 1.0 and 1.1. If you choose to remove a 1.0 tag and the file contains a 1.1 tag, this tag will be removed, as v1.1 is only an extension of 1.0.
See also id3_get_tag(), id3_set_tag() and id3_get_version().
id3_set_tag() is used to change the information stored of an ID3 tag. If no tag has been present, it will be added to the file.
Nota: Instead of a filename you may also pass a valid stream resource.
The optional version parameter allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags.
Esempio 1. id3_set_tag() example
If the file is writable, this will output:
|
Nota: Currently id3_set_tag() only supports version 1.0 and 1.1.
The following keys may be used in the associative array:
Tabella 1. Keys in the associative array
key | possible value | available in version |
---|---|---|
title | string with maximum of 30 characters | v1.0, v1.1 |
artist | string with maximum of 30 characters | v1.0, v1.1 |
album | string with maximum of 30 characters | v1.0, v1.1 |
year | 4 digits | v1.0, v1.1 |
genre | integer value between 0 and 147 | v1.0, v1.1 |
comment | string with maximum of 30 characters (28 in v1.1) | v1.0, v1.1 |
track | integer between 0 and 255 | v1.1 |
See also id3_get_tag(), id3_remove_tag() and id3_get_version().
This PECL extension is not bundled with PHP. Questa estensione è disponibile solo per sistemi Win32. Prevede funzioni per amministrare Microsoft Internet Information Server (IIS). L'estensione include la funzione per creare siti web e directory virtuali come meglio e come la configurazione della sicurezza e lo script mapping. Queste funzioni sono state aggiunte nel PHP 4.
Per potere utilizzare queste funzioni occorre abilitare l'uso della dll php_iisfunc.dll dal php.ini. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
(PECL)
iis_get_script_map -- Riceve informazioni sul mapping dello script sulla cartella virtuale per una specifica estensioneo
Ogni server virtuale in IIS è associato con un numero di istanza. iis_get_server_by_path() trova il numero di istanza dall'attuale path alla root directory.
In PHP puoi usare delle funzioni specifiche per sapere la dimensione di un'immagine JPEG, GIF, PNG, SWF, TIFF e JPEG2000.
Se hai installato le librerie GD (scaricabili su http://www.boutell.com/gd/) sarai anche in grado di creare immagini al volo e di modificarle.
I formati delle immagini sulle quali potrai agire dipendono dalla versione delle librerie GD che hai installato, e dalle altre librerie di cui GD può aver bisogno per accedere a quei formati di immagine. Versioni precedenti alla gd-1.6 supportano il formato GIF ma non quello PNG, mentre versioni superiori alla gd-1.6 supportano il formato PNG ma non il GIF.
Se hai compilato PHP con l'opzione --enable-exif sarai in grado di lavorare con le informazioni memorizzate negli header delle immagini JPEG e TIFF. Queste funzioni non richiedono le librerie GD.
Per leggere e scrivere immagini in formato JPEG avrai bisogno di installare jpeg-6b (scaricabile da ftp://ftp.uu.net/graphics/jpeg/) e quindi ricompilare le librerie GD in modo che usino jpeg-6b. Dovrai anche compilare PHP con l'opzione --with-jpeg-dir=/percorso/per/jpeg-6b.
Per aggiungere il supporto per i Font Type 1 dovrai installare t1lib (scaricabile su ftp://sunsite.unc.edu/pub/Linux/libs/graphics/), e quindi aggiungere l'opzione --with-t1lib[=dir].
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Returns an associative array describing the version and capabilities of the installed GD library.
Tabella 1. Elements of array returned by gd_info()
Attribute | Meaning |
---|---|
GD Version | string value describing the installed libgd version. |
Freetype Support | boolean value. TRUE if Freetype Support is installed. |
Freetype Linkage | string value describing the way in which Freetype was linked. Expected values are: 'with freetype', 'with TTF library', and 'with unknown library'. This element will only be defined if Freetype Support evaluated to TRUE. |
T1Lib Support | boolean value. TRUE if T1Lib support is included. |
GIF Read Support | boolean value. TRUE if support for reading GIF images is included. |
GIF Create Support | boolean value. TRUE if support for creating GIF images is included. |
JPG Support | boolean value. TRUE if JPG support is included. |
PNG Support | boolean value. TRUE if PNG support is included. |
WBMP Support | boolean value. TRUE if WBMP support is included. |
XBM Support | boolean value. TRUE if XBM support is included. |
Esempio 1. Using gd_info()
The typical output is :
|
See also imagepng(), imagejpeg(), imagegif(), imagewbmp(), and imagetypes().
The getimagesize() function will determine the size of any GIF, JPG, PNG, SWF, SWC, PSD, TIFF, BMP, IFF, JP2, JPX, JB2, JPC, XBM, or WBMP image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML <IMG> tag.
If accessing the filename image is impossible, or if it isn't a valid picture, getimagesize() will return FALSE and generate an error of level E_WARNING.
Nota: Support for JPC, JP2, JPX, JB2, XBM, and WBMP became available in PHP 4.3.2. Support for SWC exists as of PHP 4.3.0 and TIFF support was added in PHP 4.2.0
Nota: JPEG 2000 support was added in PHP 4.3.2. Note that JPC and JP2 are capable of having components with different bit depths. In this case, the value for "bits" is the highest bit depth encountered. Also, JP2 files may contain multiple JPEG 2000 codestreams. In this case, getimagesize() returns the values for the first codestream it encounters in the root of the file.
Nota: The getimagesize() function does not require the GD image library.
Returns an array with 4 elements. Index 0 contains the width of the image in pixels. Index 1 contains the height. Index 2 is a flag indicating the type of the image: 1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(intel byte order), 8 = TIFF(motorola byte order), 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC, 14 = IFF, 15 = WBMP, 16 = XBM. These values correspond to the IMAGETYPE constants that were added in PHP 4.3.0. Index 3 is a text string with the correct height="yyy" width="xxx" string that can be used directly in an IMG tag.
URL support was added in PHP 4.0.5
With JPG images, two extra indexes are returned: channels and bits. channels will be 3 for RGB pictures and 4 for CMYK pictures. bits is the number of bits for each color.
Beginning with PHP 4.3.0, bits and channels are present for other image types, too. However, the presence of these values can be a bit confusing. As an example, GIF always uses 3 channels per pixel, but the number of bits per pixel cannot be calculated for an animated GIF with a global color table.
Some formats may contain no image or may contain multiple images. In these cases, getimagesize() might not be able to properly determine the image size. getimagesize() will return zero for width and height in these cases.
Beginning with PHP 4.3.0, getimagesize() also returns an additional parameter, mime, that corresponds with the MIME type of the image. This information can be used to deliver images with correct HTTP Content-type headers:
The optional imageinfo parameter allows you to extract some extended information from the image file. Currently, this will return the different JPG APP markers as an associative array. Some programs use these APP markers to embed text information in images. A very common one is to embed IPTC http://www.iptc.org/ information in the APP13 marker. You can use the iptcparse() function to parse the binary APP13 marker into something readable.
See also image_type_to_mime_type(), exif_imagetype(), exif_read_data(), and exif_thumbnail().
(no version information, might be only in CVS)
image_type_to_extension -- Get file extension for image typeAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
image_type_to_mime_type -- Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetypeThe image_type_to_mime_type() function will determine the Mime-Type for an IMAGETYPE constant.
The returned values are as follows
Tabella 1. Returned values Constants
imagetype | Returned value |
---|---|
IMAGETYPE_GIF | image/gif |
IMAGETYPE_JPEG | image/jpeg |
IMAGETYPE_PNG | image/png |
IMAGETYPE_SWF | application/x-shockwave-flash |
IMAGETYPE_PSD | image/psd |
IMAGETYPE_BMP | image/bmp |
IMAGETYPE_TIFF_II (intel byte order) | image/tiff |
IMAGETYPE_TIFF_MM (motorola byte order) | image/tiff |
IMAGETYPE_JPC | application/octet-stream |
IMAGETYPE_JP2 | image/jp2 |
IMAGETYPE_JPX | application/octet-stream |
IMAGETYPE_JB2 | application/octet-stream |
IMAGETYPE_SWC | application/x-shockwave-flash |
IMAGETYPE_IFF | image/iff |
IMAGETYPE_WBMP | image/vnd.wap.wbmp |
IMAGETYPE_XBM | image/xbm |
Nota: This function does not require the GD image library.
See also getimagesize(), exif_imagetype(), exif_read_data() and exif_thumbnail().
(PHP 4 >= 4.0.5, PHP 5)
image2wbmp -- Rende disponibile l'immagine per il browser o la salva in un fileimage2wbmp() crea un file WBMP dall'immagine specificata nel parametro image. L'argomento image è quello ritornato dalla funzione imagecreate().
L'argomento filename è opzionale, e può essere omesso. Puoi creare uno script PHP che ha direttamente un'immagine WBMP come output inviando image/vnd.wap.wbmp insieme alla funzione header().
Nota: Il supporto per WBMP è disponibile solo se PHP è compilato assieme a GD-1.8 o superiori.
Vedere anche imagewbmp().
imagealphablending() allows for two different modes of drawing on truecolor images. In blending mode, the alpha channel component of the color supplied to all drawing function, such as imagesetpixel() determines how much of the underlying color should be allowed to shine through. As a result, gd automatically blends the existing color at that point with the drawing color, and stores the result in the image. The resulting pixel is opaque. In non-blending mode, the drawing color is copied literally with its alpha channel information, replacing the destination pixel. Blending mode is not available when drawing on palette images. If blendmode is TRUE, then blending mode is enabled, otherwise disabled. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: This function requires GD 2.0.1 or later.
Activate the fast drawing antialiased methods for lines and wired polygons. It does not support alpha components. It works using a direct blend operation. It works only with truecolor images.
Thickness and styled are not supported.
Using antialiased primitives with transparent background color can end with some unexpected results. The blend method uses the background color as any other colors. The lack of alpha component support does not allow an alpha based antialiasing method.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.
See also imagecreatetruecolor().
imagearc() draws a partial ellipse centered at cx, cy (top left is 0, 0) in the image represented by image. W and h specifies the ellipse's width and height respectively while the start and end points are specified in degrees indicated by the s and e arguments. 0° is located at the three-o'clock position, and the arc is drawn clockwise.
Esempio 1. Drawing a circle with imagearc()
|
See also imageellipse(), imagefilledellipse(), and imagefilledarc().
imagechar() draws the first character of c in the image identified by image with its upper-left at x,y (top left is 0, 0) with the color color. If font is 1, 2, 3, 4 or 5, a built-in font is used (with higher numbers corresponding to larger fonts).
Esempio 1. imagechar() example
|
See also imagecharup() and imageloadfont().
imagecharup() draws the character c vertically in the image identified by image at coordinates x, y (top left is 0, 0) with the color color. If font is 1, 2, 3, 4 or 5, a built-in font is used.
Esempio 1. imagecharup() example
|
See also imagechar() and imageloadfont().
imagecolorallocate() returns a color identifier representing the color composed of the given RGB components. The image argument is the return from the imagecreatetruecolor() function. red, green and blue are the values of the red, green and blue component of the requested color respectively. These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF. imagecolorallocate() must be called to create each color that is to be used in the image represented by image.
Nota: The first call to imagecolorallocate() fills the background color.
<?php $im = imagecreatetruecolor('example.jpg'); // sets background to red $background = imagecolorallocate($im, 255, 0, 0); // sets some colors $white = imagecolorallocate($im, 255, 255, 255); $black = imagecolorallocate($im, 0, 0, 0); // hexadecimal way $white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF); $black = imagecolorallocate($im, 0x00, 0x00, 0x00); ?> |
Returns -1 if the allocation failed.
See also imagecolorallocatealpha() and imagecolordeallocate().
imagecolorallocatealpha() behaves identically to imagecolorallocate() with the addition of the transparency parameter alpha which may have a value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.
Returns FALSE if the allocation failed.
Esempio 1. Example of using imagecolorallocatealpha()
|
Nota: This function requires GD 2.0.1 or later.
See also imagecolorallocate() and imagecolordeallocate().
Returns the index of the color of the pixel at the specified location in the image specified by image.
If PHP is compiled against GD library 2.0 or higher and the image is a truecolor image, this function returns the RGB value of that pixel as integer. Use bitshifting and masking to access the distinct red, green and blue component values:
See also imagecolorset() and imagecolorsforindex().
Returns the index of the color in the palette of the image which is "closest" to the specified RGB value.
The "distance" between the desired color and each color in the palette is calculated as if the RGB values represented points in three-dimensional space.
If you created the image from a file, only colors used in the image are resolved. Colors present only in the pallete are not resolved.
See also imagecolorexact().
(PHP 4 >= 4.0.6, PHP 5)
imagecolorclosestalpha -- Get the index of the closest color to the specified color + alphaReturns the index of the color in the palette of the image which is "closest" to the specified RGB value and alpha level.
Nota: This function requires GD 2.0.1 or later.
See also imagecolorexactalpha().
(PHP 4 >= 4.0.1, PHP 5)
imagecolorclosesthwb -- Get the index of the color which has the hue, white and blackness nearest to the given color
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
The imagecolordeallocate() function de-allocates a color previously allocated with imagecolorallocate() or imagecolorallocatealpha().
See also imagecolorallocate() and imagecolorallocatealpha().
Returns the index of the specified color in the palette of the image.
If the color does not exist in the image's palette, -1 is returned.
If you created the image from a file, only colors used in the image are resolved. Colors present only in the pallete are not resolved.
See also imagecolorclosest().
Returns the index of the specified color+alpha in the palette of the image.
If the color does not exist in the image's palette, -1 is returned.
Nota: This function requires GD 2.0.1 or later.
See also imagecolorclosestalpha().
(PHP 4 >= 4.3.0, PHP 5)
imagecolormatch -- Makes the colors of the palette version of an image more closely match the true color versionAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
image1 must be Truecolor, image2 must be Palette, and both image1 and image2 must be the same size.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.
Nota: This function requires GD 2.0.1 or later.
See also imagecreatetruecolor().
(PHP 3 >= 3.0.2, PHP 4, PHP 5)
imagecolorresolve -- Get the index of the specified color or its closest possible alternativeThis function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.
If you created the image from a file, only colors used in the image are resolved. Colors present only in the pallete are not resolved.
See also imagecolorclosest().
(PHP 4 >= 4.0.6, PHP 5)
imagecolorresolvealpha -- Get the index of the specified color + alpha or its closest possible alternativeThis function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.
Nota: This function requires GD 2.0.1 or later.
See also imagecolorclosestalpha().
This sets the specified index in the palette to the specified color. This is useful for creating flood-fill-like effects in palleted images without the overhead of performing the actual flood-fill.
See also imagecolorat().
This returns an associative array with red, green, blue and alpha keys that contain the appropriate values for the specified color index.
Esempio 1. imagecolorsforindex() example
This example will output :
|
See also imagecolorat() and imagecolorexact().
This returns the number of colors in the specified image's palette.
See also imagecolorat() and imagecolorsforindex().
imagecolortransparent() sets the transparent color in the image image to color. image is the image identifier returned by imagecreatetruecolor() and color is a color identifier returned by imagecolorallocate().
Nota: The transparent color is a property of the image, transparency is not a property of the color. Once you have set a color to be the transparent color, any regions of the image in that color that were drawn previously will be transparent.
The identifier of the new (or current, if none is specified) transparent color is returned.
Nota: Transparency is copied only with imagecopymerge() and true color images, not with imagecopy() or pallete images.
(PHP 5 >= 5.1.0RC1)
imageconvolution -- Apply a 3x3 convolution matrix, using coefficient div and offsetRestituisce TRUE in caso di successo, FALSE in caso di fallimento.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.
Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y.
Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y. The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to imagecopy() for pallete images, while it implements alpha transparency for true colour images.
Nota: This function was added in PHP 4.0.6
imagecopymergegray() copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y. The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to imagecopy().
This function is identical to imagecopymerge() except that when merging it preserves the hue of the source by converting the destination pixels to gray scale before the copy operation.
Nota: This function was added in PHP 4.0.6
imagecopyresampled() copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
dst_image is the destination image, src_image is the source image identifier. If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_image is the same as src_image) but if the regions overlap the results will be unpredictable.
Nota: There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().
Nota: This function requires GD 2.0.1 or later.
Esempio 1. Simple example This example will resample an image to half its original size.
|
Esempio 2. Resampling an image proportionally This example will display an image with the maximum width, or height, of 200 pixels.
|
imagecopyresized() copies a rectangular portion of one image to another image. dst_image is the destination image, src_image is the source image identifier. If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_image is the same as src_image) but if the regions overlap the results will be unpredictable.
Nota: There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().
Esempio 1. Resizing an image This example will display the image at half size.
The image will be output at half size, though better quality could be obtained using imagecopyresampled(). |
imagecreate() returns an image identifier representing a blank image of size x_size by y_size.
We recommend the use of imagecreatetruecolor().
Esempio 1. Creating a new GD image stream and outputting an image.
|
See also imagedestroy() and imagecreatetruecolor().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: This function requires GD 2.0.1 or later.
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
(PHP 4 >= 4.1.0, PHP 5)
imagecreatefromgd2part -- Create a new image from a given part of GD2 file or URL
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: This function requires GD 2.0.1 or later.
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
imagecreatefromgif() returns an image identifier representing the image obtained from the given filename.
imagecreatefromgif() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error GIF:
Esempio 1. Example to handle an error during creation
|
Nota: GIF support was removed from the GD library in Version 1.6, and added back in Version 2.0.28. This function is not available between these versions.
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
imagecreatefromjpeg() returns an image identifier representing the image obtained from the given filename.
imagecreatefromjpeg() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error JPEG:
Esempio 1. Example to handle an error during creation
|
Nota: JPEG support is only available if PHP was compiled against GD-1.8 or later.
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
imagecreatefrompng() returns an image identifier representing the image obtained from the given filename.
imagecreatefrompng() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error PNG:
Esempio 1. Example to handle an error during creation
|
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
(PHP 4 >= 4.0.4, PHP 5)
imagecreatefromstring -- Create a new image from the image stream in the stringimagecreatefromstring() returns an image identifier representing the image obtained from the given string. These types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, WBMP, and GD2.
An image resource will be returned on success. FALSE is returned if the image type is unsupported, the data is not in a recognised format, or the image is corrupt and cannot be loaded.
Esempio 1. imagecreatefromstring() example
|
imagecreatefromwbmp() returns an image identifier representing the image obtained from the given filename.
imagecreatefromwbmp() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error WBMP:
Esempio 1. Example to handle an error during creation
|
Nota: WBMP support is only available if PHP was compiled against GD-1.8 or later.
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
imagecreatefromxbm() returns an image identifier representing the image obtained from the given filename.
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
imagecreatefromxpm() returns an image identifier representing the image obtained from the given filename.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
imagecreatetruecolor() returns an image identifier representing a black image of size x_size by y_size.
Depending on your PHP and GD versions this function is defined or not. With PHP 4.0.6 through 4.1.x this function always exists if the GD module is loaded, but calling it without GD2 being installed PHP will issue a fatal error and exit. With PHP 4.2.x this behaviour is differnet in issueing a warning instead of an error. Other versions only define this function, if the correct GD version is installed.
Esempio 1. Creating a new GD image stream and outputting an image.
|
Nota: This function requires GD 2.0.1 or later.
Nota: This function will not work with GIF file formats.
See also imagedestroy() and imagecreate().
This function is deprecated. Use combination of imagesetstyle() and imageline() instead.
imagedestroy() frees any memory associated with image image. image is the image identifier returned by one of the image create functions, such as imagecreatetruecolor().
imageellipse() draws an ellipse centered at cx, cy (top left is 0, 0) in the image represented by image. W and h specifies the ellipse's width and height respectively. The color of the ellipse is specified by color.
Nota: This function was added in PHP 4.0.6 and requires GD 2.0.2 or later which can be obtained at http://www.boutell.com/gd/
Esempio 1. imageellipse() example
|
See also imagefilledellipse() and imagearc().
imagefill() performs a flood fill starting at coordinate x, y (top left is 0, 0) with color color in the image image.
imagefilledarc() draws a partial ellipse centered at cx, cy (top left is 0, 0) in the image represented by image. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. W and h specifies the ellipse's width and height respectively while the start and end points are specified in degrees indicated by the s and e arguments. style is a bitwise OR of the following possibilities:
IMG_ARC_PIE
IMG_ARC_CHORD
IMG_ARC_NOFILL
IMG_ARC_EDGED
Esempio 1. Creating a 3D looking pie
|
Nota: This function requires GD 2.0.1 or later.
imagefilledellipse() draws an ellipse centered at cx, cy (top left is 0, 0) in the image represented by image. W and h specifies the ellipse's width and height respectively. The ellipse is filled using color. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. imagefilledellipse() example
|
Nota: This function requires GD 2.0.1 or later.
See also imageellipse() and imagefilledarc().
imagefilledpolygon() creates a filled polygon in image image.
points is an array containing the x and y co-ordinates of the polygons vertices consecutively.
The parameter num_points is the total number of vertices, which must be larger than 3.
Esempio 1. imagefilledpolygon() example
|
imagefilledrectangle() creates a filled rectangle of color color in image image starting at upper left coordinates x1, y1 and ending at bottom right coordinates x2, y2. 0, 0 is the top left corner of the image.
imagefilltoborder() performs a flood fill whose border color is defined by border. The starting point for the fill is x, y (top left is 0, 0) and the region is filled with color color.
imagefilter() applies the filter filtertype to the image, using arg1, arg2 and arg3 where necessary.
filtertype can be one of the following:
IMG_FILTER_NEGATE: Reverses all colors of the image.
IMG_FILTER_GRAYSCALE: Converts the image into grayscale.
IMG_FILTER_BRIGHTNESS: Changes the brightness of the image. Use arg1 to set the level of brightness.
IMG_FILTER_CONTRAST: Changes the contrast of the image. Use arg1 to set the level of contrast.
IMG_FILTER_COLORIZE: Like IMG_FILTER_GRAYSCALE, except you can specify the color. Use arg1, arg2 and arg3 in the form of red, blue, green. The range for each color is 0 to 255.
IMG_FILTER_EDGEDETECT: Uses edge detection to highlight the edges in the image.
IMG_FILTER_EMBOSS: Embosses the image.
IMG_FILTER_GAUSSIAN_BLUR: Blurs the image using the Gaussian method.
IMG_FILTER_SELECTIVE_BLUR: Blurs the image.
IMG_FILTER_MEAN_REMOVAL: Uses mean removal to achieve a "sketchy" effect.
IMG_FILTER_SMOOTH: Makes the image smoother. Use arg1 to set the level of smoothness.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 3. imagefilter() colorize example
|
Returns the pixel height of a character in the specified font.
See also imagefontwidth() and imageloadfont().
Returns the pixel width of a character in font.
See also imagefontheight() and imageloadfont().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: This function requires GD 2.0.1 or later.
Nota: Parameter extrainfo is optional since PHP 4.3.5.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: This function requires GD 2.0.1 or later.
Nota: Parameter extrainfo is optional since PHP 4.3.5.
The imagegammacorrect() function applies gamma correction to a gd image stream (image) given an input gamma, the parameter inputgamma and an output gamma, the parameter outputgamma.
imagegd2() outputs a GD2 image to filename. The image parameter is the return from the imagecreatetruecolor() function.
The filename parameter is optional, and if left off, the raw image stream will be output directly.
The optional type parameter is either IMG_GD2_RAW or IMG_GD2_COMPRESSED. Default is IMG_GD2_RAW.
Nota: The optional chunk_size and type parameters became available in PHP 4.3.2.
Nota: The GD2 format is commonly used to allow fast loading of parts of images. Note that the GD2 format is only usable in GD2-compatible applications.
Nota: This function requires GD 2.0.1 or later.
See also imagegd()
imagegd() outputs a GD image to filename. The image argument is the return from the imagecreatetruecolor() function.
The filename parameter is optional, and if left off, the raw image stream will be output directly.
Nota: The GD format is commonly used to allow fast loading of parts of images. Note that the GD format is only usable in GD-compatible applications.
See also imagegd2().
imagegif() creates the GIF file in filename from the image image. The image argument is the return from the imagecreatetruecolor() function.
The image format will be GIF87a unless the image has been made transparent with imagecolortransparent(), in which case the image format will be GIF89a.
The filename argument is optional, and if left off, the raw image stream will be output directly. By sending an image/gif content-type using header(), you can create a PHP script that outputs GIF images directly.
Nota: Since all GIF support was removed from the GD library in version 1.6, this function is not available if you are using that version of the GD library. Support is expected to return in a version subsequent to the rerelease of GIF support in the GD library in mid 2004. For more information, see the GD Project site.
The following code snippet allows you to write more portable PHP applications by auto-detecting the type of GD support which is available. Replace the sequence header ("Content-type: image/gif"); imagegif ($im); by the more flexible sequence:
<?php if (function_exists("imagegif")) { header("Content-type: image/gif"); imagegif($im); } elseif (function_exists("imagejpeg")) { header("Content-type: image/jpeg"); imagejpeg($im, "", 0.5); } elseif (function_exists("imagepng")) { header("Content-type: image/png"); imagepng($im); } elseif (function_exists("imagewbmp")) { header("Content-type: image/vnd.wap.wbmp"); imagewbmp($im); } else { die("No image support in this PHP server"); } ?>
Nota: As of version 3.0.18 and 4.0.2 you can use the function imagetypes() in place of function_exists() for checking the presence of the various supported image formats:
See also imagepng(), imagewbmp(), imagejpeg() and imagetypes().
imageinterlace() turns the interlace bit on or off. If interlace is 1 the image will be interlaced, and if interlace is 0 the interlace bit is turned off.
If the interlace bit is set and the image is used as a JPEG image, the image is created as a progressive JPEG.
This function returns whether the interlace bit is set for the image.
imageistruecolor() finds whether the image image is a truecolor image.
Nota: This function requires GD 2.0.1 or later.
See also imagecreatetruecolor().
imagejpeg() creates the JPEG file in filename from the image image. The image argument is the return from the imagecreatetruecolor() function.
The filename argument is optional, and if left off, the raw image stream will be output directly. To skip the filename argument in order to provide a quality argument just use an empty string (''). By sending an image/jpeg content-type using header(), you can create a PHP script that outputs JPEG images directly.
Nota: JPEG support is only available if PHP was compiled against GD-1.8 or later.
quality is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).
If you want to output Progressive JPEGs, you need to set interlacing on with imageinterlace().
See also imagepng(), imagegif(), imagewbmp(), imageinterlace() and imagetypes().
(PHP 4 >= 4.3.0, PHP 5)
imagelayereffect -- Set the alpha blending flag to use the bundled libgd layering effectsAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.
Nota: This function requires GD 2.0.1 or later.
imageline() draws a line from x1, y1 to x2, y2 (top left is 0, 0) in image image of color color.
Esempio 1. Drawing a thick line
|
See also imagecreatetruecolor() and imagecolorallocate().
imageloadfont() loads a user-defined bitmap font and returns an identifier for the font (that is always greater than 5, so it will not conflict with the built-in fonts). It returns FALSE in case of error.
The font file format is currently binary and architecture dependent. This means you should generate the font files on the same type of CPU as the machine you are running PHP on.
Tabella 1. Font file format
byte position | C data type | description |
---|---|---|
byte 0-3 | int | number of characters in the font |
byte 4-7 | int | value of first character in the font (often 32 for space) |
byte 8-11 | int | pixel width of each character |
byte 12-15 | int | pixel height of each character |
byte 16- | char | array with character data, one byte per pixel in each character, for a total of (nchars*width*height) bytes. |
Esempio 1. Using imageloadfont
|
See also imagefontwidth() and imagefontheight().
imagepalettecopy() copies the palette from the source image to the destination image.
The imagepng() outputs a GD image stream (image) in PNG format to standard output (usually the browser) or, if a filename is given by the filename it outputs the image to the file.
See also imagegif(), imagewbmp(), imagejpeg(), imagetypes().
imagepolygon() creates a polygon in image id. points is a PHP array containing the polygon's vertices, i.e. points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, etc. num_points is the total number of points (vertices).
Esempio 1. imagepolygon() example
|
See also imagecreate() and imagecreatetruecolor().
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
imagepsbbox -- Give the bounding box of a text rectangle using PostScript Type1 fontssize is expressed in pixels.
space allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative.
tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative.
angle is in degrees.
Parameters space and tightness are expressed in character space units, where 1 unit is 1/1000th of an em-square.
Parameters space, tightness, and angle are optional.
The bounding box is calculated using information available from character metrics, and unfortunately tends to differ slightly from the results achieved by actually rasterizing the text. If the angle is 0 degrees, you can expect the text to need 1 pixel more to every direction.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --with-t1lib.
This function returns an array containing the following elements:
See also imagepstext().
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
imagepscopyfont -- Make a copy of an already loaded font for further modificationUse this function if you need make further modifications to the font, for example extending/condensing, slanting it or changing its character encoding vector, but need to keep the original along as well. Note that the font you want to copy must be one obtained using imagepsloadfont(), not a font that is itself a copied one. You can although make modifications to it before copying.
If you use this function, you must free the fonts obtained this way yourself and in reverse order. Otherwise your script will hang.
In the case everything went right, a valid font index will be returned and can be used for further purposes. Otherwise the function returns FALSE and prints a message describing what went wrong.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --with-t1lib.
See also imagepsloadfont().
Loads a character encoding vector from a file and changes the fonts encoding vector to it. As a PostScript fonts default vector lacks most of the character positions above 127, you'll definitely want to change this if you use an other language than English. The exact format of this file is described in T1libs documentation. T1lib comes with two ready-to-use files, IsoLatin1.enc and IsoLatin2.enc.
If you find yourself using this function all the time, a much better way to define the encoding is to set ps.default_encoding in the configuration file to point to the right encoding file and all fonts you load will automatically have the right encoding.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --with-t1lib.
Extend or condense a font (font_index), if the value of the extend parameter is less than one you will be condensing the font.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --with-t1lib.
imagepsfreefont() frees memory used by a PostScript Type 1 font.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --with-t1lib.
See also imagepsloadfont().
In the case everything went right, a valid font index will be returned and can be used for further purposes. Otherwise the function returns FALSE and prints a message describing what went wrong, which you cannot read directly, while the output type is image.
Esempio 1. imagepsloadfont() example
|
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --with-t1lib.
See also imagepsfreefont().
Slant a font given by the font_index parameter with a slant of the value of the slant parameter.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --with-t1lib.
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
imagepstext -- To draw a text string over an image using PostScript Type1 fontsforeground is the color in which the text will be painted. Background is the color to which the text will try to fade in with antialiasing. No pixels with the color background are actually painted, so the background image does not need to be of solid color.
The coordinates given by x, y will define the origin (or reference point) of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where x, y define the upper-right corner of the first character. Refer to PostScript documentation about fonts and their measuring system if you have trouble understanding how this works.
space allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative.
tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative.
angle is in degrees.
size is expressed in pixels.
antialias_steps allows you to control the number of colours used for antialiasing text. Allowed values are 4 and 16. The higher value is recommended for text sizes lower than 20, where the effect in text quality is quite visible. With bigger sizes, use 4. It's less computationally intensive.
Parameters space and tightness are expressed in character space units, where 1 unit is 1/1000th of an em-square.
Parameters space, tightness, angle and antialias_steps are optional.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --with-t1lib.
This function returns an array containing the following elements:
See also imagepsbbox().
imagerectangle() creates a rectangle of color col in image image starting at upper left coordinate x1, y1 and ending at bottom right coordinate x2, y2. 0, 0 is the top left corner of the image.
Rotates the src_im image using a given angle in degrees. bgd_color specifies the color of the uncovered zone after the rotation.
The center of rotation is the center of the image, and the rotated image is scaled down so that the whole rotated image fits in the destination image - the edges are not clipped.
If ignore_transparent is set and non-zero, transparent colors are ignored (otherwise kept). This parameter was added in PHP 5.1.
Esempio 1. Rotate an image 180 degrees This example rotates an image 180 degrees - upside down.
|
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.
(PHP 4 >= 4.3.2, PHP 5)
imagesavealpha -- Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG imagesimagesavealpha() sets the flag to attempt to save full alpha channel information (as opposed to single-color transparency) when saving PNG images.
You have to unset alphablending (imagealphablending($im, FALSE)), to use it.
Alpha channel is not supported by all browsers, if you have problem with your browser, try to load your script with an alpha channel compliant browser, e.g. latest Mozilla.
Nota: This function requires GD 2.0.1 or later.
See also imagealphablending().
imagesetbrush() sets the brush image to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special colors IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED.
Nota: You need not take special action when you are finished with a brush, but if you destroy the brush image, you must not use the IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED colors until you have set a new brush image!
Nota: This function was added in PHP 4.0.6
imagesetpixel() draws a pixel at x, y (top left is 0, 0) in image image of color color.
See also imagecreatetruecolor() and imagecolorallocate().
imagesetstyle() sets the style to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special color IMG_COLOR_STYLED or lines of images with color IMG_COLOR_STYLEDBRUSHED. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The style parameter is an array of pixels. Following example script draws a dashed line from upper left to lower right corner of the canvas:
Esempio 1. imagesetstyle() example
|
See also imagesetbrush(), imageline().
Nota: This function was added in PHP 4.0.6
imagesetthickness() sets the thickness of the lines drawn when drawing rectangles, polygons, ellipses etc. etc. to thickness pixels. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: This function requires GD 2.0.1 or later.
imagesettile() sets the tile image to be used by all region filling functions (such as imagefill() and imagefilledpolygon()) when filling with the special color IMG_COLOR_TILED.
A tile is an image used to fill an area with a repeated pattern. Any GD image can be used as a tile, and by setting the transparent color index of the tile image with imagecolortransparent(), a tile allows certain parts of the underlying area to shine through can be created.
Nota: You need not take special action when you are finished with a tile, but if you destroy the tile image, you must not use the IMG_COLOR_TILED color until you have set a new tile image!
imagestring() draws the string s in the image identified by image with the upper-left corner at coordinates x, y (top left is 0, 0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.
Esempio 1. imagestring() example
|
See also imageloadfont(), and imagettftext().
imagestringup() draws the string s vertically in the image identified by image at coordinates x, y (top left is 0, 0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.
See also imageloadfont().
imagesx() returns the width of the image identified by image.
See also imagecreatetruecolor(), getimagesize() and imagesy().
imagesy() returns the height of the image identified by image.
See also imagecreatetruecolor(), getimagesize() and imagesx().
imagetruecolortopalette() converts a truecolor image to a palette image. The code for this function was originally drawn from the Independent JPEG Group library code, which is excellent. The code has been modified to preserve as much alpha channel information as possible in the resulting palette, in addition to preserving colors as well as possible. This does not work as well as might be hoped. It is usually best to simply produce a truecolor output image instead, which guarantees the highest output quality.
dither indicates if the image should be dithered - if it is TRUE then dithering will be used which will result in a more speckled image but with better color approximation.
ncolors sets the maximum number of colors that should be retained in the palette.
Nota: This function requires GD 2.0.1 or later.
This function calculates and returns the bounding box in pixels for a TrueType text.
The font size in pixels.
Angle in degrees in which text will be measured.
The name of the TrueType font file (can be a URL). Depending on which version of the GD library that PHP is using, it may attempt to search for files that do not begin with a leading '/' by appending '.ttf' to the filename and searching along a library-defined font path.
The string to be measured.
0 | lower left corner, X position |
1 | lower left corner, Y position |
2 | lower right corner, X position |
3 | lower right corner, Y position |
4 | upper right corner, X position |
5 | upper right corner, Y position |
6 | upper left corner, X position |
7 | upper left corner, Y position |
This function requires both the GD library and the FreeType library.
See also imagettftext().
The image resource. See imagecreatetruecolor().
The font size. Depending on your version of GD, this should be specified as the pixel size (GD1) or point size (GD2).
The angle in degrees, with 0 degrees being left-to-right reading text. Higher values represent a counter-clockwise rotation. For example, a value of 90 would result in bottom-to-top reading text.
The coordinates given by x and y will define the basepoint of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where x and y define the upper-left corner of the first character. For example, "top left" is 0, 0.
The y-ordinate. This sets the position of the fonts baseline, not the very bottom of the character.
The color index. Using the negative of a color index has the effect of turning off antialiasing. See imagecolorallocate().
The path to the TrueType font you wish to use.
Depending on which version of the GD library PHP is using, when fontfile does not begin with a leading / then .ttf will be appended to the filename and the library will attempt to search for that filename along a library-defined font path.
When using versions of the GD library lower than 2.0.18, a space character, rather than a semicolon, was used as the 'path separator' for different font files. Unintentional use of this feature will result in the warning message: Warning: Could not find/open font. For these affected versions, the only solution is moving the font to a path which does not contain spaces.
In many cases where a font resides in the same directory as the script using it the following trick will alleviate any include problems.
<?php // Set the enviroment variable for GD putenv('GDFONTPATH=' . realpath('.')); // Name the font to be used (note the lack of the .ttf extension) $font = 'SomeFont'; ?> |
The text string.
May include decimal numeric character references (of the form: €) to access characters in a font beyond position 127. Strings in UTF-8 encoding can be passed directly.
If a character is used in the string which is not supported by the font, a hollow rectangle will replace the character.
imagettftext() returns an array with 8 elements representing four points making the bounding box of the text. The order of the points is lower left, lower right, upper right, upper left. The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner when you see the text horizontally.
Esempio 1. imagettftext() example This example script will produce a white PNG 400x30 pixels, with the words "Testing..." in black (with grey shadow), in the font Arial.
|
This function requires both the GD library and the FreeType library.
See also imagettfbbox().
(PHP 3 CVS only, PHP 4 >= 4.0.2, PHP 5)
imagetypes -- Return the image types supported by this PHP buildThis function returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP. The following bits are returned, IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM. To check for PNG support, for example, do this:
imagewbmp() creates the WBMP file in filename from the image image. The image argument is the return from the imagecreatetruecolor() function.
The filename argument is optional, and if left off, the raw image stream will be output directly. By sending an image/vnd.wap.wbmp content-type using header(), you can create a PHP script that outputs WBMP images directly.
Nota: WBMP support is only available if PHP was compiled against GD-1.8 or later.
Using the optional foreground parameter, you can set the foreground color. Use an identifier obtained from imagecolorallocate(). The default foreground color is black.
See also image2wbmp(), imagepng(), imagegif(), imagejpeg(), imagetypes().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
iptcparse -- Parse a binary IPTC http://www.iptc.org/ block into single tags.This function parses a binary IPTC block into its single tags. It returns an array using the tagmarker as an index and the value as the value. It returns FALSE on error or if no IPTC data was found. See getimagesize() for a sample.
Converts the jpegname JPEG file to WBMP format, and saves it as wbmpname. With the d_height and d_width you specify the height and width of the destination image.
Nota: JPEG support is only available if PHP was compiled against GD-1.8 or later.
Nota: WBMP support is only available if PHP was compiled against GD-1.8 or later.
See also png2wbmp().
Converts the pngname PNG file to WBMP format, and saves it as wbmpname. With the d_height and d_width you specify the height and width of the destination image.
Nota: WBMP support is only available if PHP was compiled against GD-1.8 or later.
See also jpeg2wbmp().
These functions are not limited to the IMAP protocol, despite their name. The underlying c-client library also supports NNTP, POP3 and local mailbox access methods.
This extension requires the c-client library to be installed. Grab the latest version from ftp://ftp.cac.washington.edu/imap/ and compile it.
It's important that you do not copy the IMAP source files directly into the system include directory as there may be conflicts. Instead, create a new directory inside the system include directory, such as /usr/local/imap-2000b/ (location and name depend on your setup and IMAP version), and inside this new directory create additional directories named lib/ and include/. From the c-client directory from your IMAP source tree, copy all the *.h files into include/ and all the *.c files into lib/. Additionally when you compiled IMAP, a file named c-client.a was created. Also put this in the lib/ directory but rename it as libc-client.a.
Nota: To build the c-client library with SSL or/and Kerberos support read the docs supplied with the package.
Nota: In Mandrake Linux, the IMAP library (libc-client.a) is compiled without Kerberos support. A separate version with SSL (client-PHP4.a) is installed. The library must be recompiled in order to add Kerberos support.
To get these functions to work, you have to compile PHP with --with-imap[=DIR], where DIR is the c-client install prefix. From our example above, you would use --with-imap=/usr/local/imap-2000b. This location depends on where you created this directory according to the description above. Windows users may include the php_imap.dll DLL in php.ini. IMAP is not supported on systems earlier that Windows 2000. This is because it uses encryption functions in order to enable SSL connections to the mail servers.
Nota: Depending how the c-client was configured, you might also need to add --with-imap-ssl=/path/to/openssl/ and/or --with-kerberos=/path/to/kerberos into the PHP configure line.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Open mailbox read-only
Don't use or update a .newsrc for news (NNTP only)
For IMAP and NNTP names, open a connection but don't open a mailbox.
silently expunge the mailbox before closing when calling imap_close()
The parameter is a UID
Do not set the \Seen flag if not already set
The return string is in internal format, will not canonicalize to CRLF.
The sequence argument contains UIDs instead of sequence numbers
the sequence numbers contain UIDS
Delete the messages from the current mailbox after copying with imap_mail_copy()
Return UIDs instead of sequence numbers
Don't prefetch searched messages
This mailbox has no "children" (there are no mailboxes below this one).
This is only a container, not a mailbox - you cannot open it.
This mailbox is marked. Only used by UW-IMAPD.
This mailbox is not marked. Only used by UW-IMAPD.
Sort criteria for imap_sort(): message Date
Sort criteria for imap_sort(): arrival date
Sort criteria for imap_sort(): mailbox in first From address
Sort criteria for imap_sort(): message subject
Sort criteria for imap_sort(): mailbox in first To address
Sort criteria for imap_sort(): mailbox in first cc address
Sort criteria for imap_sort(): size of message in octets
This document can't go into detail on all the topics touched by the provided functions. Further information is provided by the documentation of the c-client library source (docs/internal.txt). and the following RFC documents:
RFC2821: Simple Mail Transfer Protocol (SMTP).
RFC2822: Standard for ARPA internet text messages.
RFC2060: Internet Message Access Protocol (IMAP) Version 4rev1.
RFC1939: Post Office Protocol Version 3 (POP3).
RFC977: Network News Transfer Protocol (NNTP).
RFC2076: Common Internet Message Headers.
RFC2045 , RFC2046 , RFC2047 , RFC2048 & RFC2049: Multipurpose Internet Mail Extensions (MIME).
Convert an 8bit string to a quoted-printable string (according to RFC2045, section 6.7).
Returns a quoted-printable string.
See also imap_qprint().
(PHP 3 >= 3.0.12, PHP 4, PHP 5)
imap_alerts -- This function returns all IMAP alert messages (if any) that have occurred during this page request or since the alert stack was resetThis function returns an array of all of the IMAP alert messages generated since the last imap_alerts() call, or the beginning of the page. When imap_alerts() is called, the alert stack is subsequently cleared. The IMAP specification requires that these messages be passed to the user.
imap_append() appends a string message to the specified mailbox mbox. If the optional options is specified, writes the options to that mailbox also.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
When talking to the Cyrus IMAP server, you must use "\r\n" as your end-of-line terminator instead of "\n" or the operation will fail.
Esempio 1. imap_append() example
|
imap_base64() function decodes BASE-64 encoded text (see RFC2045, Section 6.8). The decoded message is returned as a string.
See also imap_binary(), base64_encode() and base64_decode().
Convert an 8bit string to a base64 string (according to RFC2045, Section 6.8).
Returns a base64 string.
See also imap_base64().
imap_body() returns the body of the message, numbered msg_number in the current mailbox.
The optional options are a bit mask with one or more of the following:
FT_UID - The msg_number is a UID
FT_PEEK - Do not set the \Seen flag if not already set
FT_INTERNAL - The return string is in internal format, will not canonicalize to CRLF.
imap_body() will only return a verbatim copy of the message body. To extract single parts of a multipart MIME-encoded message you have to use imap_fetchstructure() to analyze its structure and imap_fetchbody() to extract a copy of a single body component.
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
imap_bodystruct -- Read the structure of a specified body section of a specific message
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Returns information about the current mailbox. Returns FALSE on failure.
The imap_check() function checks the current mailbox status on the server and returns the information in an object with following properties:
Date - current system time formatted according to RFC822
Driver - protocol used to access this mailbox: POP3, IMAP, NNTP
Mailbox - the mailbox name
Nmsgs - number of messages in the mailbox
Recent - number of recent messages in the mailbox
Esempio 1. imap_check() example
this will output :
|
This function causes a store to delete the specified flag to the flags set for the messages in the specified sequence. The flags which you can unset are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", and "\\Draft" (as defined by RFC2060). Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
options are a bit mask and may contain the single option:
ST_UID - The sequence argument contains UIDs instead of sequence numbers
See also: imap_setflag_full().
Closes the imap stream. Takes an optional flag CL_EXPUNGE, which will silently expunge the mailbox before closing, removing all messages marked for deletion.
See also: imap_open().
imap_createmailbox() creates a new mailbox specified by mbox. Names containing international characters should be encoded by imap_utf7_encode()
Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
Esempio 1. imap_createmailbox() example
|
See also imap_renamemailbox(), imap_deletemailbox() and imap_open() for the format of mbox names.
Returns TRUE.
imap_delete() marks messages listed in msg_number for deletion. The optional flags parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID. Messages marked for deletion will stay in the mailbox until either imap_expunge() is called or imap_close() is called with the optional parameter CL_EXPUNGE.
Nota: POP3 mailboxes do not have their message flags saved between connections, so imap_expunge() must be called during the same connection in order for messages marked for deletion to actually be purged.
Esempio 1. imap_delete() example
|
See also: imap_undelete(), imap_expunge(), and imap_close().
imap_deletemailbox() deletes the specified mailbox (see imap_open() for the format of mbox names).
Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
See also imap_createmailbox(), imap_renamemailbox(), and imap_open() for the format of mbox.
(PHP 3 >= 3.0.12, PHP 4, PHP 5)
imap_errors -- This function returns all of the IMAP errors (if any) that have occurred during this page request or since the error stack was resetThis function returns an array of all of the IMAP error messages generated since the last imap_errors() call, or the beginning of the page. When imap_errors() is called, the error stack is subsequently cleared.
See also: imap_last_error().
imap_expunge() deletes all the messages marked for deletion by imap_delete(), imap_mail_move(), or imap_setflag_full().
Returns TRUE.
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
imap_fetch_overview -- Read an overview of the information in the headers of the given messageThis function fetches mail headers for the given sequence and returns an overview of their contents. sequence will contain a sequence of message indices or UIDs, if flags contains FT_UID. The returned value is an array of objects describing one message header each:
subject - the messages subject
from - who sent it
to - recipient
date - when was it sent
message_id - Message-ID
references - is a reference to this message id
in_reply_to - is a reply to this message id
size - size in bytes
uid - UID the message has in the mailbox
msgno - message sequence number in the mailbox
recent - this message is flagged as recent
flagged - this message is flagged
answered - this message is flagged as answered
deleted - this message is flagged for deletion
seen - this message is flagged as already read
draft - this message is flagged as being a draft
Esempio 1. imap_fetch_overview() example
|
This function causes a fetch of a particular section of the body of the specified messages as a text string and returns that text string. The section specification is a string of integers delimited by period which index into a body part list as per the IMAP4 specification. Body parts are not decoded by this function.
The options for imap_fetchbody() is a bitmask with one or more of the following:
FT_UID - The msg_number is a UID
FT_PEEK - Do not set the \Seen flag if not already set
FT_INTERNAL - The return string is in internal format, will not canonicalize to CRLF.
See also: imap_fetchstructure().
This function causes a fetch of the complete, unfiltered RFC2822 format header of the specified message as a text string and returns that text string.
The options are:
FT_UID - The msgno argument is a UID
FT_INTERNAL - The return string is in "internal" format, without any attempt to canonicalize to CRLF newlines
FT_PREFETCHTEXT - The RFC822.TEXT should be pre-fetched at the same time. This avoids an extra RTT on an IMAP connection if a full message text is desired (e.g. in a "save to local file" operation)
This function fetches all the structured information for a given message. The optional options parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID. The returned object includes the envelope, internal date, size, flags and body structure along with a similar object for each mime attachment. The structure of the returned objects is as follows:
Tabella 1. Returned Objects for imap_fetchstructure()
type | Primary body type |
encoding | Body transfer encoding |
ifsubtype | TRUE if there is a subtype string |
subtype | MIME subtype |
ifdescription | TRUE if there is a description string |
description | Content description string |
ifid | TRUE if there is an identification string |
id | Identification string |
lines | Number of lines |
bytes | Number of bytes |
ifdisposition | TRUE if there is a disposition string |
disposition | Disposition string |
ifdparameters | TRUE if the dparameters array exists |
dparameters | An array of objects where each object has an "attribute" and a "value" property corresponding to the parameters on the Content-disposition MIMEheader. |
ifparameters | TRUE if the parameters array exists |
parameters | An array of objects where each object has an "attribute" and a "value" property. |
parts | An array of objects identical in structure to the top-level object, each of which corresponds to a MIME body part. |
See also: imap_fetchbody().
(PHP 4 >= 4.0.5, PHP 5)
imap_get_quota -- Retrieve the quota level settings, and usage statics per mailboxReturns an array with integer values limit and usage for the given mailbox. The value of limit represents the total amount of space allowed for this mailbox. The usage value represents the mailboxes current level of capacity. Will return FALSE in the case of failure.
This function is currently only available to users of the c-client2000 or greater library.
NOTE: For this function to work, the mail stream is required to be opened as the mail-admin user. For a non-admin user version of this function, please see the imap_get_quotaroot() function of PHP.
imap_stream should be the value returned from an imap_open() call. NOTE: This stream is required to be opened as the mail admin user for the get_quota function to work. quota_root should normally be in the form of user.name where name is the mailbox you wish to retrieve information about.
Esempio 1. imap_get_quota() example
|
As of PHP 4.3, the function more properly reflects the functionality as dictated by the RFC 2087. The array return value has changed to support an unlimited number of returned resources (i.e. messages, or sub-folders) with each named resource receiving an individual array key. Each key value then contains an another array with the usage and limit values within it. The example below shows the updated returned output.
For backwards compatibility reasons, the original access methods are still available for use, although it is suggested to update.
Esempio 2. imap_get_quota() 4.3 or greater example
|
See also imap_open(), imap_set_quota() and imap_get_quotaroot().
Returns an array of integer values pertaining to the specified user mailbox. All values contain a key based upon the resource name, and a corresponding array with the usage and limit values within.
The limit value represents the total amount of space allowed for this user's total mailbox usage. The usage value represents the user's current total mailbox capacity. This function will return FALSE in the case of call failure, and an array of information about the connection upon an un-parsable response from the server.
This function is currently only available to users of the c-client2000 or greater library.
imap_stream should be the value returned from an imap_open() call. This stream should be opened as the user whose mailbox you wish to check. quota_root should normally be in the form of which mailbox (i.e. INBOX).
Esempio 1. imap_get_quotaroot() example
|
See also imap_open(), imap_set_quota() and imap_get_quota().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
This function is currently only available to users of the c-client2000 or greater library.
See also imap_setacl().
(PHP 3 >= 3.0.12, PHP 4, PHP 5)
imap_getmailboxes -- Read the list of mailboxes, returning detailed information on each oneReturns an array of objects containing mailbox information. Each object has the attributes name, specifying the full name of the mailbox; delimiter, which is the hierarchy delimiter for the part of the hierarchy this mailbox is in; and attributes. Attributes is a bitmask that can be tested against:
LATT_NOINFERIORS - This mailbox has no "children" (there are no mailboxes below this one).
LATT_NOSELECT - This is only a container, not a mailbox - you cannot open it.
LATT_MARKED - This mailbox is marked. Only used by UW-IMAPD.
LATT_UNMARKED - This mailbox is not marked. Only used by UW-IMAPD.
Mailbox names containing international Characters outside the printable ASCII range will be encoded and may be decoded by imap_utf7_decode().
ref should normally be just the server specification as described in imap_open(), and pattern specifies where in the mailbox hierarchy to start searching. If you want all mailboxes, pass '*' for pattern.
There are two special characters you can pass as part of the pattern: '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.
Esempio 1. imap_getmailboxes() example
|
See also imap_getsubscribed().
This function is identical to imap_getmailboxes(), except that it only returns mailboxes that the user is subscribed to.
This function returns an object of various header elements.
remail, date, Date, subject, Subject, in_reply_to, message_id,
newsgroups, followup_to, references
message flags:
Recent - 'R' if recent and seen,
'N' if recent and not seen,
' ' if not recent
Unseen - 'U' if not seen AND not recent,
' ' if seen OR not seen and recent
Answered -'A' if answered,
' ' if unanswered
Deleted - 'D' if deleted,
' ' if not deleted
Draft - 'X' if draft,
' ' if not draft
Flagged - 'F' if flagged,
' ' if not flagged
NOTE that the Recent/Unseen behavior is a little odd. If you want to
know if a message is Unseen, you must check for
Unseen == 'U' || Recent == 'N'
toaddress (full to: line, up to 1024 characters)
to[] (returns an array of objects from the To line, containing):
personal
adl
mailbox
host
fromaddress (full from: line, up to 1024 characters)
from[] (returns an array of objects from the From line, containing):
personal
adl
mailbox
host
ccaddress (full cc: line, up to 1024 characters)
cc[] (returns an array of objects from the Cc line, containing):
personal
adl
mailbox
host
bccaddress (full bcc line, up to 1024 characters)
bcc[] (returns an array of objects from the Bcc line, containing):
personal
adl
mailbox
host
reply_toaddress (full reply_to: line, up to 1024 characters)
reply_to[] (returns an array of objects from the Reply_to line,
containing):
personal
adl
mailbox
host
senderaddress (full sender: line, up to 1024 characters)
sender[] (returns an array of objects from the sender line, containing):
personal
adl
mailbox
host
return_path (full return-path: line, up to 1024 characters)
return_path[] (returns an array of objects from the return_path line,
containing):
personal
adl
mailbox
host
udate (mail message date in unix time)
fetchfrom (from line formatted to fit fromlength
characters)
fetchsubject (subject line formatted to fit subjectlength characters)
Returns an array of string formatted with header info. One element per mail message.
(PHP 3 >= 3.0.12, PHP 4, PHP 5)
imap_last_error -- This function returns the last IMAP error (if any) that occurred during this page requestThis function returns the full text of the last IMAP error message that occurred on the current page. The error stack is untouched; calling imap_last_error() subsequently, with no intervening errors, will return the same error.
See also: imap_errors().
Returns an array containing the names of the mailboxes. See imap_getmailboxes() for a description of ref and pattern.
Esempio 1. imap_list() example
|
See also: imap_getmailboxes().
(no version information, might be only in CVS)
imap_listscan -- Read the list of mailboxes, takes a string to search for in the text of the mailboxReturns an array containing the names of the mailboxes that have content in the text of the mailbox.
This function is similar to imap_listmailbox(), but it will additionally check for the presence of the string content inside the mailbox data.
See imap_getmailboxes() for a description of ref and pattern.
Returns an array of all the mailboxes that you have subscribed.
(PHP 3 >= 3.0.5, PHP 4, PHP 5)
imap_mail_compose -- Create a MIME message based on given envelope and body sections
Esempio 1. imap_mail_compose() example
|
Copies mail messages specified by msglist to specified mailbox. Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
msglist is a range not just message numbers (as described in RFC2060).
options is a bitmask of one or more of
CP_UID - the sequence numbers contain UIDS
CP_MOVE - Delete the messages from the current mailbox after copying
See also imap_mail_move().
Moves mail messages specified by msglist to specified mailbox mbox. Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
msglist is a range not just message numbers (as described in RFC2060).
options is a bitmask and may contain the single option:
CP_UID - the sequence numbers contain UIDS
See also imap_mail_copy().
This function allows sending of emails with correct handling of Cc and Bcc receivers. Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
The parameters to, cc and bcc are all strings and are all parsed as rfc822 address lists.
The receivers specified in bcc will get the mail, but are excluded from the headers.
Use the rpath parameter to specify return path. This is useful when using PHP as a mail client for multiple users.
Returns information about the current mailbox. Returns FALSE on failure.
The imap_mailboxmsginfo() function checks the current mailbox status on the server. It is similar to imap_status(), but will additionally sum up the size of all messages in the mailbox, which will take some additional time to execute. It returns the information in an object with following properties.
Tabella 1. Mailbox properties
Date | date of last change |
Driver | driver |
Mailbox | name of the mailbox |
Nmsgs | number of messages |
Recent | number of recent messages |
Unread | number of unread messages |
Deleted | number of deleted messages |
Size | mailbox size |
Esempio 1. imap_mailboxmsginfo() example
|
imap_mime_header_decode() function decodes MIME message header extensions that are non ASCII text (see RFC2047). The decoded elements are returned in an array of objects, where each object has two properties, "charset" and "text". If the element hasn't been encoded, and in other words is in plain US-ASCII,the "charset" property of that element is set to "default".
In the above example we would have two elements, whereas the first element had previously been encoded with ISO-8859-1, and the second element would be plain US-ASCII.
(PHP 3 >= 3.0.3, PHP 4, PHP 5)
imap_msgno -- This function returns the message sequence number for the given UIDThis function returns the message sequence number for the given uid. It is the inverse of imap_uid().
See also imap_uid().
Return the number of messages in the current mailbox.
See also: imap_num_recent() and imap_status().
Returns the number of recent messages in the current mailbox.
See also: imap_num_msg() and imap_status().
Returns an IMAP stream on success and FALSE on error. This function can also be used to open streams to POP3 and NNTP servers, but some functions and features are only available on IMAP servers.
A mailbox name consists of a server part and a mailbox path on this server. The special name INBOX stands for the current users personal mailbox. The server part, which is enclosed in '{' and '}', consists of the servers name or ip address, an optional port (prefixed by ':'), and an optional protocol specification (prefixed by '/'). The server part is mandatory in all mailbox parameters. Mailbox names that contain international characters besides those in the printable ASCII space have to be encoded with imap_utf7_encode().
All names which start with { are remote names, and are in the form "{" remote_system_name [":" port] [flags] "}" [mailbox_name] where:
remote_system_name - Internet domain name or bracketed IP address of server.
port - optional TCP port number, default is the default port for that service
flags - optional flags, see following table.
mailbox_name - remote mailbox name, default is INBOX
Tabella 1. Optional flags for names
Flag | Description |
---|---|
/service=service | mailbox access service, default is "imap" |
/user=user | remote user name for login on the server |
/authuser=user | remote authentication user; if specified this is the user name whose password is used (e.g. administrator) |
/anonymous | remote access as anonymous user |
/debug | record protocol telemetry in application's debug log |
/secure | do not transmit a plaintext password over the network |
/imap, /imap2, /imap2bis, /imap4, /imap4rev1 | equivalent to /service=imap |
/pop3 | equivalent to /service=pop3 |
/nntp | equivalent to /service=nntp |
/norsh | do not use rsh or ssh to establish a preauthenticated IMAP session |
/ssl | use the Secure Socket Layer to encrypt the session |
/validate-cert | validate certificates from TLS/SSL server (this is the default behavior) |
/novalidate-cert | do not validate certificates from TLS/SSL server, needed if server uses self-signed certificates |
/tls | force use of start-TLS to encrypt the session, and reject connection to servers that do not support it |
/notls | do not do start-TLS to encrypt the session, even with servers that support it |
/readonly | request read-only mailbox open (IMAP only; ignored on NNTP, and an error with SMTP and POP3) |
The options are a bit mask with one or more of the following:
OP_READONLY - Open mailbox read-only
OP_ANONYMOUS - Don't use or update a .newsrc for news (NNTP only)
OP_HALFOPEN - For IMAP and NNTP names, open a connection but don't open a mailbox.
CL_EXPUNGE - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())
OP_DEBUG - Debug protocol negotiations
OP_SHORTCACHE - Short (elt-only) caching
OP_SILENT - Don't pass up events (internal use)
OP_PROTOTYPE - Return driver prototype
OP_EXPUNGE - Silently expunge recycle stream
OP_SECURE - Don't do non-secure authentication
Esempio 1. Different use of imap_open()
|
Esempio 2. imap_open() example
|
Returns TRUE if the stream is still alive, FALSE otherwise.
imap_ping() pings the stream to see if it's still active. It may discover new mail; this is the preferred method for a periodic "new mail check" as well as a "keep alive" for servers which have inactivity timeout.
Convert a quoted-printable string to an 8 bit string (according to RFC2045, section 6.7).
See also imap_8bit().
This function renames on old mailbox to new mailbox (see imap_open() for the format of mbox names).
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also imap_createmailbox(), imap_deletemailbox(), and imap_open() for the format of mbox.
This function reopens the specified stream to a new mailbox on an IMAP or NNTP server.
The options are a bit mask with one or more of the following:
OP_READONLY - Open mailbox read-only
OP_ANONYMOUS - Don't use or update a .newsrc for news (NNTP only)
OP_HALFOPEN - For IMAP and NNTP names, open a connection but don't open a mailbox.
CL_EXPUNGE - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
This function parses the address string as defined in RFC2822 and for each address, returns an array of objects. The objects properties are:
mailbox - the mailbox name (username)
host - the host name
personal - the personal name
adl - at domain source route
Esempio 1. imap_rfc822_parse_adrlist() example
|
This function returns an object of various header elements, similar to imap_header(), except without the flags and other elements that come from the IMAP server.
(PHP 3 >= 3.0.2, PHP 4, PHP 5)
imap_rfc822_write_address -- Returns a properly formatted email address given the mailbox, host, and personal infoReturns a properly formatted email address as defined in RFC2822 given the mailbox, host, and personal info.
(PHP 3 >= 3.0.12, PHP 4, PHP 5)
imap_search -- This function returns an array of messages matching the given search criteriaThis function performs a search on the mailbox currently opened in the given imap stream. criteria is a string, delimited by spaces, in which the following keywords are allowed. Any multi-word arguments (e.g. FROM "joey smith") must be quoted.
ALL - return all messages matching the rest of the criteria
ANSWERED - match messages with the \\ANSWERED flag set
BCC "string" - match messages with "string" in the Bcc: field
BEFORE "date" - match messages with Date: before "date"
BODY "string" - match messages with "string" in the body of the message
CC "string" - match messages with "string" in the Cc: field
DELETED - match deleted messages
FLAGGED - match messages with the \\FLAGGED (sometimes referred to as Important or Urgent) flag set
FROM "string" - match messages with "string" in the From: field
KEYWORD "string" - match messages with "string" as a keyword
NEW - match new messages
OLD - match old messages
ON "date" - match messages with Date: matching "date"
RECENT - match messages with the \\RECENT flag set
SEEN - match messages that have been read (the \\SEEN flag is set)
SINCE "date" - match messages with Date: after "date"
SUBJECT "string" - match messages with "string" in the Subject:
TEXT "string" - match messages with text "string"
TO "string" - match messages with "string" in the To:
UNANSWERED - match messages that have not been answered
UNDELETED - match messages that are not deleted
UNFLAGGED - match messages that are not flagged
UNKEYWORD "string" - match messages that do not have the keyword "string"
UNSEEN - match messages which have not been read yet
For example, to match all unanswered messages sent by Mom, you'd use: "UNANSWERED FROM mom". Searches appear to be case insensitive. This list of criteria is from a reading of the UW c-client source code and may be incomplete or inaccurate (see also RFC2060, section 6.4.4).
Valid values for flags are SE_UID, which causes the returned array to contain UIDs instead of messages sequence numbers.
Parameter charset was added in PHP 4.3.3.
Sets an upper limit quota on a per mailbox basis. This function requires the imap_stream to have been opened as the mail administrator account. It will not work if opened as any other user.
This function is currently only available to users of the c-client2000 or greater library.
imap_stream is the stream pointer returned from a imap_open() call. This stream must be opened as the mail administrator, other wise this function will fail. quota_root is the mailbox to have a quota set. This should follow the IMAP standard format for a mailbox, 'user.name'. quota_limit is the maximum size (in KB) for the quota_root.
Returns TRUE on success and FALSE on error.
See also imap_open() and imap_get_quota().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
This function is currently only available to users of the c-client2000 or greater library.
See also imap_getacl().
This function causes a store to add the specified flag to the flags set for the messages in the specified sequence.
The flags which you can set are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", and "\\Draft" (as defined by RFC2060).
options are a bit mask and may contain the single option:
ST_UID - The sequence argument contains UIDs instead of sequence numbers
See also: imap_clearflag_full().
Returns an array of message numbers sorted by the given parameters.
Reverse is 1 for reverse-sorting.
Criteria can be one (and only one) of the following:
SORTDATE - message Date
SORTARRIVAL - arrival date
SORTFROM - mailbox in first From address
SORTSUBJECT - message subject
SORTTO - mailbox in first To address
SORTCC - mailbox in first cc address
SORTSIZE - size of message in octets
The flags are a bitmask of one or more of the following:
SE_UID - Return UIDs instead of sequence numbers
SE_NOPREFETCH - Don't prefetch searched messages
Parameter charset was added in PHP 4.3.3.
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
imap_status -- This function returns status information on a mailbox other than the current oneThis function returns an object containing status information. Valid flags are:
SA_MESSAGES - set status->messages to the number of messages in the mailbox
SA_RECENT - set status->recent to the number of recent messages in the mailbox
SA_UNSEEN - set status->unseen to the number of unseen (new) messages in the mailbox
SA_UIDNEXT - set status->uidnext to the next uid to be used in the mailbox
SA_UIDVALIDITY - set status->uidvalidity to a constant that changes when uids for the mailbox may no longer be valid
SA_ALL - set all of the above
status->flags is also set, which contains a bitmask which can be checked against any of the above constants.
Esempio 1. imap_status() example
|
Subscribe to a new mailbox.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also: imap_unsubscribe().
imap_thread() returns an associative array containing a tree of messages threaded by REFERENCES, or FALSE on error.
Every message in the current mailbox will be represented by three entries in the resulting array:
$thread["XX.num"] - current message number
$thread["XX.next"]
$thread["XX.branch"]
Esempio 1. imap_thread() Example
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 3 >= 3.0.3, PHP 4, PHP 5)
imap_uid -- This function returns the UID for the given message sequence numberThis function returns the UID for the given message sequence number. An UID is a unique identifier that will not change over time while a message sequence number may change whenever the content of the mailbox changes. This function is the inverse of imap_msgno().
Nota: This is not supported by POP3 mailboxes.
See also: imap_msgno().
This function removes the deletion flag for a specified message, which is set by imap_delete() or imap_mail_move().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also: imap_delete(), and imap_mail_move().
Unsubscribe from a specified mailbox.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also: imap_subscribe().
Decodes modified UTF-7 text into ISO-8859-1 string.
Returns a string that is encoded in ISO-8859-1 and consists of the same sequence of characters in text, or FALSE if text contains invalid modified UTF-7 sequence or text contains a character that is not part of ISO-8859-1 character set.
This function is needed to decode mailbox names that contain certain characters which are not in range of printable ASCII characters.
The modified UTF-7 encoding is defined in RFC 2060, section 5.1.3 (original UTF-7 was defined in RFC1642).
See also: imap_utf7_encode().
(PHP 3 >= 3.0.15, PHP 4, PHP 5)
imap_utf7_encode -- Converts ISO-8859-1 string to modified UTF-7 textConverts data to modified UTF-7 text. Note that data is expected to be encoded in ISO-8859-1.
This is needed to encode mailbox names that contain certain characters which are not in range of printable ASCII characters.
The modified UTF-7 encoding is defined in RFC 2060, section 5.1.3 (original UTF-7 was defined in RFC1642).
See also: imap_utf7_decode().
The Informix driver for Informix (IDS) 7.x, SE 7.x, Universal Server (IUS) 9.x and IDS 2000 is implemented in "ifx.ec" and "php3_ifx.h" in the informix extension directory. IDS 7.x support is fairly complete, with full support for BYTE and TEXT columns. IUS 9.x support is partly finished: the new data types are there, but SLOB and CLOB support is still under construction.
Configuration notes: You need a version of ESQL/C to compile the PHP Informix driver. ESQL/C versions from 7.2x on should be OK. ESQL/C is now part of the Informix Client SDK.
Make sure that the "INFORMIXDIR" variable has been set, and that $INFORMIXDIR/bin is in your PATH before you run the "configure" script.
To be able to use the functions defined in this module you must compile your PHP interpreter using the configure line --with-informix[=DIR], where DIR is the Informix base install directory, defaults to nothing.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Nota: Make sure that the Informix environment variables INFORMIXDIR and INFORMIXSERVER are available to the PHP ifx driver, and that the INFORMIX bin directory is in the PATH. Check this by running a script that contains a call to phpinfo() before you start testing. The phpinfo() output should list these environment variables. This is true for both CGI php and Apache mod_php. You may have to set these environment variables in your Apache startup script.
The Informix shared libraries should also be available to the loader (check LD_LIBRARY_PATH or ld.so.conf/ldconfig).
Some notes on the use of BLOBs (TEXT and BYTE columns): BLOBs are normally addressed by BLOB identifiers. Select queries return a "blob id" for every BYTE and TEXT column. You can get at the contents with "string_var = ifx_get_blob($blob_id);" if you choose to get the BLOBs in memory (with: "ifx_blobinfile(0);"). If you prefer to receive the content of BLOB columns in a file, use "ifx_blobinfile(1);", and "ifx_get_blob($blob_id);" will get you the filename. Use normal file I/O to get at the blob contents.
For insert/update queries you must create these "blob id's" yourself with "ifx_create_blob();". You then plug the blob id's into an array, and replace the blob columns with a question mark (?) in the query string. For updates/inserts, you are responsible for setting the blob contents with ifx_update_blob().
The behaviour of BLOB columns can be altered by configuration variables that also can be set at runtime:
configuration variable: ifx.textasvarchar
configuration variable: ifx.byteasvarchar
runtime functions:
ifx_textasvarchar(0): use blob id's for select queries with TEXT columns
ifx_byteasvarchar(0): use blob id's for select queries with BYTE columns
ifx_textasvarchar(1): return TEXT columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.
ifx_byteasvarchar(1): return BYTE columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.
configuration variable: ifx.blobinfile
runtime function:
ifx_blobinfile_mode(0): return BYTE columns in memory, the blob id lets you get at the contents.
ifx_blobinfile_mode(1): return BYTE columns in a file, the blob id lets you get at the file name.
If you set ifx_text/byteasvarchar to 1, you can use TEXT and BYTE columns in select queries just like normal (but rather long) VARCHAR fields. Since all strings are "counted" in PHP, this remains "binary safe". It is up to you to handle this correctly. The returned data can contain anything, you are responsible for the contents.
If you set ifx_blobinfile to 1, use the file name returned by ifx_get_blob(..) to get at the blob contents. Note that in this case YOU ARE RESPONSIBLE FOR DELETING THE TEMPORARY FILES CREATED BY INFORMIX when fetching the row. Every new row fetched will create new temporary files for every BYTE column.
The location of the temporary files can be influenced by the environment variable "blobdir", default is "." (the current directory). Something like: putenv(blobdir=tmpblob"); will ease the cleaning up of temp files accidentally left behind (their names all start with "blb").
Automatically trimming "char" (SQLCHAR and SQLNCHAR) data: This can be set with the configuration variable
ifx.charasvarchar: if set to 1 trailing spaces will be automatically trimmed, to save you some "chopping".
NULL values: The configuration variable ifx.nullformat (and the runtime function ifx_nullformat()) when set to TRUE will return NULL columns as the string "NULL", when set to FALSE they return the empty string. This allows you to discriminate between NULL columns and empty columns.
Tabella 1. Informix configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
ifx.allow_persistent | "1" | PHP_INI_SYSTEM | |
ifx.max_persistent | "-1" | PHP_INI_SYSTEM | |
ifx.max_links | "-1" | PHP_INI_SYSTEM | |
ifx.default_host | NULL | PHP_INI_SYSTEM | |
ifx.default_user | NULL | PHP_INI_SYSTEM | |
ifx.default_password | NULL | PHP_INI_SYSTEM | |
ifx.blobinfile | "1" | PHP_INI_ALL | |
ifx.textasvarchar | "0" | PHP_INI_ALL | |
ifx.byteasvarchar | "0" | PHP_INI_ALL | |
ifx.charasvarchar | "0" | PHP_INI_ALL | |
ifx.nullformat | "0" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
Whether to allow persistent Informix connections.
The maximum number of persistent Informix connections per process.
The maximum number of Informix connections per process, including persistent connections.
The default host to connect to when no host is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in modalità sicura.
The default user id to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in modalità sicura.
The default password to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in modalità sicura.
Set to TRUE if you want to return blob columns in a file, FALSE if you want them in memory. You can override the setting at runtime with ifx_blobinfile_mode().
Set to TRUE if you want to return TEXT columns as normal strings in select statements, FALSE if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().
Set to TRUE if you want to return BYTE columns as normal strings in select queries, FALSE if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().
Set to TRUE if you want to trim trailing spaces from CHAR columns when fetching them.
Set to TRUE if you want to return NULL columns as the literal string "NULL", FALSE if you want them returned as the empty string "". You can override this setting at runtime with ifx_nullformat().
result_id is a valid result id returned by ifx_query() or ifx_prepare().
Returns the number of rows affected by a query associated with result_id.
For inserts, updates and deletes the number is the real number (sqlerrd[2]) of affected rows. For selects it is an estimate (sqlerrd[0]). Don't rely on it. The database server can never return the actual number of rows that will be returned by a SELECT because it has not even begun fetching them at this stage (just after the "PREPARE" when the optimizer has determined the query plan).
Useful after ifx_prepare() to limit queries to reasonable result sets.
Esempio 1. Informix affected rows
|
See also ifx_num_rows().
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
ifx_blobinfile_mode -- Set the default blob mode for all select queriesSet the default blob mode for all select queries. Mode "0" means save Byte-Blobs in memory, and mode "1" means save Byte-Blobs in a file.
Sets the default byte mode for all select-queries. Mode "0" will return a blob id, and mode "1" will return a varchar with text content.
Returns: always TRUE.
ifx_close() closes the link to an Informix database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.
Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
ifx_close() will not close persistent links generated by ifx_pconnect().
See also ifx_connect() and ifx_pconnect().
Returns a connection identifier on success, or FALSE on error.
ifx_connect() establishes a connection to an Informix server. All of the arguments are optional, and if they're missing, defaults are taken from values supplied in configuration file (ifx.default_host for the host (Informix libraries will use INFORMIXSERVER environment value if not defined), ifx.default_user for user, ifx.default_password for the password (none if not defined).
In case a second call is made to ifx_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.
The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling ifx_close().
See also ifx_pconnect() and ifx_close().
Duplicates the given blob object. bid is the ID of the blob object.
Returns FALSE on error otherwise the new blob object-id.
Creates an blob object.
type: 1 = TEXT, 0 = BYTE
mode: 0 = blob-object holds the content in memory, 1 = blob-object holds the content in file.
param: if mode = 0: pointer to the content, if mode = 1: pointer to the filestring.
Return FALSE on error, otherwise the new blob object-id.
Creates an char object. param should be the char content.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Executes a previously prepared query or opens a cursor for it.
Does NOT free result_id on error.
Also sets the real number of ifx_affected_rows() for non-select statements for retrieval by ifx_affected_rows()
See also: ifx_prepare().
The Informix error codes (SQLSTATE & SQLCODE) formatted as follows :
x [SQLSTATE = aa bbb SQLCODE=cccc]
where x = space : no error
E : error
N : no more data
W : warning
? : undefined
If the "x" character is anything other than space, SQLSTATE and SQLCODE describe the error in more detail.
See the Informix manual for the description of SQLSTATE and SQLCODE
Returns in a string one character describing the general results of a statement and both SQLSTATE and SQLCODE associated with the most recent SQL statement executed. The format of the string is "(char) [SQLSTATE=(two digits) (three digits) SQLCODE=(one digit)]". The first character can be ' ' (space) (success), 'W' (the statement caused some warning), 'E' (an error happened when executing the statement) or 'N' (the statement didn't return any data).
See also: ifx_errormsg()
Returns the Informix error message associated with the most recent Informix error, or, when the optional "errorcode" parameter is present, the error message corresponding to "errorcode".
See also ifx_error().
Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.
Blob columns are returned as integer blob id values for use in ifx_get_blob() unless you have used ifx_textasvarchar(1) or ifx_byteasvarchar(1), in which case blobs are returned as string values. Returns FALSE on error
result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).
position is an optional parameter for a "fetch" operation on "scroll" cursors: "NEXT", "PREVIOUS", "CURRENT", "FIRST", "LAST" or a number. If you specify a number, an "absolute" row fetch is executed. This parameter is optional, and only valid for SCROLL cursors.
ifx_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0, with the column name as key.
Subsequent calls to ifx_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.
Esempio 1. Informix fetch rows
|
Returns an associative array with fieldnames as key and the SQL fieldproperties as data for a query with result_id. Returns FALSE on error.
Returns the Informix SQL fieldproperties of every field in the query as an associative array. Properties are encoded as: "SQLTYPE;length;precision;scale;ISNULLABLE" where SQLTYPE = the Informix type like "SQLVCHAR" etc. and ISNULLABLE = "Y" or "N".
Returns an associative array with fieldnames as key and the SQL fieldtypes as data for query with result_id. Returns FALSE on error.
Deletes the blobobject for the given blob object-id bid. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Deletes the charobject for the given char object-id bid. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Releases resources for the query associated with result_id. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Returns the content of the blob object for the given blob object-id bid.
Returns the content of the char object for the given char object-id bid.
result_id is a valid result id returned by ifx_query() or ifx_prepare().
Returns a pseudo-row (associative array) with sqlca.sqlerrd[0] ... sqlca.sqlerrd[5] after the query associated with result_id.
For inserts, updates and deletes the values returned are those as set by the server after executing the query. This gives access to the number of affected rows and the serial insert value. For SELECTs the values are those saved after the PREPARE statement. This gives access to the *estimated* number of affected rows. The use of this function saves the overhead of executing a "select dbinfo('sqlca.sqlerrdx')" query, as it retrieves the values that were saved by the ifx driver at the appropriate moment.
Esempio 1. Retrieve Informix sqlca.sqlerrd[x] values
|
Returns the number of rows fetched or FALSE on error.
Formats all rows of the result_id query into a HTML table. The optional second argument is a string of <table> tag options
Esempio 1. Informix results as HTML table
|
Sets the default return value of a NULL-value on a fetch row. Mode "0" returns "", and mode "1" returns "NULL".
Returns the number of columns in query for result_id or FALSE on error
After preparing or executing a query, this call gives you the number of columns in the query.
Gives the number of rows fetched so far for a query with result_id after a ifx_query() or ifx_do() query.
Returns: A positive Informix persistent link identifier on success, or FALSE on error
ifx_pconnect() acts very much like ifx_connect() with two major differences.
This function behaves exactly like ifx_connect() when PHP is not running as an Apache module. First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ifx_close() will not close links established by ifx_pconnect()).
This type of links is therefore called 'persistent'.
See also: ifx_connect().
Returns an integer result_id for use by ifx_do(). Sets affected_rows for retrieval by the ifx_affected_rows() function.
Prepares query on connection conn_id. For "select-type" queries a cursor is declared and opened. The optional cursor_type parameter allows you to make this a "scroll" and/or "hold" cursor. It's a bitmask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together.
For either query type the estimated number of affected rows is saved for retrieval by ifx_affected_rows().
If you have BLOB (BYTE or TEXT) columns in the query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.
If the contents of the TEXT (or BYTE) column allow it, you can also use "ifx_textasvarchar(1)" and "ifx_byteasvarchar(1)". This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.
With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).
See also: ifx_do().
Returns a positive Informix result identifier on success, or FALSE on error.
A "result_id" resource used by other functions to retrieve the query results. Sets "affected_rows" for retrieval by the ifx_affected_rows() function.
ifx_query() sends a query to the currently active database on the server that's associated with the specified link identifier.
Executes query on connection conn_id. For "select-type" queries a cursor is declared and opened. The optional cursor_type parameter allows you to make this a "scroll" and/or "hold" cursor. It's a bitmask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together. Non-select queries are "execute immediate". IFX_SCROLL and IFX_HOLD are symbolic constants and as such shouldn't be between quotes. I you omit this parameter the cursor is a normal sequential cursor.
For either query type the number of (estimated or real) affected rows is saved for retrieval by ifx_affected_rows().
If you have BLOB (BYTE or TEXT) columns in an update query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.
If the contents of the TEXT (or BYTE) column allow it, you can also use "ifx_textasvarchar(1)" and "ifx_byteasvarchar(1)". This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.
With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).
Esempio 1. Show all rows of the "orders" table as a HTML table
|
Esempio 2. Insert some values into the "catalog" table
|
See also ifx_connect().
Sets the default text mode for all select-queries. Mode "0" will return a blob id, and mode "1" will return a varchar with text content.
Updates the content of the blob object for the given blob object bid. content is a string with new data. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Updates the content of the char object for the given char object bid. content is a string with new data. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Deletes the slob object on the given slob object-id bid. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Creates an slob object and opens it. Modes: 1 = LO_RDONLY, 2 = LO_WRONLY, 4 = LO_APPEND, 8 = LO_RDWR, 16 = LO_BUFFER, 32 = LO_NOBUFFER -> or-mask. You can also use constants named IFX_LO_RDONLY, IFX_LO_WRONLY etc. Return FALSE on error otherwise the new slob object-id.
Deletes the slob object. bid is the Id of the slob object. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Opens an slob object. bid should be an existing slob id. Modes: 1 = LO_RDONLY, 2 = LO_WRONLY, 4 = LO_APPEND, 8 = LO_RDWR, 16 = LO_BUFFER, 32 = LO_NOBUFFER -> or-mask. Returns FALSE on error otherwise the new slob object-id.
Reads nbytes of the slob object. bid is a existing slob id and nbytes is the number of bytes read. Return FALSE on error otherwise the string.
Sets the current file or seek position of an open slob object. bid should be an existing slob id. Modes: 0 = LO_SEEK_SET, 1 = LO_SEEK_CUR, 2 = LO_SEEK_END and offset is an byte offset. Return FALSE on error otherwise the seek position.
Returns the current file or seek position of an open slob object bid should be an existing slob id. Return FALSE on error otherwise the seek position.
These functions allow you to access Ingres II database servers.
Nota: If you already used PHP extensions to access other database servers, note that Ingres doesn't allow concurrent queries and/or transaction over one connection, thus you won't find any result or transaction handle in this extension. The result of a query must be treated before sending another query, and a transaction must be committed or rolled back before opening another transaction (which is automatically done when sending the first query).
To compile PHP with Ingres support, you need the Open API library and header files included with Ingres II.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/ingres.
In order to have these functions available, you must compile PHP with Ingres support by using the --with-ingres[=DIR] option, where DIR is the Ingres base directory, which defaults to /II/ingres. If the II_SYSTEM environment variable isn't correctly set you may have to use --with-ingres=DIR to specify your Ingres installation directory.
When using this extension with Apache, if Apache does not start and complains with "PHP Fatal error: Unable to start ingres_ii module in Unknown on line 0" then make sure the environment variable II_SYSTEM is correctly set. Adding "export II_SYSTEM="/home/ingres/II" in the script that starts Apache, just before launching httpd, should be fine.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Ingres configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
ingres.allow_persistent | "1" | PHP_INI_SYSTEM | Available since PHP 4.0.2. |
ingres.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 4.0.2. |
ingres.max_links | "-1" | PHP_INI_SYSTEM | Available since PHP 4.0.2. |
ingres.default_database | NULL | PHP_INI_ALL | Available since PHP 4.0.2. |
ingres.default_user | NULL | PHP_INI_ALL | Available since PHP 4.0.2. |
ingres.default_password | NULL | PHP_INI_ALL | Available since PHP 4.0.2. |
ingres.report_db_warnings | "1" | PHP_INI_ALL | Available since version 1.1.0 of the PECL extension. |
ingres.cursor_mode | "0" | PHP_INI_ALL | Available since version 1.1.0 of the PECL extension. |
ingres.blob_segment_length | "4096" | PHP_INI_ALL | Available since version 1.2.0 of the PECL extension. |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Columns are returned into the array having the fieldname as the array index.
Columns are returned into the array having a numerical index to the fields. This index starts with 1, the first field in the result.
Columns are returned into the array having both a numerical index and the fieldname as the array index.
Specifies the version of the Ingres Extension. Available since version 1.2.0 of the PECL extension.
Specifies the version of Ingres OpenAPI the extension was built against. Available since version 1.2.0 of the PECL extension.
Specifies that Ingres cursors should be opened in 'readonly' mode. Available since version 1.2.0 of the PECL extension.
Specifies that Ingres cursors should be opened 'for update'. Available since version 1.2.0 of the PECL extension.
Equivalent to the II_DATE_FORMAT setting of MULTINATIONAL. Available since version 1.2.0 of the PECL extension.
Equivalent to the II_DATE_FORMAT setting of MULTINATIONAL4. Available since version 1.2.0 of the PECL extension.
Equivalent to the II_DATE_FORMAT setting of FINNISH. Available since version 1.2.0 of the PECL extension.
Equivalent to the II_DATE_FORMAT setting of ISO. Available since version 1.2.0 of the PECL extension.
Equivalent to the II_DATE_FORMAT setting of ISO4. Available since version 1.2.0 of the PECL extension.
Equivalent to the II_DATE_FORMAT setting of GERMAN. Available since version 1.2.0 of the PECL extension.
Equivalent to the II_DATE_FORMAT setting of MDY. Available since version 1.2.0 of the PECL extension.
Equivalent to the II_DATE_FORMAT setting of DMY. Available since version 1.2.0 of the PECL extension.
Equivalent to the II_DATE_FORMAT setting of YMD. Available since version 1.2.0 of the PECL extension.
Speifies the currency character should be placed a the start of a money value. Equivalent to setting II_MONEY_FORMAT to 'L:'. Available since version 1.2.0 of the PECL extension.
Speifies the currency character should be placed a the end of a money value. Equivalent to setting II_MONEY_FORMAT to 'T:'. Available since version 1.2.0 of the PECL extension.
ingres_autocommit() is called before opening a transaction (before the first call to ingres_query() or just after a call to ingres_rollback() or ingres_commit()) to switch the "autocommit" mode of the server on or off (when the script begins the autocommit mode is off).
When the autocommit mode is on, every query is automatically committed by the server, as if ingres_commit() was called after every call to ingres_query().
See also ingres_query(), ingres_rollback(), and ingres_commit().
Returns TRUE on success, or FALSE on failure.
ingres_close() closes the connection to the Ingres server that's associated with the specified link. If the link parameter isn't specified, the last opened link is used.
ingres_close() isn't usually necessary, as it won't close persistent connections and all non-persistent connections are automatically closed at the end of the script.
See also ingres_connect() and ingres_pconnect().
ingres_commit() commits the currently open transaction, making all changes made to the database permanent.
This closes the transaction. A new one can be open by sending a query with ingres_query().
You can also have the server commit automatically after every query by calling ingres_autocommit() before opening the transaction.
See also ingres_query(), ingres_rollback(), and ingres_autocommit().
Returns a Ingres II link resource on success, or FALSE on failure.
ingres_connect() opens a connection with the Ingres database designated by database, which follows the syntax [node_id::]dbname[/svr_class].
If some parameters are missing, ingres_connect() uses the values in php.ini for ingres.default_database, ingres.default_user, and ingres.default_password.
The connection is closed when the script ends or when ingres_close() is called on this link.
All the other ingres functions use the last opened link as a default, so you need to store the returned value only if you use more than one link at a time.
See also ingres_pconnect() and ingres_close().
Returns an string containing the active cursor name. If no cursor is active then NULL is returned.
If a link resource is passed to ingres_cursor() it returns the cursor name recorded for the link. If no link is passed then ingres_cursor() returns the cursor name asssociated with the default link.
See also ingres_prepare() and ingres_execute().
Returns an integer containing the last error number. If no error was reported 0 is returned.
If a link resource is passed to ingres_errno() it returns the last error recorded for the link. If no link is passed then ingres_errno() returns the last error reported using the default link.
The function, ingres_errno(), should always be called after executing a database query. Calling another function before ingres_errno() is called, will reset or change any error code from the last Ingres function call.
Esempio 1. ingres_error() example
|
See also ingres_error() and ingres_errsqlstate().
Returns a string containing the last error, or NULL if no error has occurred.
If a link resource is passed to ingres_error() it returns the last error recorded for the link. If no link is passed then ingres_error() returns the last error reported using the default link.
The function, ingres_error(), should always be called after executing any database query. Calling another function before ingres_error() is called will reset or change any error message from the last Ingres function call.
See also ingres_errno() and ingres_errsqlstate().
Returns a string containing the last SQLSTATE, or NULL if no error has occurred.
If a link resource is passed to ingres_errsqlstate() it returns the last error recorded for the link. If no link is passed then ingres_errsqlstate() returns the last error reported using the default link.
The function, ingres_errsqlstate(), should always be called after executing any database query. Calling another function before ingres_errsqlstate() is called will reset or change any error message from the last Ingres function call.
See also ingres_errno() and ingres_errsqlstate().
ingres_fetch_array() Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
This function is an extended version of ingres_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.
If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use the numeric index of the column or make an alias for the column.
<?php ingres_query("select t1.f1 as foo t2.f1 as bar from t1, t2"); $result = ingres_fetch_array(); $foo = $result["foo"]; $bar = $result["bar"]; ?> |
result_type can be INGRES_NUM for enumerated array, INGRES_ASSOC for associative array, or INGRES_BOTH (default).
Speed-wise, the function is identical to ingres_fetch_object(), and almost as quick as ingres_fetch_row() (the difference is insignificant).
See also ingres_query(), ingres_num_fields(), ingres_field_name(), ingres_fetch_object(), and ingres_fetch_row().
ingres_fetch_object() Returns an object that corresponds to the fetched row, or FALSE if there are no more rows.
This function is similar to ingres_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
The optional argument result_type is a constant and can take the following values: INGRES_ASSOC, INGRES_NUM, and INGRES_BOTH.
Speed-wise, the function is identical to ingres_fetch_array(), and almost as quick as ingres_fetch_row() (the difference is insignificant).
See also ingres_query(), ingres_num_fields(), ingres_field_name(), ingres_fetch_array(), and ingres_fetch_row().
ingres_fetch_row() returns an array that corresponds to the fetched row, or FALSE if there are no more rows. Each result column is stored in an array offset, starting at offset 1.
Subsequent call to ingres_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.
See also ingres_num_fields(), ingres_query(), ingres_fetch_array(), and ingres_fetch_object().
ingres_field_length() returns the length of a field. This is the number of bytes used by the server to store the field. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.
index is the number of the field and must be between 1 and the value given by ingres_num_fields().
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().
ingres_field_name() returns the name of a field in a query result, or FALSE on failure.
index is the number of the field and must be between 1 and the value given by ingres_num_fields().
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object() and ingres_fetch_row().
ingres_field_nullable() returns TRUE if the field can be set to the NULL value and FALSE if it can't.
index is the number of the field and must be between 1 and the value given by ingres_num_fields().
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().
ingres_field_precision() returns the precision of a field. This value is used only for decimal, float and money SQL data types. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.
index is the number of the field and must be between 1 and the value given by ingres_num_fields().
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().
ingres_field_scale() returns the scale of a field. This value is used only for the decimal SQL data type. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.
index is the number of the field and must be between 1 and the value given by ingres_num_fields().
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().
ingres_field_type() returns the type of a field in a query result, or FALSE on failure. Examples of types returned are "IIAPI_BYTE_TYPE", "IIAPI_CHA_TYPE", "IIAPI_DTE_TYPE", "IIAPI_FLT_TYPE", "IIAPI_INT_TYPE", "IIAPI_VCH_TYPE". Some of these types can map to more than one SQL type depending on the length of the field (see ingres_field_length()). For example "IIAPI_FLT_TYPE" can be a float4 or a float8. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.
index is the number of the field and must be between 1 and the value given by ingres_num_fields().
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)
ingres_num_fields -- Get the number of fields returned by the last queryingres_num_fields() returns the number of fields in the results returned by the Ingres server after a call to ingres_query()
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)
ingres_num_rows -- Get the number of rows affected or returned by the last queryFor delete, insert or update queries, ingres_num_rows() returns the number of rows affected by the query. For other queries, ingres_num_rows() returns the number of rows in the query's result.
Nota: This function is mainly meant to get the number of rows modified in the database. If this function is called before using ingres_fetch_array(), ingres_fetch_object() or ingres_fetch_row() the server will delete the result's data and the script won't be able to get them.
You should instead retrieve the result's data using one of these fetch functions in a loop until it returns FALSE, indicating that no more results are available.
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)
ingres_pconnect -- Open a persistent connection to an Ingres II databaseReturns a Ingres II link resource on success, or FALSE on failure.
See ingres_connect() for parameters details and examples. There are only 2 differences between ingres_pconnect() and ingres_connect() : First, when connecting, the function will first try to find a (persistent) link that's already opened with the same parameters. If one is found, an identifier for it will be returned instead of opening a new connection. Second, the connection to the Ingres server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ingres_close() will not close links established by ingres_pconnect()). This type of link is therefore called 'persistent'.
See also ingres_connect() and ingres_close().
Returns TRUE on success, or FALSE on failure.
ingres_query() sends the given query to the Ingres server. This query must be a valid SQL query (see the Ingres SQL reference guide)
The query becomes part of the currently open transaction. If there is no open transaction, ingres_query() opens a new transaction. To close the transaction, you can either call ingres_commit() to commit the changes made to the database or ingres_rollback() to cancel these changes. When the script ends, any open transaction is rolled back (by calling ingres_rollback()). You can also use ingres_autocommit() before opening a new transaction to have every SQL query immediately committed.
Some types of SQL queries can't be sent with this function:
close (see ingres_close())
commit (see ingres_commit())
connect (see ingres_connect())
disconnect (see ingres_close())
get dbevent
prepare to commit
rollback (see ingres_rollback())
savepoint
set autocommit (see ingres_autocommit())
all cursor related queries are unsupported
See also ingres_fetch_array(), ingres_fetch_object(), ingres_fetch_row(), ingres_commit(), ingres_rollback(), and ingres_autocommit().
ingres_rollback() rolls back the currently open transaction, actually canceling all changes made to the database during the transaction.
This closes the transaction. A new one can be open by sending a query with ingres_query().
See also ingres_query(), ingres_commit(), and ingres_autocommit().
With IRCG you can rapidly stream XML data to thousands of concurrently connected users. This can be used to build powerful, extensible interactive platforms such as online games and webchats. IRCG also features support for a non-streaming mode where a helper application reformats incoming data and supplies static file snippets in special formats such as cHTML (i-mode) or WML (WAP). These static files are then delivered by the high-performance web server.
Up to v4, IRCG runs under these platforms:
AIX
FreeBSD
HP-UX
Irix
Linux
Solaris
Tru64
Windows
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.1.0.
Detailed installation instructions can be found at http://www.schumann.cx/ircg/. We urge you to use the provided installation script.
It is not recommended, but you can try enable IRCG support yourself. Provide the path to the ircg-config script, --with-ircg-config=path/to/irc-config and in addition add --with-ircg to your configure line.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Set channel mode flags for channel on server connected to by connection. Mode flags are passed in mode_spec and are applied to the user specified by nick.
Mode flags are set or cleared by specifying a mode character and prepending it with a plus or minus character, respectively. E.g. operator mode is granted by '+o' and revoked by '-o', as passed as mode_spec.
ircg_disconnect() will close a connection to a server previously established with ircg_pconnect().
See also: ircg_pconnect().
(PHP 4 >= 4.3.0, PHP 5 <= 5.0.4)
ircg_eval_ecmascript_params -- Decodes a list of JS-encoded parametersAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
From the ircg_eval_ecmascript_params source file: /* * State 0: Looking for ' or digit * State 1: Assembling parameter inside '..' * State 2: After escape sign: Copies single char verbatim, go to 1 * State 3: Assembling numeric para, no quotation * State 4: Looking for ",", skipping whitespace */ |
See also ircg_lookup_format_messages().
(PHP 4 >= 4.1.0, PHP 5 <= 5.0.4)
ircg_fetch_error_msg -- Returns the error from previous IRCG operationircg_fetch_error_msg() returns the error from a failed connection.
Nota: Error code is stored in first array element, error text in second. The error code is equivalent to IRC reply codes as defined by RFC 2812.
Function ircg_get_username() returns the username for the specified connection connection. Returns FALSE if connection died or is not valid.
Encodes a HTML string html_string for output. This exposes the interface which the IRCG extension uses internally to reformat data coming from an IRC link. The function causes IRC color/font codes to be encoded in HTML and escapes certain entities.
This function adds user nick to the ignore list of connection connection. Afterwards, IRCG will suppress all messages from this user through the associated connection.
See also: ircg_ignore_del().
This function removes user nick from the IRCG ignore list associated with connection.
See also: ircg_ignore_add().
ircg_invite() will send an invitation to the user nickname, prompting him to join channel. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
ircg_is_conn_alive() returns TRUE if connection is still alive and working or FALSE, if the connection has died for some reason.
Join the channel channel on the server connected to by connection. IRCG will optionally pass the room key key.
Kick user nick from channel on server connected to by connection. reason should give a short message describing why this action was performed.
ircg_list() will request a list of users in the channel. The answer is sent to the output defined by ircg_set_file() or ircg_set_current(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. ircg_list() example
This example will output something similar to:
|
See also: ircg_set_file(), ircg_set_current(), and ircg_who().
(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)
ircg_lookup_format_messages -- Check for the existence of a format message setCheck for the existence of the format message set name. Sets may be registered with ircg_register_format_messages(), a default set named ircg is always available. Returns TRUE, if the set exists and FALSE otherwise.
See also: ircg_register_format_messages()
ircg_lusers() will request a statistical breakdown of users on the network connected to on connection. The answer is sent to the output defined by ircg_set_file() or ircg_set_current(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also: ircg_set_file(), and ircg_set_current().
ircg_msg() will send the message to a channel or user on the server connected to by connection. A recipient starting with # or & will send the message to a channel, anything else will be interpreted as a username.
Setting the optional parameter suppress to a TRUE value will suppress output of your message to your own connection. This so-called loopback is necessary, because the IRC server does not echo PRIVMSG commands back to us.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
See also ircg_get_username() and ircg_lusers().
Change your nickname on the given connection to the one given in nick, if possible.
Will return TRUE on success and FALSE on failure.
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)
ircg_nickname_escape -- Encode special characters in nickname to be IRC-compliantFunction ircg_nickname_escape() returns an encoded nickname specified by nick which is IRC-compliant.
See also: ircg_nickname_unescape()
Function ircg_nickname_unescape() returns a decoded nickname, which is specified in nick.
See also: ircg_nickname_escape()
This function will send the message text to the user nick on the server connected to by connection. IRC servers and other software will not automatically generate replies to NOTICEs in contrast to other message types.
ircg_oper() will authenticate the logged in user on connection as an IRC operator. name and password must match a registered IRC operator account. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Leave the channel channel on the server connected to by connection.
ircg_pconnect() will try to establish a connection to an IRC server and return a connection resource handle for further use.
The only mandatory parameter is username, this will set your initial nickname on the server. server_ip and server_port are optional and default to 127.0.0.1 and 6667.
Nota: For now parameter server_ip will not do any hostname lookups and will only accept IP addresses in numerical form. DNS lookups are expensive and should be done in the context of IRCG.
You can customize the output of IRC messages and events by selecting a format message set previously created with ircg_register_format_messages() by specifying the set's name in msg_format.
If you want to handle CTCP messages such as ACTION (/me), you need to define a mapping from CTCP type (e.g. ACTION) to a custom format string. Do this by passing an associative array as ctcp_messages. The keys of the array are the CTCP type and the respective value is the format message.
You can define "ident", "password", and "realname" tokens which are sent to the IRC server by setting these in an associative array. Pass that array as user_settings.
See also: ircg_disconnect(), ircg_is_conn_alive(), ircg_register_format_messages().
With ircg_register_format_messages() you can customize the way your IRC output looks like or which script functions are invoked on the client side.
Plain channel message
Private message received
Private message sent
Some user leaves channel
Some user enters channel
Some user was kicked from the channel
Topic has been changed
Error
Fatal error
Join list end(?)
Self part(?)
Some user changes his nick
Some user quits his connection
Mass join begin
Mass join element
Mass join end
Whois user
Whois server
Whois idle
Whois channel
Whois end
Voice status change on user
Operator status change on user
Banlist
Banlist end
%f - from
%t - to
%c - channel
%r - plain message
%m - encoded message
%j - js encoded message
1 - mod encode
2 - nickname decode
See also: ircg_lookup_format_messages().
Select the current HTTP connection for output in this execution context. Every output sent from the server connected to by connection will be copied to standard output while using default formatting or a format message set specified by ircg_register_format_messages().
See also: ircg_register_format_messages().
Function ircg_set_file() specifies a logfile path in which all output from connection connection will be logged. Returns TRUE on success, otherwise FALSE.
In case of the termination of connection connection IRCG will connect to host at port (Note: host must be an IPv4 address, IRCG does not resolve host-names due to blocking issues), send data to the new host connection and will wait until the remote part closes connection. This can be used to trigger a PHP script for example.
This feature requires IRCG 3.
Change the topic for channel channel on the server connected to by connection to new_topic.
ircg_who() will request a list of users whose nickname is matching mask on connected network connection. The optional parameter ops_only will shrink the list to server operators only.
The answer is sent to the output defined by ircg_set_file() or ircg_set_current(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also: ircg_set_file(), and ircg_set_current().
There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension.
The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
This PECL extension is not bundled with PHP.
In PHP 4 this PECL extensions source can be found in the ext/ directory within the PHP source or at the PECL link above. In order to use these functions you must compile PHP with Java support by using the --with-java[=DIR] where DIR points to the base install directory of your JDK. This extension can only be built as a shared extension. Additional build extensions can be found in php-src/ext/java/README.
Windows users will enable php_java.dll inside of php.ini in order to use these functions. In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Nota: In order to enable this module on a Windows environment with PHP <= 4.0.6, you must make jvm.dll available to your systems PATH. No additional DLL is needed for PHP versions > 4.0.6.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Java configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
java.class.path | NULL | PHP_INI_ALL | |
java.home | NULL | PHP_INI_ALL | |
java.library.path | NULL | PHP_INI_ALL | |
java.library | JAVALIB | PHP_INI_ALL |
Esempio 1. Java Example
|
Esempio 2. AWT Example
|
new Java() will create an instance of a class if a suitable constructor is available. If no parameters are passed and the default constructor is useful as it provides access to classes like java.lang.System which expose most of their functionallity through static methods.
Accessing a member of an instance will first look for bean properties then public fields. In other words, print $date.time will first attempt to be resolved as $date.getTime(), then as $date.time.
Both static and instance members can be accessed on an object with the same syntax. Furthermore, if the java object is of type java.lang.Class, then static members of the class (fields and methods) can be accessed.
Exceptions raised result in PHP warnings, and NULL results. The warnings may be eliminated by prefixing the method call with an "@" sign. The following APIs may be used to retrieve and reset the last error:
Overload resolution is in general a hard problem given the differences in types between the two languages. The PHP Java extension employs a simple, but fairly effective, metric for determining which overload is the best match.
Additionally, method names in PHP are not case sensitive, potentially increasing the number of overloads to select from.
Once a method is selected, the parameters are coerced if necessary, possibly with a loss of data (example: double precision floating point numbers will be converted to boolean).
In the tradition of PHP, arrays and hashtables may pretty much be used interchangably. Note that hashtables in PHP may only be indexed by integers or strings; and that arrays of primitive types in Java can not be sparse. Also note that these constructs are passed by value, so may be expensive in terms of memory and time.
The Java Servlet SAPI builds upon the mechanism defined by the Java extension to enable the entire PHP processor to be run as a servlet. The primary advantage of this from a PHP perspective is that web servers which support servlets typically take great care in pooling and reusing JVMs. Build instructions for the Servlet SAPI module can be found in php4/sapi/README. Notes:
While this code is intended to be able to run on any servlet engine, it has only been tested on Apache's Jakarta/tomcat to date. Bug reports, success stories and/or patches required to get this code to run on other engines would be appreciated.
PHP has a habit of changing the working directory. sapi/servlet will eventually change it back, but while PHP is running the servlet engine may not be able to load any classes from the CLASSPATH which are specified using a relative directory syntax, or find the work directory used for administration and JSP compilation tasks.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
See java_last_exception_get() for an example.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The following example demonstrates the usage of Java's exception handler from within PHP:
Esempio 1. Java exception handler
|
These package allows you to access Kerberos V administration servers. You can create, modify, and delete Kerberos V principals and policies.
More information about Kerberos can be found at http://web.mit.edu/kerberos/www/.
Documentation for Kerberos and KADM5 can be found at http://web.mit.edu/kerberos/www/krb5-1.2/krb5-1.2.8/doc/admin_toc.html.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
The functions kadm5_create_principal(), kadm5_modify_principal(), and kadm5_modify_principal() allow to specify special attributes using a bitfield. The symbols are defined below:
Tabella 1. Attributes for use by the KDC
constant |
---|
KRB5_KDB_DISALLOW_POSTDATED |
KRB5_KDB_DISALLOW_FORWARDABLE |
KRB5_KDB_DISALLOW_TGT_BASED |
KRB5_KDB_DISALLOW_RENEWABLE |
KRB5_KDB_DISALLOW_PROXIABLE |
KRB5_KDB_DISALLOW_DUP_SKEY |
KRB5_KDB_DISALLOW_ALL_TIX |
KRB5_KDB_REQUIRES_PRE_AUTH |
KRB5_KDB_REQUIRES_HW_AUTH |
KRB5_KDB_REQUIRES_PWCHANGE |
KRB5_KDB_DISALLOW_SVR |
KRB5_KDB_PWCHANGE_SERVER |
KRB5_KDB_SUPPORT_DESMD5 |
KRB5_KDB_NEW_PRINC |
The functions kadm5_create_principal(), kadm5_modify_principal(), and kadm5_get_principal() allow to specify or return principal's options as an associative array. The keys for the associative array are defined as string constants below:
Tabella 2. Options for creating/modifying/retrieving principals
constant | funcdef | description |
---|---|---|
KADM5_PRINCIPAL | long | The expire time of the princial as a Kerberos timestamp. |
KADM5_PRINC_EXPIRE_TIME | long | The expire time of the princial as a Kerberos timestamp. |
KADM5_LAST_PW_CHANGE | long | The time this principal's password was last changed. |
KADM5_PW_EXPIRATION | long | The expire time of the principal's current password, as a Kerberos timestamp. |
KADM5_MAX_LIFE | long | The maximum lifetime of any Kerberos ticket issued to this principal. |
KADM5_MAX_RLIFE | long | The maximum renewable lifetime of any Kerberos ticket issued to or for this principal. |
KADM5_MOD_NAME | string | The name of the Kerberos principal that most recently modified this principal. |
KADM5_MOD_TIME | long | The time this principal was last modified, as a Kerberos timestamp. |
KADM5_KVNO | long | The version of the principal's current key. |
KADM5_POLICY | string | The name of the policy controlling this principal. |
KADM5_CLEARPOLICY | long | Standard procedure is to assign the 'default' policy to new principals. KADM5_CLEARPOLICY suppresses this behaviour. |
KADM5_LAST_SUCCESS | long | The KDC time of the last successfull AS_REQ. |
KADM5_LAST_FAILED | long | The KDC time of the last failed AS_REQ. |
KADM5_FAIL_AUTH_COUNT | long | The number of consecutive failed AS_REQs. |
KADM5_RANDKEY | long | Generates a random password for the principal. The parameter password will be ignored. |
KADM5_ATTRIBUTES | long | A bitfield of attributes for use by the KDC. |
This simple example shows how to connect, query, print resulting principals and disconnect from a KADM5 database.
Esempio 1. KADM5 extension overview example
|
If you have comments, bugfixes, enhancements or want to help in developing this you can send me a mail at holger.burbach@gonicus.de. The project homepage can be found at http://oss.gonicus.de/project/?group_id=7.
kadm5_chpass_principal() sets the new password password for the principal.
kadm5_create_principal() creates a principal with the given password. If password is omitted or is NULL, a random key will be generated.
It is possible to specify several optional parameters within the array options. Allowed are the following options: KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_KVNO, KADM5_POLICY, KADM5_CLEARPOLICY, KADM5_MAX_RLIFE.
Esempio 1. Example of principal's creation
|
kadm5_delete_principal() remove the principal from the Kerberos database.
(PECL)
kadm5_flush -- Flush all changes to the Kerberos database, leaving the connection to the Kerberos admin server openkadm5_get_policies() returns an array containing the policies's names.
kadm5_get_principal() returns an associative array containing the following keys: KADM5_PRINCIPAL, KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_MOD_NAME, KADM5_MOD_TIME, KADM5_KVNO, KADM5_POLICY, KADM5_MAX_RLIFE, KADM5_LAST_SUCCESS, KADM5_LAST_FAILED, KADM5_FAIL_AUTH_COUNT.
Esempio 1. kadm5_get_principal() example
|
kadm5_get_principals() returns an array containing the principals's names.
(PECL)
kadm5_init_with_password -- Opens a connection to the KADM5 library and initializes any neccessary state informationkadm5_init_with_password() opens a connection with the KADM5 library using the principal and the given password to obtain initial credentials from the admin_server. The parameter realm defines the authentication domain for the connection.
Esempio 1. KADM5 initialization example
|
kadm5_modify_principal() modifies a principal according to the given options. Allowed are the following options: KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_KVNO, KADM5_POLICY, KADM5_CLEARPOLICY, KADM5_MAX_RLIFE, KADM5_FAIL_AUTH_COUNT.
Esempio 1. Example of modifying principal
|
LDAP is the Lightweight Directory Access Protocol, and is a protocol used to access "Directory Servers". The Directory is a special kind of database that holds information in a tree structure.
The concept is similar to your hard disk directory structure, except that in this context, the root directory is "The world" and the first level subdirectories are "countries". Lower levels of the directory structure contain entries for companies, organisations or places, while yet lower still we find directory entries for people, and perhaps equipment or documents.
To refer to a file in a subdirectory on your hard disk, you might use something like:
/usr/local/myapp/docs
The forwards slash marks each division in the reference, and the sequence is read from left to right.
The equivalent to the fully qualified file reference in LDAP is the "distinguished name", referred to simply as "dn". An example dn might be:
cn=John Smith,ou=Accounts,o=My Company,c=US
The comma marks each division in the reference, and the sequence is read from right to left. You would read this dn as:
country = US
organization = My Company
organizationalUnit = Accounts
commonName = John Smith
In the same way as there are no hard rules about how you organise the directory structure of a hard disk, a directory server manager can set up any structure that is meaningful for the purpose. However, there are some conventions that are used. The message is that you can not write code to access a directory server unless you know something about its structure, any more than you can use a database without some knowledge of what is available.
Lots of information about LDAP can be found at
The Netscape SDK contains a helpful Programmer's Guide in HTML format.
You will need to get and compile LDAP client libraries from either OpenLDAP or Bind9.net in order to compile PHP with LDAP support.
LDAP support in PHP is not enabled by default. You will need to use the --with-ldap[=DIR] configuration option when compiling PHP to enable LDAP support. DIR is the LDAP base install directory. To enable SASL support, be sure --with-ldap-sasl[=DIR] is used, and that sasl.h exists on the system.
Note to Win32 Users: In order to enable this module on a Windows environment, you must copy several files from the DLL folder of the PHP/Win32 binary package to the SYSTEM folder of your windows machine. (Ex: C:\WINNT\SYSTEM32, or C:\WINDOWS\SYSTEM). For PHP <= 4.2.0 copy libsasl.dll, for PHP >= 4.3.0 copy libeay32.dll and ssleay32.dll to your SYSTEM folder.
In order to use Oracle LDAP libraries, proper Oracle environment has to be set.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Retrieve information for all entries where the surname starts with "S" from a directory server, displaying an extract with name and email address.
Esempio 1. LDAP search example
|
Before you can use the LDAP calls you will need to know ..
The name or address of the directory server you will use
The "base dn" of the server (the part of the world directory that is held on this server, which could be "o=My Company,c=US")
Whether you need a password to access the server (many servers will provide read access for an "anonymous bind" but require a password for anything else)
The typical sequence of LDAP calls you will make in an application will follow this pattern:
ldap_connect() // establish connection to server
|
ldap_bind() // anonymous or authenticated "login"
|
do something like search or update the directory
and display the results
|
ldap_close() // "logout"
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The ldap_add() function is used to add entries in the LDAP directory. The DN of the entry to be added is specified by dn. Array entry specifies the information about the entry. The values in the entries are indexed by individual attributes. In case of multiple values for an attribute, they are indexed using integers starting with 0.
<?php $entree["attribut1"] = "value"; $entree["attribut2"][0] = "value1"; $entree["attribut2"][1] = "value2"; ?> |
Esempio 1. Complete example with authenticated bind
|
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Binds to the LDAP directory with specified RDN and password. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
ldap_bind() does a bind operation on the directory. bind_rdn and bind_password are optional. If not specified, anonymous bind is attempted.
Esempio 1. Using LDAP Bind
|
Esempio 2. Using LDAP Bind Anonymously
|
Returns TRUE if value matches otherwise returns FALSE. Returns -1 on error.
ldap_compare() is used to compare value of attribute to value of same attribute in LDAP directory entry specified with dn.
The following example demonstrates how to check whether or not given password matches the one defined in DN specified entry.
Esempio 1. Complete example of password check
|
Avvertimento |
ldap_compare() can NOT be used to compare BINARY values! |
Nota: This function was added in 4.0.2.
Returns a positive LDAP link identifier on success, or FALSE on error. When OpenLDAP 2.x.x is used, ldap_connect() will always return a resource as it does not actually connect but just initializes the connecting parameters. The actual connect happens with the next calls to ldap_* funcs, usually with ldap_bind().
ldap_connect() establishes a connection to a LDAP server on a specified hostname and port. Both the arguments are optional. If no arguments are specified then the link identifier of the already opened link will be returned. If only hostname is specified, then the port defaults to 389.
If you are using OpenLDAP 2.x.x you can specify a URL instead of the hostname. To use LDAP with SSL, compile OpenLDAP 2.x.x with SSL support, configure PHP with SSL, and use ldaps://hostname/ as host parameter. The port parameter is not used when using URLs.
Nota: URL and SSL support were added in 4.0.4.
See also ldap_bind().
Returns number of entries in the result or FALSE on error.
ldap_count_entries() returns the number of entries stored in the result of previous search operations. result_identifier identifies the internal ldap result.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
ldap_delete() function delete a particular entry in LDAP directory specified by dn.
ldap_dn2ufn() function is used to turn a DN, specified by dn, into a more user-friendly form, stripping off type names.
Returns string error message.
This function returns the string error message explaining the error number errno. While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.
See also ldap_errno() and ldap_error().
Return the LDAP error number of the last LDAP command for this link.
This function returns the standardized error number returned by the last LDAP command for the given link_identifier. This number can be converted into a textual error message using ldap_err2str().
Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.
Esempio 1. Generating and catching an error
|
See also ldap_err2str() and ldap_error().
Returns string error message.
This function returns the string error message explaining the error generated by the last LDAP command for the given link_identifier While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.
Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.
See also ldap_err2str() and ldap_errno().
ldap_explode_dn() function is used to split the DN returned by ldap_get_dn() and breaks it up into its component parts. Each part is known as Relative Distinguished Name, or RDN. ldap_explode_dn() returns an array of all those components. with_attrib is used to request if the RDNs are returned with only values or their attributes as well. To get RDNs with the attributes (i.e. in attribute=value format) set with_attrib to 0 and to get only values set it to 1.
Returns the first attribute in the entry on success and FALSE on error.
Similar to reading entries, attributes are also read one by one from a particular entry. ldap_first_attribute() returns the first attribute in the entry pointed by the result_entry_identifier. Remaining attributes are retrieved by calling ldap_next_attribute() successively. ber_identifier is the identifier to internal memory location pointer. It is passed by reference. The same ber_identifier is passed to the ldap_next_attribute() function, which modifies that pointer.
See also ldap_get_attributes()
Returns the result entry identifier for the first entry on success and FALSE on error.
Entries in the LDAP result are read sequentially using the ldap_first_entry() and ldap_next_entry() functions. ldap_first_entry() returns the entry identifier for first entry in the result. This entry identifier is then supplied to ldap_next_entry() routine to get successive entries from the result.
See also ldap_get_entries().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
ldap_free_result() frees up the memory allocated internally to store the result and pointed by the result_identifier. All result memory will be automatically freed when the script terminates.
Typically all the memory allocated for the ldap result gets freed at the end of the script. In case the script is making successive searches which return large result sets, ldap_free_result() could be called to keep the runtime memory usage by the script low.
Returns a complete entry information in a multi-dimensional array on success and FALSE on error.
ldap_get_attributes() function is used to simplify reading the attributes and values from an entry in the search result. The return value is a multi-dimensional array of attributes and values.
Having located a specific entry in the directory, you can find out what information is held for that entry by using this call. You would use this call for an application which "browses" directory entries and/or where you do not know the structure of the directory entries. In many applications you will be searching for a specific attribute such as an email address or a surname, and won't care what other data is held.
return_value["count"] = number of attributes in the entry return_value[0] = first attribute return_value[n] = nth attribute return_value["attribute"]["count"] = number of values for attribute return_value["attribute"][0] = first value of the attribute return_value["attribute"][i] = (i+1)th value of the attribute |
Esempio 1. Show the list of attributes held for a particular directory entry
|
See also ldap_first_attribute() and ldap_next_attribute().
Returns the DN of the result entry and FALSE on error.
ldap_get_dn() function is used to find out the DN of an entry in the result.
Returns a complete result information in a multi-dimensional array on success and FALSE on error.
ldap_get_entries() function is used to simplify reading multiple entries from the result, specified with result_identifier, and then reading the attributes and multiple values. The entire information is returned by one function call in a multi-dimensional array. The structure of the array is as follows.
The attribute index is converted to lowercase. (Attributes are case-insensitive for directory servers, but not when used as array indices.)
return_value["count"] = number of entries in the result return_value[0] : refers to the details of first entry return_value[i]["dn"] = DN of the ith entry in the result return_value[i]["count"] = number of attributes in ith entry return_value[i][j] = jth attribute in the ith entry in the result return_value[i]["attribute"]["count"] = number of values for attribute in ith entry return_value[i]["attribute"][j] = jth value of attribute in ith entry |
See also ldap_first_entry() and ldap_next_entry().
Sets retval to the value of the specified option. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The parameter option can be one of: LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT, LDAP_OPT_PROTOCOL_VERSION, LDAP_OPT_ERROR_NUMBER, LDAP_OPT_REFERRALS, LDAP_OPT_RESTART, LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING, LDAP_OPT_MATCHED_DN. These are described in draft-ietf-ldapext-ldap-c-api-xx.txt
Nota: This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x, and was added in PHP 4.0.4
See also ldap_set_option().
Returns an array of values for the attribute on success and FALSE on error.
ldap_get_values_len() function is used to read all the values of the attribute in the entry in the result. entry is specified by the result_entry_identifier. The number of values can be found by indexing "count" in the resultant array. Individual values are accessed by integer index in the array. The first index is 0.
This function is used exactly like ldap_get_values() except that it handles binary data and not string data.
Nota: This function was added in 4.0.
Returns an array of values for the attribute on success and FALSE on error.
ldap_get_values() function is used to read all the values of the attribute in the entry in the result. entry is specified by the result_entry_identifier. The number of values can be found by indexing "count" in the resultant array. Individual values are accessed by integer index in the array. The first index is 0.
This call needs a result_entry_identifier, so needs to be preceded by one of the ldap search calls and one of the calls to get an individual entry.
You application will either be hard coded to look for certain attributes (such as "surname" or "mail") or you will have to use the ldap_get_attributes() call to work out what attributes exist for a given entry.
LDAP allows more than one entry for an attribute, so it can, for example, store a number of email addresses for one person's directory entry all labeled with the attribute "mail"
return_value["count"] = number of values for attribute
return_value[0] = first value of attribute
return_value[i] = ith value of attribute
Esempio 1. List all values of the "mail" attribute for a directory entry
|
Returns a search result identifier or FALSE on error.
ldap_list() performs the search for a specified filter on the directory with the scope LDAP_SCOPE_ONELEVEL.
LDAP_SCOPE_ONELEVEL means that the search should only return information that is at the level immediately below the base_dn given in the call. (Equivalent to typing "ls" and getting a list of files and folders in the current working directory.)
This call takes 5 optional parameters. See ldap_search() notes.
Nota: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.
Esempio 1. Produce a list of all organizational units of an organization
|
Nota: From 4.0.5 on it's also possible to do parallel searches. See ldap_search() for details.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
This function adds attribute(s) to the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level additions are done by the ldap_add() function.
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
This function removes attribute(s) from the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level deletions are done by the ldap_delete() function.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
This function replaces attribute(s) from the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level modifications are done by the ldap_modify() function.
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
ldap_modify() function is used to modify the existing entries in the LDAP directory. The structure of the entry is same as in ldap_add().
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Returns the next attribute in an entry on success and FALSE on error.
ldap_next_attribute() is called to retrieve the attributes in an entry. The internal state of the pointer is maintained by the ber_identifier. It is passed by reference to the function. The first call to ldap_next_attribute() is made with the result_entry_identifier returned from ldap_first_attribute().
See also ldap_get_attributes()
Returns entry identifier for the next entry in the result whose entries are being read starting with ldap_first_entry(). If there are no more entries in the result then it returns FALSE.
ldap_next_entry() function is used to retrieve the entries stored in the result. Successive calls to the ldap_next_entry() return entries one by one till there are no more entries. The first call to ldap_next_entry() is made after the call to ldap_first_entry() with the result_entry_identifier as returned from the ldap_first_entry().
See also ldap_get_entries()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Returns a search result identifier or FALSE on error.
ldap_read() performs the search for a specified filter on the directory with the scope LDAP_SCOPE_BASE. So it is equivalent to reading an entry from the directory.
An empty filter is not allowed. If you want to retrieve absolutely all information for this entry, use a filter of "objectClass=*". If you know which entry types are used on the directory server, you might use an appropriate filter such as "objectClass=inetOrgPerson".
This call takes 5 optional parameters. See ldap_search() notes.
Nota: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.
From 4.0.5 on it's also possible to do parallel searches. See ldap_search() for details.
The entry specified by dn is renamed/moved. The new RDN is specified by newrdn and the new parent/superior entry is specified by newparent. If the parameter deleteoldrdn is TRUE the old RDN value(s) is removed, else the old RDN value(s) is retained as non-distinguished values of the entry. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: This function currently only works with LDAPv3. You may have to use ldap_set_option() prior to binding to use LDAPv3. This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x, and was added in PHP 4.0.5.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Requirement: ldap_sasl_bind() requires SASL support (sasl.h). Be sure --with-ldap-sasl is used when configuring PHP otherwise this function will be undefined.
Returns a search result identifier or FALSE on error.
ldap_search() performs the search for a specified filter on the directory with the scope of LDAP_SCOPE_SUBTREE. This is equivalent to searching the entire directory. base_dn specifies the base DN for the directory.
There is an optional fourth parameter, that can be added to restrict the attributes and values returned by the server to just those required. This is much more efficient than the default action (which is to return all attributes and their associated values). The use of the fourth parameter should therefore be considered good practice.
The fourth parameter is a standard PHP string array of the required attributes, e.g. array("mail", "sn", "cn") Note that the "dn" is always returned irrespective of which attributes types are requested.
Note too that some directory server hosts will be configured to return no more than a preset number of entries. If this occurs, the server will indicate that it has only returned a partial results set. This occurs also if the sixth parameter sizelimit has been used to limit the count of fetched entries.
The fifth parameter attrsonly should be set to 1 if only attribute types are wanted. If set to 0 both attributes types and attribute values are fetched which is the default behaviour.
With the sixth parameter sizelimit it is possible to limit the count of entries fetched. Setting this to 0 means no limit. NOTE: This parameter can NOT override server-side preset sizelimit. You can set it lower though.
The seventh parameter timelimit sets the number of seconds how long is spend on the search. Setting this to 0 means no limit. NOTE: This parameter can NOT override server-side preset timelimit. You can set it lower though.
The eighth parameter deref specifies how aliases should be handled during the search. It can be one of the following:
LDAP_DEREF_NEVER - (default) aliases are never dereferenced.
LDAP_DEREF_SEARCHING - aliases should be dereferenced during the search but not when locating the base object of the search.
LDAP_DEREF_FINDING - aliases should be dereferenced when locating the base object but not during the search.
LDAP_DEREF_ALWAYS - aliases should be dereferenced always.
Nota: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.
The search filter can be simple or advanced, using boolean operators in the format described in the LDAP documentation (see the Netscape Directory SDK for full information on filters).
The example below retrieves the organizational unit, surname, given name and email address for all people in "My Company" where the surname or given name contains the substring $person. This example uses a boolean filter to tell the server to look for information in more than one attribute.
Esempio 1. LDAP search
|
From 4.0.5 on it's also possible to do parallel searches. To do this you use an array of link identifiers, rather than a single identifier, as the first argument. If you don't want the same base DN and the same filter for all the searches, you can also use an array of base DNs and/or an array of filters. Those arrays must be of the same size as the link identifier array since the first entries of the arrays are used for one search, the second entries are used for another, and so on. When doing parallel searches an array of search result identifiers is returned, except in case of error, then the entry corresponding to the search will be FALSE. This is very much like the value normally returned, except that a result identifier is always returned when a search was made. There are some rare cases where the normal search returns FALSE while the parallel search returns an identifier.
Sets the value of the specified option to be newval. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. on error.
The parameter option can be one of: LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT, LDAP_OPT_PROTOCOL_VERSION, LDAP_OPT_ERROR_NUMBER, LDAP_OPT_REFERRALS, LDAP_OPT_RESTART, LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING, LDAP_OPT_MATCHED_DN, LDAP_OPT_SERVER_CONTROLS, LDAP_OPT_CLIENT_CONTROLS. Here's a brief description, see draft-ietf-ldapext-ldap-c-api-xx.txt for details.
The options LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT, LDAP_OPT_PROTOCOL_VERSION and LDAP_OPT_ERROR_NUMBER have integer value, LDAP_OPT_REFERRALS and LDAP_OPT_RESTART have boolean value, and the options LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING and LDAP_OPT_MATCHED_DN have string value. The first example illustrates their use. The options LDAP_OPT_SERVER_CONTROLS and LDAP_OPT_CLIENT_CONTROLS require a list of controls, this means that the value must be an array of controls. A control consists of an oid identifying the control, an optional value, and an optional flag for criticality. In PHP a control is given by an array containing an element with the key oid and string value, and two optional elements. The optional elements are key value with string value and key iscritical with boolean value. iscritical defaults to FALSE if not supplied. See also the second example below.
Nota: This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x, and was added in PHP 4.0.4.
Esempio 2. Set server controls
|
See also ldap_get_option().
(PHP 4 >= 4.2.0, PHP 5)
ldap_set_rebind_proc -- Set a callback function to do re-binds on referral chasing
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
These functions/constants are available since PHP 5.1.0 and if you have compiled one of the extensions based on libxml, like DOM, SimpleXML and XSLT.
code - the error's code
column - the column where the error occurred. Please note that this property isn't entirely implemented in libxml and therefore 0 is often returned.
file - the filename, or empty if the XML was loaded from a string
level - the severity of the error (one of the following constants: LIBXML_ERR_WARNING, LIBXML_ERR_ERROR or LIBXML_ERR_FATAL)
line - the line where the error occurred
message - the error message
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Activate small nodes allocation optimization. This may speed up your application without needing to change the code.
Nota: Only available in Libxml >= 2.6.21
Default DTD attributes
Load the external subset
Validate with the DTD
Remove blank nodes
Merge CDATA as text nodes
Expand empty tags (e.g. <br/> to <br></br>)
Nota: This option is currently just available in the DOMDocument->save() and DOMDocument->saveXML() functions.
Substitute entities
Suppress error reports
Disable network access when loading documents
Suppress warning reports
Drop the XML declaration when saving a document
Nota: Only available in Libxml >= 2.6.21
Remove redundant namespaces declarations
Implement XInclude substitution
A recoverable error
A fatal error
No errors
A simple warning
libxml version like 20605 or 20617
libxml version like 2.6.5 or 2.6.17
Returns an array with LibXMLError objects if there are any errors in the buffer, or an empty array otherwise.
Esempio 1. A libxml_get_errors() example This example demonstrates how to build a simple libxml error handler.
Il precedente esempio visualizzerà:
|
Returns a LibXMLError object if there is any error in the buffer, FALSE otherwise.
(PHP 5)
libxml_set_streams_context -- Set the streams context for the next libxml document load or writeSets the streams context for the next libxml document load or write.
The stream context resource (created with stream_context_create())
Esempio 1. A libxml_set_streams_context() example
|
(PHP 5 >= 5.1.0RC1)
libxml_use_internal_errors -- Disable libxml errors and allow user to fetch error information as neededlibxml_use_internal_errors() allows you to disable standard libxml errors and enable user error handling.
Esempio 1. A libxml_use_internal_errors() example This example demonstrates the basic usage of libxml errors and the value returned by this function.
Il precedente esempio visualizzerà:
|
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.0.0. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/notes.
Avvertimento |
This extension is currently not supported, thus looking for a maintainer. |
(PHP 4 >= 4.0.5, PECL)
notes_body -- Open the message msg_number in the specified mailbox on the specified server (leave servAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.0.5, PECL)
notes_header_info -- Open the message msg_number in the specified mailbox on the specified server (leave servAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
LZF è un algoritmo di compressione molto veloce, ideale per risparmiare spazio con leggere perdite di velocità. L'algoritmo può essere ottimizzato per velocità o spazio al momento della compila.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/lzf.
Per potere utilizzare queste funzioni occorre compilare il PHP con il supporto lzf utilizzando il parametro di configurazione --with-lzf[=DIR]. Occorre, inoltre, indicare --enable-lzf-better-compression per abilitare l'ottimizzazione per lo spazio piuttosto che per la velocità
Gli utenti di Windows devono abilitare php_lzf.dll dal php.ini per potere utilizzare queste funzioni. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
lzf_compress() comprime i dati presenti nel parametro arg.
Restituisce i dati compressi oppre FALSE se si verifica un errore.
Vedere anche lzf_decompress().
lzf_decompress() decomprime i dati dal parametro arg.
Restituisce id ati decompressi oppure FALSE se si verifica un errore.
Vedere anche lzf_compress().
La funzione mail() permette di inviare messaggi di posta elettronica.
Per avere disponibili le funzioni Mail, il PHP deve potere accedere all'eseguibile sendmail del sistema durante la compila. Qualora si utilizzi un'altro programma di posta, tipo qmail o postfix, occorre utlizzare il wrapper sendmail allegato al programma di posta. Il PHP cercherà sendmail in PATH e quindi in: /usr/bin:/usr/sbin:/usr/etc:/etc:/usr/ucblib:/usr/lib. Si consiglia vivamente di avere sendmail in PATH. Inoltre, l'utente che compila PHP deve avere i diritti di accesso all'eseguibile di sendmail.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Opzioni di configurazione Mail
Nome | Predefinito | Modificabile in |
---|---|---|
SMTP | "localhost" | PHP_INI_ALL |
smtp_port | "25" | PHP_INI_ALL |
sendmail_from | NULL | PHP_INI_ALL |
sendmail_path | DEFAULT_SENDMAIL_PATH | PHP_INI_SYSTEM |
Breve descrizione dei parametri di configurazione.
Usato solo sotto Windows: Nome DNS o indirizzo IP del server SMTP che PHP deve usare per spedire posta elettronica con la funzione mail().
Usato solo sotto Windows: Numero della porta del server specificato da SMTP al quale connettersi quando si inviano email usando mail(); il valore predefinito è 25. Disponibile solo a partire da PHP 4.3.0.
Quale campo "From:" devono avere i messaggi inviati da PHP sotto Windows.
Dove trovare il programma sendmail, solitamente /usr/sbin/sendmail oppure /usr/lib/sendmail. configure cerca di trovare il file e lo imposta di default, ma se non riesce a localizzarlo, lo si può impostare qui.
I sistemi che non usano sendmail devono impostare questa direttiva al wrapper che i rispettivi sistemi di posta offrono, se esistenti. Per esempio, gli utenti di Qmail possono normalmente impostarla a /var/qmail/bin/sendmail o /var/qmail/bin/qmail-inject.
qmail-inject non necessita di nessuna opzione al fine di processare correttamente la mail.
Questi parametri funzionano anche su Windows. Se si impostate smtp, smtp_port e sendmail_from saranno ignorate e verrà eseguito il comando indicato.
ezmlm_hash() calcola il valore hash che occorre quando si mantengono mailing list EZMLM in un database MySQL.
mail() invia automaticamente il messaggio specificato in messaggio al destinatario specificato in a. Destinatari multipli possono essere specificati mettendo una virgola tra ogni indirizzo in a. Email con allegati e tipi speciali di contenuto possono essere spedite usando questa funzione. Questo è possibile tramite la codifica MIME. Per maggiori informazioni, fare riferimento a un articolo Zend o alle Classi Mime del PEAR.
Le seguenti RFC possono essere di aiuto: RFC 1896, RFC 2045, RFC 2046, RFC 2047, RFC 2048 e RFC 2049.
mail() restituisce TRUE se la mail è stata accettata per la spedizione con successo, altrimenti restituisce FALSE.
Avvertimento |
L'implementazione Windows della funzione mail() differisce sotto molti aspetti dall'implementazione Unix. Primo, non usa una un programma in locale per comporre i messaggi, ma opera soltanto direttamente sui socket, il che significa che deve essere presente in ascolto un MTA su un socket di rete (che può essere su localhost o su una macchina remota). Secondo, gli header custom quali From:, Cc:, Bcc: e Date: non vengono interpretati subito dal MTA, ma ne viene fatto prima il parsing da parte di PHP. PHP < 4.3 supportava solo gli header Cc: (ed era case-sensitive). PHP >= 4.3 supporta tutti gli header e non è più case-sensitive. |
Se viene passata come parametro una quarta stringa, questa stringa viene inserita alla fine dell'intestazione (header). Ciò viene tipicamente usato per aggiungere intestazioni supplementari. Intestazioni multiple supplementari sono separate da un carattere di "a capo" (sia newline che carriage return).
Nota: È necessario usare \r\n per separare le intestazioni, alcuni mail transfer agent sotto Unix potrebbero funzionare anche solo con un singolo newline (\n).
Con il parametro parametri_addizionali è possibile impostare un parametro addizionale a linea di comando per il programma configurato per inviare mail usando sendmail_path. Per esempio si può impostare il corretto valore per envelope sender di sendmail con l'opzione -f di sendmail. Potrebbe essere necessario aggiungere l'utente che ha in esecuzione il server web alla configurazione di sendmail per prevenire l'aggiunta dell'intestazione 'X-Warning' quando si imposta envelope sender in questo modo.
Nota: Questo quinto parametro è stato aggiunto in PHP 4.0.5. A partire da PHP 4.2.3, questo parametro è disabilitato in modalità safe_mode, se si cerca di usarlo comunque, la funzione mail() darà un messaggio di errore e restituirà FALSE.
È possibile costruire messaggi complessi utilizzando la tecnica di concatenazione delle stringhe.
Esempio 4. Invio di mail complessa.
|
Nota: Assicurarsi di non avere nessun carattere di newline nei parametri a o oggetto, o la mail non verrà spedita correttamente.
Nota: Il parametro a non può essere un indirizzo nella forma "Qualcosa <qualcuno@example.com>". Il comando di mail non sarebbe in grado di effettuare correttamente il parsing mentre dialoga con il MTA (in particolare sotto Windows).
Vedere anche imap_mail().
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 4.2.0.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/mailparse.
In order to use these functions you must compile PHP with mailparse support by using the --enable-mailparse configure option.
Windows users will enable php_mailparse.dll inside of php.ini in order to use these functions. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
(4.1.0 - 4.1.2 only, PECL)
mailparse_determine_best_xfer_encoding -- Figures out the best way of encoding the content read from the file pointer fp, which must be seek-ableAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only, PECL)
mailparse_msg_create -- Returns a handle that can be used to parse a messageAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only, PECL)
mailparse_msg_extract_part_file -- Extracts/decodes a message section, decoding the transfer encodingAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
If callbackfunc is not specified, the contents will be sent to "stdout".
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only, PECL)
mailparse_msg_get_part_data -- Returns an associative array of info about the messageAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only, PECL)
mailparse_msg_get_part -- Returns a handle on a given section in a mimemessageAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only, PECL)
mailparse_msg_get_structure -- Returns an array of mime section names in the supplied messageAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only, PECL)
mailparse_msg_parse_file -- Parse file and return a resource representing the structureAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only, PECL)
mailparse_rfc822_parse_addresses -- Parse addresses and returns a hash containing that dataAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only, PECL)
mailparse_stream_encode -- Streams data from source file pointer, apply encoding and write to destfpAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Returns an array listing filename information.
Queste funzioni matematiche operano esclusivamente nel range dei tipi di dato integer e float del computer. (questo corrisponde attualmente ai tipi di dati long e double del C) Se si ha necessità di lavorare con numeri più grandi, fare riferimento alle funzioni matematiche a precisione arbitraria.
Vedere anche il manuale alle pagine operatori aritmetici.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Le costanti qui elencate sono sempre disponibili in quanto parte del core di PHP.
Tabella 1. Costanti Matematiche
Costante | Valore | Descrizione |
---|---|---|
M_PI | 3.14159265358979323846 | Pi |
M_E | 2.7182818284590452354 | e |
M_LOG2E | 1.4426950408889634074 | log_2 e |
M_LOG10E | 0.43429448190325182765 | log_10 e |
M_LN2 | 0.69314718055994530942 | log_e 2 |
M_LN10 | 2.30258509299404568402 | log_e 10 |
M_PI_2 | 1.57079632679489661923 | pi/2 |
M_PI_4 | 0.78539816339744830962 | pi/4 |
M_1_PI | 0.31830988618379067154 | 1/pi |
M_2_PI | 0.63661977236758134308 | 2/pi |
M_SQRTPI | 1.77245385090551602729 | sqrt(pi) [4.0.2] |
M_2_SQRTPI | 1.12837916709551257390 | 2/sqrt(pi) |
M_SQRT2 | 1.41421356237309504880 | sqrt(2) |
M_SQRT3 | 1.73205080756887729352 | sqrt(3) [4.0.2] |
M_SQRT1_2 | 0.70710678118654752440 | 1/sqrt(2) |
M_LNPI | 1.14472988584940017414 | log_e(pi) [4.0.2] |
M_EULER | 0.57721566490153286061 | Costante di Eulero [4.0.2] |
Restituisce il valore assoluto di un numero. Se l'argomento della funzione è di tipo float, il valore restituito è float, altrimenti restituisce un integer (perché float di solito ha un range di valori più grande di integer).
Restituisce l'arco coseno di arg in radianti. La funzione acos() è complementare alla funzione cos(), ovvero che a==cos(acos(a)) per ciascun valore di a nel range di acos().
Restituisce l'inverso del coseno iperbolico di arg, cioè il valore il cui coseno iperbolico vale arg.
Nota: Questa funzione non è implementata su piattaforme Windows
Restituisce l'arco seno di arg in radianti. La funzione asin() è complementare alla funzione sin(), ovvero che a==sin(asin(a)) per ciascun valore di a nel range di asin().
Restituisce l'inverso del seno iperbolico di arg, cioè il valore il cui seno iperbolico vale arg
Nota: Questa funzione non è implementata su piattaforme Windows
Questa funzione calcola l'arco tangente delle due variabili x e y. È simile al calcolo dell'arco tangente di y / x, eccetto per il fatto che viene tenuto in considearazione il segno di entrambi gli argomenti per determinare il quadrante del risultato.
La funzione restituisce il risultato in radianti, compreso fra -PI e PI (inclusi).
Restituisce l'arco tangente di arg in radianti. La funzione è complementare a tan(), ovvero a==tan(atan(a)) per ciascun valore di a nel range di atan()
Restituisce l'inverso della tangente iperbolica di arg, cioè il valore la cui tangente iperbolica vale arg.
Nota: Questa funzione non è implementata su piattaforme Windows
Restituisce una stringa contenente numero rappresentata in base base_di_arrivo. La base in cui numero è dato è specificata da base_di_partenza. Entrambe base_di_partenza e base_di_arrivo devono essere comprese fra 2 e 36, inclusi. Cifre in numeri con una base maggiore di 10 saranno rappresentati con le lettere a-z, con a significante 10, b significante 11 e z significante 35.
Avvertimento |
La funzione base_convert() può perdere di precisione con numeri molto grandi a causa delle proprietà dei tipi "double" o "float" utilizzati internamente. Fare riferimento alla sezione Floating point numbers del manuale per informazioni specifiche e per le limitazione. |
Restituisce il decimale equivalente al numero binario rappresentato dall'argomento stringa_binaria.
bindec() converte un binario in integer. Il più grande numero che può essere convertito è 31 volte la cifra 1 oppure 2147483647 espresso in formato decimale.
Vedere anche decbin(), octdec(), hexdec() e base_convert().
Restituisce il primo intero più grande di numero, se necessario. Il valore restituito da ceil() è ancora di tipo float, poiché la gamma di valori del tipo float è solitamente più grande di quella del tipo integer.
Restituisce il coseno di arg. Il parametro arg deve essere espresso in radianti.
Restituisce il coseno iperbolico di arg, definito come (exp(arg) + exp(-arg))/2.
Restituisce una stringa contenente una rappresentazione binaria di un dato argomento numero. Il più grande numero che può essere convertito è 4294967295 in decimale, risultante in una stringa composta da 32 volte la cifra 1.
Vedere anche bindec(), decoct(), dechex() e base_convert().
Restituisce una stringa contenente una rappresentazione esadecimale di un dato argomento numero. Il più grande numero che puù essere convertito è 2147483647 in decimale risultante in "7fffffff".
Vedere anche hexdec(), decbin(), decoct() e base_convert().
Restituisce una stringa contenente una rappresentazione in ottale di un dato argomento numero. Il più grande numero che può essere convertito è 2147483647 in decimale risultante in "17777777777". Vedere anche octdec().
Vedere anche octdec(), decbin(), dechex() e base_convert().
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
deg2rad -- Converte il numero dato in gradi nell'equivalente espresso in radiantiQuesta funzione converte numero da gradi al valore equivalente espresso in radianti.
Vedere anche rad2deg().
Restituisce e elevato alla potenza di arg.
Nota: 'e' è la base del sistema dei logaritmi dei numeri naturali, e vale 2.718282.
(PHP 4 >= 4.1.0, PHP 5)
expm1 -- Restituisce exp(numero) - 1, computato in maniera tale da essere accurato anche se il valore del numero è vicino a zeroAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Questa funzione non è implementata su piattaforme Windows
Restituisce il primo intero più piccolo di numero, se necessario. Il valore restituito da floor() è ancora di tipo float, poiché la gamma di valori del tipo float è solitamente più grande di quella del tipo integer.
(PHP 4 >= 4.2.0, PHP 5)
fmod -- Returns the floating point remainder (modulo) of the division of the argumentsReturns the floating point remainder of dividing the dividend (x) by the divisor (y). The reminder (r) is defined as: x = i * y + r, for some integer i. If y is non-zero, r has the same sign as x and a magnitude less than the magnitude of y.
Restituisce il valore massimo che può essere restituito da una chiamata alla funzione rand().
Vedere anche rand(), srand() e mt_getrandmax().
Restituisce l'equivalente decimale di un numero esadecimale rappresentato dall'argomento stringa_esadecimale. hexdec() converte una stringa esadecimale in un numero decimale. Il più grande numero che può essere convertito è 7fffffff o 2147483647 espresso in decimale.
hexdec() ignora i caratteri non esadecimali che incontra.
Vedere anche dechex(), bindec(), octdec() e base_convert().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce TRUE se val è un numero finito valido all'interno del range dei float, come definito da PHP su questa piattaforma.
Vedere anche is_infinite() e is_nan().
Restituisce TRUE se val è infinito (positivo o negativo), come il risultato di log(0) o ogni altro valore troppo grande per essere contenuto nel range dei float di una determinata piattaforma.
Vedere anche is_finite() e is_nan().
Restituisce TRUE se val 'non è un numero', come il risultato di acos(1.01).
Vedere anche is_finite() e is_infinite().
lcg_value() restituisce uno pseudo numero casuale nell'intervallo (0, 1). La funzione combina due GC con periodo di 2^31 - 85 e 2^31 - 249. Il periodo di questa funzione è uguale al prodotto dei due primi.
Restituisce il logaritmo in base-10 di arg.
Vedere anche: log()
(PHP 4 >= 4.1.0, PHP 5)
log1p -- Restituisce log(1 + numero), computato in maniera tale da essere accurato anche se il valore del numero è vicino a zeroAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Questa funzione non è implementata su piattaforme Windows
Se si specifica il parametro opzionale base, la funzione log() restituisce logbase arg, altrimenti log() il logaritmo naturale di arg.
Nota: Il parametro base è disponibile dalla versione 4.3.0 di PHP.
Si può comunque calcolare il logaritmo in base b di un numero n, usando la formula matematica: logb(n) = log(n)/log(b), dove log è il logaritmo neperiano (o naturale).
Vedere anche exp().
max() restituisce il numericamente più grande dei valori dati come parametro.
Se il primo ed unico parametro è un array, max() restituisce il massimo dei valori di tale array. Se il primo parametro è un integer, string o double, si ha bisogno almeno di due parametri e max() restituisce il maggiore di tali valori. Si può confrontare un numero illimitato di valori.
Nota: Le stringhe non numeriche saranno considerate dal PHP come 0, ma verrà restituita la stringa se questa è il più alto valore numerico. Se vi sono più argomenti considerati come 0, la funzione max() restituirà il primo (il valore più a sinistra).
Esempio 1. Esempio di max()
|
min() restituisce il numericamente più piccolo dei valori dati come parametro.
Se il primo ed unico pareametro è un array, la funzione min() restituisce il valore più basso nell'array. Se il primo parametro è un intero, una stringa, o un float, occorrono almeno due parametri e min() restituisce il minore tra questi. Si può confrontare un numero illimitato di valori.
Nota: Le stringhe non numeriche saranno considerate dal PHP come 0, ma verrà restituita la stringa se questa è il più basso valore numerico. Se vi sono più argomenti considerati come 0, la funzione min() restituirà il primo (il valore più a sinistra).
Esempio 1. Esempio di uso di min()
|
Restituisce il massimo valore che può essere restituito da una chiamata alla funzione mt_rand().
Vedere anche mt_rand(), mt_srand() e getrandmax().
Molti generatori di numeri casuali di vecchie libc hanno caratteristiche dubbie o sconosciute e sono lenti. Di default, PHP usa il generatore di numeri casuali libc con la funzione rand(). La funzione mt_rand() è un sostituto per questa. Usa un generatore di numeri casuali con caratteristiche conosciute, il Mersenne Twister, il quale produce numeri casuali quattro volte più velocemente di libc.
Se invocata senza i parametri opzionali min, max, mt_rand() restituisce un valore pseudo-casuale compreso fra 0 e RAND_MAX. Se ad esempio si desidera un numero casuale compreso fra 5 e 15 (inclusi), usare mt_rand (5, 15).
Nota: Come in PHP 4.2.0, non vi è necessità di inizializzare il generatore di numeri casuali con srand() oppure con mt_srand() poichè viene eseguito in modo automatico.
Nota: Nelle versioni precedenti la 3.0.7 il significato di max era range. Per ottenere lo stesso risultato in queste vecchie versioni un breve esempio dovrebbe essere il seguente: mt_rand (5, 11), si otterrà un numero casuale compreso fra 5 e 15.
Vedere anche mt_srand(), mt_getrandmax() e rand().
Inizializza il generatore di numeri casuali con il parametro seme. A partire dalla versione 4.2.0 di PHP il parametro seme è diventato opzionale, e, per default, viene impostato ad un valore random.
Nota: Come in PHP 4.2.0, non vi è necessità di inizializzare il generatore di numeri casuali con srand() oppure con mt_srand() poichè viene eseguito in modo automatico.
Vedere anche mt_rand(), mt_getrandmax() e srand().
Restituisce l'equivalente decimale del numero ottale rappresentato dall'argomento stringa_ottale. OctDec converte una stringa ottale in un numero decimale. Il più grande numero che può essere convertito è 17777777777 o 2147483647 in decimale.
Vedere anche decoct(), bindec(), hexdec() e base_convert().
Restituisce una appossimazione di pi. Il valore restituito è un float e ha precisione secondo la direttiva precision del file php.ini, che ha come valore predefinito 14. Inoltre, si può usare la costante M_PI che permette di ottenere risultati identici all'uso di pi().
Restituisce base elevato alla potenza di esp. Se possibile, questa funzione restituisce un integer.
Se la potenza non può essere computata, viene generato un errore, e pow() restituirà FALSE. dalla versione 4.2.0 di PHP la funzione pow() non genera alcun warning.
Nota: Il PHP non può gestire valori negativi per bases.
Avvertimento |
Nel PHP 4.0.6 e precedenti, pow() restituiva sempre un float e non generava alcun errore. |
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
rad2deg -- Converte un numero in radianti nell'equivalente numero in gradiQuesta funzione converte numero da radianti a gradi.
Vedere anche deg2rad().
Se chiamata senza i parametri opzionali min, max, rand() restituisce un valore pseudo casuale compreso fra 0 e RAND_MAX. Se ad esempio si desidera un numero casuale compreso fra 5 e 15 (inclusi) usare rand (5, 15).
Nota: Su alcune piattaforme (come Windows) RAND_MAX vale soltanto 32768. Se si desidera un range più ampio di 32768, indicare i parametri min e max, questo permette di avere range maggiori di RAND_MAX, oppure si valuti l'utilizzo di mt_rand()
Nota: Come in PHP 4.2.0, non vi è necessità di inizializzare il generatore di numeri casuali con srand() oppure con mt_srand() poichè viene eseguito in modo automatico.
Nota: Nelle versioni precedenti la 3.0.7 il significato di max era range. Per ottenere lo stesso risultato in queste vecchie versioni un breve esempio dovrebbe essere il seguente: rand (5, 11), si otterrà un numero casuale compreso fra 5 e 15.
Vedere anche: srand(), getrandmax() e mt_rand().
Restituisce il valore arrotondato di val con la precisione specificata (numero di cifre dopo il punto decimale). precisione può anche essere negativa o zero (predefinito).
Nota: Il PHP non maneggia correttamente stringhe quali "12,300.2" in maniera predefinita. Fare riferimento a conversione da stringhe.
Nota: Il parametro precisione è disponibile dal PHP 4.
Vedere anche: ceil(), floor() e number_format().
La funzione sin() restituisce il seno di arg. Il parametro arg viene espresso in radianti.
Restituisce il seno iperbolico di arg, definito come (exp(arg) - exp(-arg))/2.
Inizializza il generatore di numeri casuali con seme. A partire dalla versione 4.2.0 di PHP il parametro seme è opzionale, e per default viene impostato ad un valore casuale.
Nota: Come in PHP 4.2.0, non vi è necessità di inizializzare il generatore di numeri casuali con srand() oppure con mt_srand() poichè viene eseguito in modo automatico.
Vedere anche: rand(), getrandmax() e mt_srand().
La funzione tan() restituisce la tangente del parametro arg. Il parametro arg deve essere espresso in radianti.
The MaxDB PHP extension allows you to access the functionality provided by MaxDB 7.5.0 and above. More information about the MaxDB Database server can be found at http://www.mysql.com/products/maxdb/.
The MaxDB PHP extension is compatible to the MySQL mysqli extension. There are only minor differences in the behaviour of some functions due to the differences of the underlying database servers, MaxDB and MySQL.
The main differences to mysqli are in the following functions:
maxdb_character_set_name() - Returns only ascii or unicode. |
maxdb_get_client_info() - Returns a different version string. |
maxdb_get_client_version() - Returns a different version string. |
maxdb_get_host_info() - Returns localhost or hostname. |
maxdb_get_server_info() - Returns a different version string. |
maxdb_get_server_version() - Returns a different version string. |
maxdb_kill() - Only disconnects the session. |
maxdb_multi_query() - Can not handle multiple SQL statements. |
maxdb_next_result() - Function returns always false. |
maxdb_options() - Supports a different set of options. |
maxdb_report() - Supports a different report mode. |
maxdb_stat() - Returns a different system status string. |
maxdb_stmt_store_result() - Is not necessary for MaxDB. |
maxdb_store_result() - Is not necessary for MaxDB. |
Documentation for MaxDB can be found at http://dev.mysql.com/doc/maxdb/.
In order to have these functions available, you must compile PHP with MaxDB support. Additionally, you must have the MaxDB SQLDBC runtime library available to access the MaxDB server.
Documentation for MaxDB SQLDBC can be found at http://dev.mysql.com/doc/maxdb/.
Download the MaxDB SQLDBC package from http://dev.mysql.com/downloads/maxdb/clients.html.
By using the --with-maxdb[=DIR] configuration option you enable PHP to access MaxDB databases. [DIR] points to the directory that contains the installed MaxDB SQLDBC package.
Windows users will need to enable php_maxdb.dll inside of php.ini.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. MaxDB Configuration Options
Name | Default | Changeable | Changelog |
---|---|---|---|
maxdb.default_host | NULL | PHP_INI_ALL | |
maxdb.default_db | NULL | PHP_INI_ALL | |
maxdb.default_user | NULL | PHP_INI_ALL | |
maxdb.default_pw | NULL | PHP_INI_ALL | |
maxdb.long_readlen | "200" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
The default server host to use when connecting to the database server if no other host is specified.
The default server database to use when connecting if no other database is specified.
The default user name to use when connecting to the database server if no other name is specified.
The default password to use when connecting to the database server if no other password is specified.
The default maximum length of bytes that is transferred to the client if long data is retrieved from the MaxDB database server.
Represents a connection between PHP and a MaxDB database.
autocommit - turns on or off auto-commiting database modifications
change_user - changes the user of the specified database connection
character_set_name - returns the default character set for the database connection
close - closes a previously opened connection
commit - commits the current transaction
connect - opens a new connection to MaxDB database server
debug - performs debugging operations
dump_debug_info - dumps debug information
get_client_info - returns client version
get_host_info - returns type of connection used
get_server_info - returns version of the MaxDB server
get_server_version - returns version of the MaxDB server
init - initializes maxdb object
info - retrieves information about the most recently executed query
kill - asks the server to kill a MaxDB thread
multi_query - performs multiple queries
more_results - check if more results exist from currently executed multi-query
next_result - reads next result from currently executed multi-query
options - set options
ping - pings a server connection or reconnects if there is no connection
prepare - prepares a SQL query
query - performs a query
real_connect - attempts to open a connection to MaxDB database server
escape_string - escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection
rollback - rolls back the current transaction
select_db - selects the default database
ssl_set - sets ssl parameters
stat - gets the current system status
stmt_init- initializes a statement for use with maxdb_stmt_prepare
store_result - transfers a resultset from last query
use_result - transfers an unbuffered resultset from last query
thread-safe - returns whether thread safety is given or not
affected_rows - gets the number of affected rows in a previous MaxDB operation
client_info - returns the MaxDB client version as a string
client_version - returns the MaxDB client version as an integer
errno - returns the error code for the most recent function call
error - returns the error string for the most recent function call
field_count - returns the number of columns for the most recent query
host_info - returns a string representing the type of connection used
info - retrieves information about the most recently executed query
insert_id - returns the auto generated id used in the last query
protocol_version - returns the version of the MaxDB protocol used
sqlstate - returns a string containing the SQLSTATE error code for the last error
thread_id - returns the thread ID for the current connection
warning_count - returns the number of warnings generated during execution of the previous SQL statement
Represents a prepared statement.
bind_param - binds variables to a prepared statement
bind_result - binds variables to a prepared statement for result storage
close - closes a prepared statement
data-seek - seeks to an arbitrary row in a statement result set
execute - executes a prepared statement
fetch - fetches result from a prepared statement into bound variables
free_result - frees stored result memory for the given statement handle
result_metadata - retrieves a resultset from a prepared statement for metadata information
prepare - prepares a SQL query
send_long_data - sends data in chunks
close_long_data - end sending long data
reset - resets a prepared statement
store_result - buffers complete resultset from a prepared statement
affected_rows - returns affected rows from last statement execution
errno - returns errorcode for last statement function
errno - returns errormessage for last statement function
param_count - returns number of parameter for a given prepare statement
sqlstate - returns a string containing the SQLSTATE error code for the last statement function
Represents the result set obtained from a query against the database.
close - closes resultset
data_seek - moves internal result pointer
fetch_field - gets column information from a resultset
fetch_fields - gets information for all columns from a resulset
fetch_field_direct - gets column information for specified column
fetch_array - fetches a result row as an associative array, a numeric array, or both.
fetch_assoc - fetches a result row as an associative array
fetch_object - fetches a result row as an object
fetch_row - gets a result row as an enumerated array
close - frees result memory
field_seek - set result pointer to a specified field offset
current_field - returns offset of current fieldpointer
field_count - returns number of fields in resultset
lengths - returns an array of columnlengths
num_rows - returns number of rows in resultset
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
The following constants to use with maxdb_options() are defined. For further description of these constants see http://dev.mysql.com/doc/maxdb/.
Tabella 2. MaxDB PHP client constants
Constant | Description |
---|---|
MAXDB_COMPNAME | The component name used to initialise the SQLDBC runtime environment. |
MAXDB_APPLICATION | The application to be connected to the database. |
MAXDB_APPVERSION | The version of the application. |
MAXDB_SQLMODE | The SQL mode. |
MAXDB_UNICODE | TRUE, if the connection is an unicode (UCS2) client or FALSE, if not. |
MAXDB_TIMEOUT | The maximum allowed time of inactivity after which the connection to the database is closed by the system. |
MAXDB_ISOLATIONLEVEL | Specifies whether and how shared locks and exclusive locks are implicitly requested or released. |
MAXDB_PACKETCOUNT | The number of different request packets used for the connection. |
MAXDB_STATEMENTCACHESIZE | The number of prepared statements to be cached for the connection for re-use. |
MAXDB_CURSORPREFIX | The prefix to use for result tables that are automatically named. |
The function maxdb_fetch_array() uses a constant for the different types of result arrays. The following constants are defined:
Tabella 3. MaxDB fetch constants
Constant | Description |
---|---|
MAXDB_ASSOC | Columns are returned into the array having the fieldname as the array index. |
MAXDB_ASSOC_UPPER | Columns are returned into the array having the upper case fieldname as the array index. |
MAXDB_ASSOC_LOWER | Columns are returned into the array having the lower case fieldname as the array index. |
MAXDB_BOTH | Columns are returned into the array having both a numerical index and the fieldname as the array index. |
MAXDB_NUM | Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result. |
All examples in the MaxDB PHP documentation use the HOTELDB demo database from MaxDB. More about this database can be found at http://dev.mysql.com/doc/maxdb/en/98/11b83fa6b33c17e10000000a114084/frameset.htm.
To use the examples in the MaxDB PHP documentation, you have to load the tutorial data into your database. Then you have to set maxdb.default_db in php.ini to the database that contains the tutorial data.
This simple example shows how to connect, execute a query, print resulting rows and disconnect from a MaxDB database.
Esempio 1. MaxDB extension overview example
|
The following example shows how to bind variables to a SELECT INTO statement.
Esempio 2. Example for use of SELECT INTO statements
|
The following example shows how to use MaxDB database procedures.
Esempio 3. Example fore using database procedures
|
(PECL)
maxdb_affected_rows(no version information, might be only in CVS)
maxdb->affected_rows -- Gets the number of affected rows in a previous MaxDB operationProcedural style:
int maxdb_affected_rows ( resource link )Object oriented style (property):
class maxdb {maxdb_affected_rows() returns the number of rows affected by the last INSERT, UPDATE, or DELETE query associated with the provided link parameter. If this number cannot be determined, this function will return -1.
Nota: For SELECT statements maxdb_affected_rows() works like maxdb_num_rows().
The maxdb_affected_rows() function only works with queries which modify a table. In order to return the number of rows from a SELECT query, use the maxdb_num_rows() function instead.
An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the number of rows affected can not be determined.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Affected rows (INSERT): 15 Affected rows (UPDATE): 15 Affected rows (DELETE): 0 Affected rows (SELECT): 15 |
(PECL)
maxdb_autocommit(no version information, might be only in CVS)
maxdb->auto_commit -- Turns on or off auto-commiting database modificationsProcedural style:
bool maxdb_autocommit ( resource link, bool mode )Object oriented style (method)
class maxdb {maxdb_autocommit() is used to turn on or off auto-commit mode on queries for the database connection represented by the link resource.
This function is an alias of: maxdb_stmt_bind_param()
This function alias is deprecated and only exists for backwards compatibility reasons. It is recommended to not use this function as one day it may be removed from PHP.
This function is an alias of: maxdb_stmt_bind_result().
This function alias is deprecated and only exists for backwards compatibility reasons. It is recommended to not use this function as one day it may be removed from PHP.
(PECL)
maxdb_change_user(no version information, might be only in CVS)
maxdb->change_user -- Changes the user of the specified database connectionProcedural style:
bool maxdb_change_user ( resource link, string user, string password, string database )Object oriented style (method):
class maxdb {maxdb_change_user() is used to change the user of the specified database connection as given by the link parameter and to set the current database to that specified by the database parameter.
In order to successfully change users a valid username and password parameters must be provided and that user must have sufficient permissions to access the desired database. If for any reason authorization fails, the current user authentication will remain.
Nota: Using this command will always cause the current database connection to behave as if was a completely new database connection, regardless of if the operation was completed successfully. This reset includes performing a rollback on any active transactions, closing all temporary tables, and unlocking all locked tables.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Result: a Database running |
(PECL)
maxdb_character_set_name(no version information, might be only in CVS)
maxdb->character_set_name -- Returns the default character set for the database connectionProcedural style:
string maxdb_character_set_name ( resource link )Object oriented style (method):
class maxdb {Returns the current character set for the database connection specified by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would be produce the following output:
Current character set is ascii |
This function is an alias of: maxdb_character_set_name().
This function alias is deprecated and only exists for backwards compatibility reasons. It is recommended to not use this function as one day it may be removed from PHP.
(PECL)
maxdb_close_long_data(no version information, might be only in CVS)
maxdb->close_long_data -- Alias di maxdb_stmt_close_long_data()This function is an alias of: maxdb_stmt_close_long_data().
This function alias is deprecated and only exists for backwards compatibility reasons. It is recommended to not use this function as one day it may be removed from PHP.
(PECL)
maxdb_close(no version information, might be only in CVS)
maxdb->close -- Closes a previously opened database connectionProcedural style:
bool maxdb_close ( resource link )Object oriented style (method):
class maxdb {The maxdb_close() function closes a previously opened database connection specified by the link parameter.
(PECL)
maxdb_commit(no version information, might be only in CVS)
maxdb->commit -- Commits the current transactionProcedural style:
bool maxdb_commit ( resource link )Object oriented style (method)
class maxdb {Commits the current transaction for the database connection specified by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples produces no output.
The maxdb_connect_errno() function will return the last error code number for last call to maxdb_connect(). If no errors have occured, this function will return zero.
An error code value for the last call to maxdb_connect(), if it failed. zero means no error occurred.
The above example would produce the following output:
PHP Warning: maxdb_connect(): -4008 POS(1) Unknown user name/password combination [08004] <...> Can't connect to localhost. Errorcode: -4008 |
The maxdb_connect_error() function is identical to the corresponding maxdb_connect_errno() function in every way, except instead of returning an integer error code the maxdb_connect_error() function will return a string representation of the last error to occur for the last maxdb_connect() call. If no error has occured, this function will return an empty string.
The above example would produce the following output:
PHP Warning: maxdb_connect(): -4008 POS(1) Unknown user name/password combination <...> Can't connect to localhost. Error: POS(1) Unknown user name/password combination |
(PECL)
maxdb_connect(no version information, might be only in CVS)
maxdb() -- Open a new connection to the MaxDB serverProcedural style
resource maxdb_connect ( [string host [, string username [, string passwd [, string dbname [, int port [, string socket]]]]]] )Object oriented style (constructor):
class maxdb {The maxdb_connect() function attempts to open a connection to the MaxDB Server running on host which can be either a host name or an IP address. Passing the string "localhost" to this parameter, the local host is assumed. If successful, the maxdb_connect() will return an resource representing the connection to the database, or FALSE on failure.
The username and password parameters specify the username and password under which to connect to the MaxDB server. If the password is not provided (the NULL value is passed), the MaxDB server will attempt to authenticate the user against the maxdb.default_pw in php.ini.
The dbname parameter if provided will specify the default database to be used when performing queries. If not provied, the entry maxdb.default_db in php.ini is used.
The port and socket parameters are ignored for the MaxDB server.
Returns a resource which represents the connection to a MaxDB Server or FALSE if the connection failed.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Host information: localhost |
(PECL)
maxdb_data_seek(no version information, might be only in CVS)
result->data_seek -- Adjusts the result pointer to an arbitary row in the resultProcedural style:
bool maxdb_data_seek ( resource result, int offset )Object oriented style (method):
class result {The maxdb_data_seek() function seeks to an arbitrary result pointer specified by the offset in the result set represented by result. The offset parameter must be between zero and the total number of rows minus one (0..maxdb_num_rows() - 1).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
City: Irvine State: CA |
The maxdb_debug() can be used to trace the SQLDBC communication. The following strings can be used as a parameter to maxdb_debug():
TRACE SHORT ON|OFF - Enables/disables method call trace. |
TRACE LONG ON|OFF - Enables/disables method argument and detail debug trace. |
TRACE PACKET ON|OFF|<size> - Enables/disables packet trace, limiting the size of the traced object to the specified number of bytes, or 1000 if no size is specified. |
TRACE SQL ON|OFF - Enables/disables high level api trace. |
TRACE TIMESTAMP ON|OFF - Enables/disables a timestamp prefix on each line that is traced. |
TRACE SIZE <size> - Limits the size of the trace file to <size> bytes, at least 8192 bytes are required. |
(PECL)
maxdb_disable_reads_from_master(no version information, might be only in CVS)
maxdb->disable_reads_from_master -- Disable reads from masterProcedural style:
bool maxdb_disable_reads_from_master ( resource link )Object oriented style (method):
class maxdb {Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PECL)
maxdb_errno(no version information, might be only in CVS)
maxdb->errno -- Returns the error code for the most recent function callProcedural style:
int maxdb_errno ( resource link )Object oriented style (property):
class maxdb {The maxdb_errno() function will return the last error code for the most recent MaxDB function call that can succeed or fail with respect to the database link defined by the link parameter. If no errors have occured, this function will return zero.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
PHP Warning: maxdb_query(): -4005 POS(8) Unknown column name:XXX [42000] <...> Errorcode: -4005 |
Procedural style:
string maxdb_error ( resource link )Object oriented style (property)
class maxdb {The maxdb_error() function is identical to the corresponding maxdb_errno() function in every way, except instead of returning an integer error code the maxdb_error() function will return a string representation of the last error to occur for the database connection represented by the link parameter. If no error has occured, this function will return an empty string.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
PHP Warning: maxdb_query(): -4005 POS(8) Unknown column name:XXX [42000] Errormessgae: POS(8) Unknown column name:XXX |
This function is an alias of: maxdb_stmt_execute().
This function alias is deprecated and only exists for backwards compatibility reasons. It is recommended to not use this function as one day it may be removed from PHP.
(PECL)
maxdb_fetch_array(no version information, might be only in CVS)
result->fetch_array -- Fetch a result row as an associative, a numeric array, or bothProcedural style:
mixed maxdb_fetch_array ( resource result [, int resulttype] )Object oriented style (method):
class result {Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.
maxdb_fetch_array() is an extended version of the maxdb_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the maxdb_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Nota: This function sets NULL fields to PHP NULL value.
If two or more columns of the result have the same field names, the last column will take precedence and overwrite the earlier data. In order to access multiple columns with the same name, the numerically indexed version of the row must be used.
The optional second argument resulttype is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MAXDB_ASSOC, MAXDB_ASSOC_UPPER, MAXDB_ASSOC_LOWER, MAXDB_NUM, or MAXDB_BOTH. By default the maxdb_fetch_array() function will assume MAXDB_BOTH, which is a combination of MAXDB_NUM and MAXDB_ASSOC for this parameter.
By using the MAXDB_ASSOC constant this function will behave identically to the maxdb_fetch_assoc(), while MAXDB_NUM will behave identically to the maxdb_fetch_row() function. The final option MAXDB_BOTH will create a single array with the attributes of both.
By using the MAXDB_ASSOC_UPPER constant, the behaviour of this function is identical to the use of MAXDB_ASSOC except the array index of a column is the fieldname in upper case.
By using the MAXDB_ASSOC_LOWER constant, the behaviour of this function is identical to the use of MAXDB_ASSOC except the array index of a column is the fieldname in lower case.
Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
New York (NY) New York (NY) Long Island (NY) |
(PECL)
maxdb_fetch_assoc(no version information, might be only in CVS)
maxdb->fetch_assoc -- Fetch a result row as an associative arrayProcedural style:
array maxdb_fetch_assoc ( resource result )Object oriented style (method):
class result {Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.
The maxdb_fetch_assoc() function is used to return an associative array representing the next row in the result set for the result represented by the result parameter, where each key in the array represents the name of one of the result set's columns.
If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using maxdb_fetch_row() or add alias names.
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Nota: This function sets NULL fields to PHP NULL value.
Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
New York (NY) New York (NY) Long Island (NY) Albany (NY) Washington (DC) Washington (DC) Washington (DC) Silver Spring (MD) Daytona Beach (FL) Deerfield Beach (FL) Clearwater (FL) Cincinnati (OH) Detroit (MI) Rosemont (IL) Chicago (IL) Chicago (IL) New Orleans (LA) Dallas (TX) Los Angeles (CA) Hollywood (CA) Long Beach (CA) Palm Springs (CA) Irvine (CA) Santa Clara (CA) Portland (OR) |
(PECL)
maxdb_fetch_field_direct(no version information, might be only in CVS)
result->fetch_field_direct -- Fetch meta-data for a single fieldProcedural style:
mixed maxdb_fetch_field_direct ( resource result, int fieldnr )Object oriented style (method):
class result {maxdb_fetch_field_direct() returns an resource which contains field definition informations from specified resultset. The value of fieldnr must be in the range from 0 to number of fields - 1.
Returns an resource which contains field definition informations or FALSE if no field information for specified fieldnr is available.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Name: CNO Table: max. Len: 4 Flags: -1 Type: 0 |
(PECL)
maxdb_fetch_field(no version information, might be only in CVS)
result->fetch_field -- Returns the next field in the result setProcedural style:
mixed maxdb_fetch_field ( resource result )Object oriented style (method):
class result {The maxdb_fetch_field() returns the definition of one column of a result set as an resource. Call this function repeatedly to retrieve information about all columns in the result set. maxdb_fetch_field() returns FALSE when no more fields are left.
Returns an resource which contains field definition informations or FALSE if no field information is available.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Name: NAME Table: max. Len: 10 Flags: -1 Type: 2 Name: CNO Table: max. Len: 4 Flags: -1 Type: 0 |
(PECL)
maxdb_fetch_fields(no version information, might be only in CVS)
result->fetch_fields -- Returns an array of resources representing the fields in a result setProcedural Style:
mixed maxdb_fetch_fields ( resource result )Object oriented style (method):
class result {This function serves an identical purpose to the maxdb_fetch_field() function with the single difference that, instead of returning one resource at a time for each field, the columns are returned as an array of resources.
Returns an array of resources which contains field definition informations or FALSE if no field information is available.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Name: NAME Table: max. Len: 10 Flags: -1 Type: 2 Name: CNO Table: max. Len: 4 Flags: -1 Type: 0 |
(PECL)
maxdb_fetch_lengths(no version information, might be only in CVS)
result->lengths -- Returns the lengths of the columns of the current row in the result setProcedural style:
array maxdb_fetch_lengths ( resource result )Object oriented style (property):
class result {The maxdb_fetch_lengths() function returns an array containing the lengths of every column of the current row within the result set represented by the result parameter. If successful, a numerically indexed array representing the lengths of each column is returned or FALSE on failure.
An array of integers representing the size of each column (not including any terminating null characters). FALSE if an error occurred.
maxdb_fetch_lengths() is valid only for the current row of the result set. It returns FALSE if you call it before calling maxdb_fetch_row/array/resource or after retrieving all rows in the result.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Field 1 has Length 4 Field 2 has Length 3 Field 3 has Length 5 Field 4 has Length 6 Field 5 has Length 5 Field 6 has Length 21 |
(PECL)
maxdb_fetch_object(no version information, might be only in CVS)
result->fetch_object -- Returns the current row of a result set as an objectProcedural style:
object maxdb_fetch_object ( object result )Object oriented style (method):
class result {The maxdb_fetch_object() will return the current row result set as an object where the attributes of the object represent the names of the fields found within the result set. If no more rows exist in the current result set, NULL is returned.
Returns an object that corresponds to the fetched row or NULL if there are no more rows in resultset.
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Nota: This function sets NULL fields to PHP NULL value.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
New York (NY) New York (NY) Long Island (NY) Albany (NY) Washington (DC) Washington (DC) Washington (DC) Silver Spring (MD) Daytona Beach (FL) Deerfield Beach (FL) Clearwater (FL) Cincinnati (OH) Detroit (MI) Rosemont (IL) Chicago (IL) Chicago (IL) New Orleans (LA) Dallas (TX) Los Angeles (CA) Hollywood (CA) Long Beach (CA) Palm Springs (CA) Irvine (CA) Santa Clara (CA) Portland (OR) |
(PECL)
maxdb_fetch_row(no version information, might be only in CVS)
result->fetch_row -- Get a result row as an enumerated arrayProcedural style:
mixed maxdb_fetch_row ( resource result )Object oriented style (method):
class result {Returns an array that corresponds to the fetched row, or NULL if there are no more rows.
maxdb_fetch_row() fetches one row of data from the result set represented by result and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to the maxdb_fetch_row() function will return the next row within the result set, or FALSE if there are no more rows.
maxdb_fetch_row() returns an array that corresponds to the fetched row or NULL if there are no more rows in result set.
Nota: This function sets NULL fields to PHP NULL value.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
New York (NY) New York (NY) Long Island (NY) Albany (NY) Washington (DC) Washington (DC) Washington (DC) Silver Spring (MD) Daytona Beach (FL) Deerfield Beach (FL) Clearwater (FL) Cincinnati (OH) Detroit (MI) Rosemont (IL) Chicago (IL) Chicago (IL) New Orleans (LA) Dallas (TX) Los Angeles (CA) Hollywood (CA) Long Beach (CA) Palm Springs (CA) Irvine (CA) Santa Clara (CA) Portland (OR) |
This function is an alias of: maxdb_stmt_fetch().
This function alias is deprecated and only exists for backwards compatibility reasons. It is recommended to not use this function as one day it may be removed from PHP.
(PECL)
maxdb_field_count(no version information, might be only in CVS)
maxdb->field_count -- Returns the number of columns for the most recent queryProcedural style:
int maxdb_field_count ( resource link )Object oriented style (method):
class maxdb {Returns the number of columns for the most recent query on the connection represented by the link parameter. This function can be useful when using the maxdb_store_result() function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above example produces no output.
(PECL)
maxdb_field_seek(no version information, might be only in CVS)
result->field_seek -- Set result pointer to a specified field offsetProcedural style:
bool maxdb_field_seek ( resource result, int fieldnr )Object oriented style (method):
class result {Sets the field cursor to the given offset. The next call to maxdb_fetch_field() will retrieve the field definition of the column associated with that offset.
Nota: To seek to the beginning of a row, pass an offset value of zero.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Name: NAME Table: max. Len: 10 Flags: -1 Type: 2 |
(PECL)
maxdb_field_tell(no version information, might be only in CVS)
result->current_field -- Get current field offset of a result pointerProcedural style:
int maxdb_field_tell ( resource result )Object oriented style (property):
class result {Returns the position of the field cursor used for the last maxdb_fetch_field() call. This value can be used as an argument to maxdb_field_seek().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Column 1: Name: NAME Table: max. Len: 10 Flags: -1 Type: 2 Column 2: Name: CNO Table: max. Len: 4 Flags: -1 Type: 0 |
(PECL)
maxdb_free_result(no version information, might be only in CVS)
result->free -- Frees the memory associated with a resultProcedural style:
void maxdb_free_result ( resource result )Object oriented style (method):
class result {The maxdb_free_result() function frees the memory associated with the result represented by the result parameter, which was allocated by maxdb_query(), maxdb_store_result() or maxdb_use_result().
Nota: You should always free your result with maxdb_free_result(), when your result resource is not needed anymore.
The maxdb_get_client_info() function is used to return a string representing the client version being used in the MaxDB extension.
The above examples would produce the following output:
Client library version: libSQLDBC <...> |
A number that represents the MaxDB client library version in format: main_version*10000 + minor_version *100 + sub_version. For example, 7.5.0 is returned as 70500.
This is useful to quickly determine the version of the client library to know if some capability exits.
(PECL)
maxdb_get_host_info(no version information, might be only in CVS)
maxdb->get_host_info -- Returns a string representing the type of connection usedProcdural style:
string maxdb_get_host_info ( resource link )Object oriented style (property):
class maxdb {The maxdb_get_host_info() function returns a string describing the connection represented by the link parameter is using.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Host info: localhost |
This function is an alias of: maxdb_stmt_result_metadata().
This function alias is deprecated and only exists for backwards compatibility reasons. It is recommended to not use this function as one day it may be removed from PHP.
(PECL)
maxdb_get_proto_info(no version information, might be only in CVS)
maxdb->protocol_version -- Returns the version of the MaxDB protocol usedProcedural style:
int maxdb_get_proto_info ( resource link )Object oriented style (property):
class maxdb {Returns an integer representing the MaxDB protocol version used by the connection represented by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Protocol version: 10 |
(PECL)
maxdb_get_server_info(no version information, might be only in CVS)
maxdb->server_info -- Returns the version of the MaxDB serverProcedural style:
string maxdb_get_server_info ( resource link )Object oriented style (property):
class maxdb {Returns a string representing the version of the MaxDB server that the MaxDB extension is connected to (represented by the link parameter).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Server version: Kernel 7<...> |
Procedural style:
int maxdb_get_server_version ( resource link )Object oriented style (property):
class maxdb {The maxdb_get_server_version() function returns the version of the server connected to (represented by the link parameter) as an integer.
The form of this version number is main_version * 10000 + minor_version * 100 + sub_version (i.e. version 7.5.0 is 70500).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Server version: 7<...> |
(PECL)
maxdb_info(no version information, might be only in CVS)
maxdb->info -- Retrieves information about the most recently executed queryProcedural style:
string maxdb_info ( resource link )Object oriented style (property)
class maxdb {The maxdb_info() function returns a string providing information about the last query executed. The nature of this string is provided below:
Tabella 1. Possible maxdb_info return values
Query type | Example result string |
---|---|
INSERT INTO...SELECT... | Records: 100 Duplicates: 0 Warnings: 0 |
INSERT INTO...VALUES (...),(...),(...) | Records: 3 Duplicates: 0 Warnings: 0 |
LOAD DATA INFILE ... | Records: 1 Deleted: 0 Skipped: 0 Warnings: 0 |
ALTER TABLE ... | Records: 3 Duplicates: 0 Warnings: 0 |
UPDATE ... | Rows matched: 40 Changed: 40 Warnings: 0 |
Nota: Queries which do not fall into one of the above formats are not supported. In these situations, maxdb_info() will return an empty string.
A character string representing additional information about the most recently executed query.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Records: 25 Duplicates: 0 Warnings: 0 |
Allocates or initializes a MaxDB resource suitable for maxdb_options() and maxdb_real_connect().
Nota: Any subsequent calls to any maxdb function (except maxdb_options()) will fail until maxdb_real_connect() was called.
(PECL)
maxdb_insert_id(no version information, might be only in CVS)
maxdb->insert_id -- Returns the auto generated id used in the last queryProcedural style:
mixed maxdb_insert_id ( resource link )Object oriented style (property):
class maxdb {The maxdb_insert_id() function returns the ID generated by a query on a table with a column having the DEFAULT SERIAL attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the DEFAULT SERIAL attribute, this function will return zero.
The value of the DEFAULT SERIAL field that was updated by the previous query. Returns zero if there was no previous query on the connection or if the query did not update an DEFAULT_SERIAL value.
Nota: If the number is greater than maximal int value, maxdb_insert_id() will return a string.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
New Record has id 1. |
(PECL)
maxdb_kill(no version information, might be only in CVS)
maxdb->kill -- Disconnects from a MaxDB serverProcedural style:
bool maxdb_kill ( resource link, int processid )Object oriented style (method)
class maxdb {This function is used to disconnect from a MaxDB server specified by the processid parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Error: Session not connected |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PECL)
maxdb_more_results(no version information, might be only in CVS)
maxdb->more_results -- Check if there any more query results from a multi querymaxdb_more_results() indicates if one or more result sets are available from a previous call to maxdb_multi_query().
(PECL)
maxdb_multi_query(no version information, might be only in CVS)
maxdb->multi_query -- Performs a query on the databaseProcedural style:
bool maxdb_multi_query ( resource link, string query )Object oriented style (method):
class maxdb {The maxdb_multi_query() works like the function maxdb_query(). Multiple queries are not yet supported.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
a |
(PECL)
maxdb_next_result(no version information, might be only in CVS)
maxdb->next_result -- Prepare next result from multi_querySince multiple queries are not yet supported, maxdb_next_result() returns always FALSE.
(PECL)
maxdb_num_fields(no version information, might be only in CVS)
result->field_count -- Get the number of fields in a resultProcedural style:
int maxdb_num_fields ( resource result )Object oriented style (property):
class result {maxdb_num_fields() returns the number of fields from specified result set.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Result set has 3 fields. |
Procedural style:
int maxdb_num_rows ( resource result )Object oriented style (property):
class maxdb {Returns the number of rows in the result set.
The use of maxdb_num_rows() depends on whether you use buffered or unbuffered result sets. In case you use unbuffered resultsets maxdb_num_rows() will not correct the correct number of rows until all the rows in the result have been retrieved.
Returns number of rows in the result set.
Nota: If the number of rows is greater than maximal int value, the number will be returned as a string.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Result set has 15 rows. |
Procedural style:
bool maxdb_options ( resource link, int option, mixed value )Object oriented style (method)
class maxdb {maxdb_options() can be used to set extra connect options and affect behavior for a connection.
This function may be called multiple times to set several options.
maxdb_options() should be called after maxdb_init() and before maxdb_real_connect().
The parameter option is the option that you want to set, the value is the value for the option. For detailed description of the options see http://dev.mysql.com/doc/maxdb/ The parameter option can be one of the following values:
Tabella 1. Valid options
Name | Description |
---|---|
MAXDB_COMPNAME | The component name used to initialise the SQLDBC runtime environment. |
MAXDB_APPLICATION | The application to be connected to the database. |
MAXDB_APPVERSION | The version of the application. |
MAXDB_SQLMODE | The SQL mode. |
MAXDB_UNICODE | TRUE, if the connection is an unicode (UCS2) client or FALSE, if not. |
MAXDB_TIMEOUT | The maximum allowed time of inactivity after which the connection to the database is closed by the system. |
MAXDB_ISOLATIONLEVEL | Specifies whether and how shared locks and exclusive locks are implicitly requested or released. |
MAXDB_PACKETCOUNT | The number of different request packets used for the connection. |
MAXDB_STATEMENTCACHESIZE | The number of prepared statements to be cached for the connection for re-use. |
MAXDB_CURSORPREFIX | The prefix to use for result tables that are automatically named. |
This function is an alias of: maxdb_stmt_param_count().
This function alias is deprecated and only exists for backwards compatibility reasons. It is recommended to not use this function as one day it may be removed from PHP.
(PECL)
maxdb_ping(no version information, might be only in CVS)
maxdb->ping -- Pings a server connection, or tries to reconnect if the connection has gone downProcedural style:
bool maxdb_ping ( resource link )Object oriented style (method):
class maxdb {Checks whether the connection to the server is working. If it has gone down, and global option maxdb.reconnect is enabled an automatic reconnection is attempted.
This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Our connection is ok! |
(PECL)
maxdb_prepare(no version information, might be only in CVS)
maxdb->prepare -- Prepare a SQL statement for executionProcedure style:
resource maxdb_prepare ( resource link, string query )Object oriented style (method)
class stmt {maxdb_prepare() prepares the SQL query pointed to by the null-terminated string query, and returns a statement handle to be used for further operations on the statement. The query must consist of a single SQL statement.
Nota: You should not add a terminating semicolon or \g to the statement.
The parameter query can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.
Nota: The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.
However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.
The parameter markers must be bound to application variables using maxdb_stmt_bind_param() and/or maxdb_stmt_bind_result() before executing the statement or fetching rows.
maxdb_stmt_execute(), maxdb_stmt_fetch(), maxdb_stmt_bind_param(), maxdb_stmt_bind_result(), maxdb_stmt_close()
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Rosemont is in district IL |
(PECL)
maxdb_query(no version information, might be only in CVS)
maxdb->query -- Performs a query on the databaseProcedural style:
mixed maxdb_query ( resource link, string query [, int resultmode] )Object oriented style (method):
class maxdb {The maxdb_query() function is used to simplify the act of performing a query against the database represented by the link parameter.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. For SELECT, SHOW, DESCRIBE or EXPLAIN maxdb_query() will return a result resource.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Table mycity successfully created. Select returned 25 rows. |
(PECL)
maxdb_real_connect(no version information, might be only in CVS)
maxdb->real_connect -- Opens a connection to a MaxDB serverProcedural style
bool maxdb_real_connect ( resource link [, string hostname [, string username [, string passwd [, string dbname [, int port [, string socket]]]]]] )Object oriented style (method)
class maxdb {maxdb_real_connect() attempts to establish a connection to a MaxDB database engine running on hostname.
This function differs from maxdb_connect():
maxdb_real_connect() needs a valid resource which has to be created by function maxdb_init()
With function maxdb_options() you can set various options for connection.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Connection: localhost <...> |
(PECL)
maxdb_real_escape_string(no version information, might be only in CVS)
maxdb->real_escape_string -- Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connectionProcedural style:
string maxdb_real_escape_string ( resource link, string escapestr )Object oriented style (method):
class maxdb {This function is used to create a legal SQL string that you can use in a SQL statement. The string escapestr is encoded to an escaped SQL string, taking into account the current character set of the connection.
Characters encoded are ', ".
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Warning: maxdb_query(): -5016 POS(43) Missing delimiter: ) <...> Error: 42000 1 Row inserted. |
(PECL)
maxdb_real_query(no version information, might be only in CVS)
maxdb->real_query -- Execute an SQL queryProcedural style
bool maxdb_real_query ( resource link, string query )Object oriented style (method):
class maxdb {The maxdb_real_query() is functionally identical with the maxdb_query().
Nota: In order to determine if a given query should return a result set or not, see maxdb_field_count().
Esempio 1. Procedural style
|
The above examples would produce the following output:
Warning: maxdb_query(): -4004 POS(18) Unknown table name:NONEXISTINGTABLE <...> |
(PECL)
maxdb_rollback(no version information, might be only in CVS)
maxdb->rollback -- Rolls back current transactionRollbacks the current transaction for the database specified by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
0 rows in table mycity. 25 rows in table mycity (after rollback). |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PECL)
maxdb_rpl_query_type(no version information, might be only in CVS)
maxdb->rpl_query_type -- Returns RPL query typeObject oriented style (method)
class maxdb {Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PECL)
maxdb_select_db(no version information, might be only in CVS)
maxdb->select_db -- Selects the default database for database queriesThe maxdb_select_db() function selects the default database (specified by the dbname parameter) to be used when performing queries against the database connection represented by the link parameter.
Nota: This function should only be used to change the default database for the connection. You can select the default database with 4th parameter in maxdb_connect().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Default database is <...>. Warning: maxdb_select_db(): -10709 Connection failed (RTE:database not running) <...> Warning: maxdb_query(): -10821 Session not connected [] <...> Warning: maxdb_close(): -10821 Session not connected [] <...> |
This function is an alias of: maxdb_stmt_send_long_data().
This function alias is deprecated and only exists for backwards compatibility reasons. It is recommended to not use this function as one day it may be removed from PHP.
(PECL)
maxdb_send_query(no version information, might be only in CVS)
maxdb->send_query -- Send the query and returnObject oriented style (method)
class maxdb {Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PECL)
maxdb_sqlstate(no version information, might be only in CVS)
maxdb->sqlstate -- Returns the SQLSTATE error from previous MaxDB operationProcedural style:
string maxdb_sqlstate ( resource link )Object oriented style (property):
class maxdb {Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC.
Nota: Note that not all MaxDB errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.
Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Warning: maxdb_query(): -6000 POS(20) Duplicate table name:CITY [I6000] <...> Error - SQLSTATE I6000. |
(PECL)
maxdb_ssl_set(no version information, might be only in CVS)
maxdb->ssl_set -- Used for establishing secure connections using SSLProcedural style:
bool maxdb_ssl_set ( resource link, string key, string cert, string ca, string capath, string cipher )Object oriented style (method):
class maxdb {Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PECL)
maxdb_stat(no version information, might be only in CVS)
maxdb->stat -- Gets the current system statusProcedural style:
string maxdb_stat ( resource link )Object oriented style (method):
class maxdb {maxdb_stat() returns a string containing several information about the MaxDB server running.
(PECL)
maxdb_stmt_affected_rows(no version information, might be only in CVS)
maxdb_stmt->affected_rows -- Returns the total number of rows changed, deleted, or inserted by the last executed statementProcedural style :
int maxdb_stmt_affected_rows ( resource stmt )Object oriented style (property):
class stmt {maxdb_stmt_affected_rows() returns the number of rows affected by INSERT, UPDATE, or DELETE query. If the last query was invalid or the number of rows can not determined, this function will return -1.
An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE/DELETE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query has returned an error or the number of rows can not determined.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
rows inserted: 4 |
(PECL)
maxdb_stmt_bind_param(no version information, might be only in CVS)
stmt->bind_param -- Binds variables to a prepared statement as parametersProcedural style:
bool maxdb_stmt_bind_param ( resource stmt, string types, mixed &var1 [, mixed &...] )Object oriented style (method):
class stmt {maxdb_stmt_bind_param() is used to bind variables for the parameter markers in the SQL statement that was passed to maxdb_prepare(). The string types contains one or more characters which specify the types for the corresponding bind variables.
Variables for SELECT INTO SQL statements can also be bound using maxdb_stmt_bind_param(). Parameters for database procedures can be bound using maxdb_stmt_bind_param(). See the examples how to use maxdb_stmt_bind_param() in this cases.
If a variable bound as INTO variable to a SQL statement was used before, the content of this variable is overwritten by the data of the SELECT INTO statement. A reference to this variable will be invalid after a call to maxdb_stmt_bind_param().
For INOUT parameters of database procedures the content of the bound INOUT variable is overwritten by the output value of the database procedure. A reference to this variable will be invalid after a call to maxdb_stmt_bind_param().
maxdb_stmt_bind_result(), maxdb_stmt_execute(), maxdb_stmt_fetch(), maxdb_prepare(), maxdb_stmt_send_long_data(), maxdb_stmt_errno(), maxdb_stmt_error()
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
1 Row inserted. 1 Row deleted. |
Esempio 3. Procedural style (SELECT INTO)
|
The above examples would produce the following output:
21.600000 |
Esempio 4. Procedural style (DB procedure)
|
The above examples would produce the following output:
a |
(PECL)
maxdb_stmt_bind_result(no version information, might be only in CVS)
stmt->bind_result -- Binds variables to a prepared statement for result storageProcedural style:
bool maxdb_stmt_bind_result ( resource stmt, mixed &var1 [, mixed &...] )Object oriented style (method):
class stmt {maxdb_stmt_bind_result() is used to associate (bind) columns in the result set to variables. When maxdb_stmt_fetch() is called to fetch data, the MaxDB client/server protocol places the data for the bound columns into the specified variables var1, ....
Nota: Note that all columns must be bound prior to calling maxdb_stmt_fetch(). Depending on column types bound variables can silently change to the corresponding PHP type.
A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time maxdb_stmt_fetch() is called.
maxdb_stmt_bind_param(), maxdb_stmt_execute(), maxdb_stmt_fetch(), maxdb_prepare(), maxdb_stmt_prepare(), maxdb_stmt_init(), maxdb_stmt_errno(), maxdb_stmt_error()
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
12203 Albany 60601 Chicago 60615 Chicago 45211 Cincinnati 33575 Clearwater 75243 Dallas 32018 Daytona Beach 33441 Deerfield Beach 48226 Detroit 90029 Hollywood 92714 Irvine 90804 Long Beach 11788 Long Island 90018 Los Angeles 70112 New Orleans 10019 New York 10580 New York 92262 Palm Springs 97213 Portland 60018 Rosemont 95054 Santa Clara 20903 Silver Spring 20005 Washington 20019 Washington 20037 Washington |
(PECL)
maxdb_stmt_close_long_data(no version information, might be only in CVS)
stmt->close_long_data -- Ends a sequence of maxdb_stmt_send_long_data()Procedural style:
bool maxdb_stmt_close_long_data ( resource stmt, int param_nr )Object oriented style (method):
class maxdb_stmt {This function has to be called after a sequence of maxdb_stmt_send_long_data(), that was started after maxdb_execute().
param_nr indicates which parameter to associate the end of data with. Parameters are numbered beginning with 0.
(PECL)
maxdb_stmt_close(no version information, might be only in CVS)
maxdb_stmt->close -- Closes a prepared statementProcedural style:
bool maxdb_stmt_close ( resource stmt )Object oriented style (method):
class maxdb_stmt {Closes a prepared statement. maxdb_stmt_close() also deallocates the statement handle pointed to by stmt. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.
(PECL)
maxdb_stmt_data_seek(no version information, might be only in CVS)
stmt->data_seek -- Seeks to an arbitray row in statement result setProcedural style:
bool maxdb_stmt_data_seek ( resource statement, int offset )Object oriented style (method):
class stmt {The maxdb_stmt_data_seek() function seeks to an arbitrary result pointer specified by the offset in the statement result set represented by statement. The offset parameter must be between zero and the total number of rows minus one (0..maxdb_stmt_num_rows() - 1).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
City: Dallas Zip: 75243 |
(PECL)
maxdb_stmt_errno(no version information, might be only in CVS)
maxdb_stmt->errno -- Returns the error code for the most recent statement callProcedural style :
int maxdb_stmt_errno ( resource stmt )Object oriented style (property):
class stmt {For the statement specified by stmt, maxdb_stmt_errno() returns the error code for the most recently invoked statement function that can succeed or fail.
Nota: For possible error codes see documentation of SQLDBC: http://dev.mysql.com/doc/maxdb/.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...> Error: -4004. |
(PECL)
maxdb_stmt_error(no version information, might be only in CVS)
maxdb_stmt->error -- Returns a string description for last statement errorProcedural style:
string maxdb_stmt_error ( resource stmt )Object oriented style (property):
class stmt {For the statement specified by stmt, maxdb_stmt_error() returns a containing the error message for the most recently invoked statement function that can succeed or fail.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...> Error: POS(23) Unknown table name:MYCITY. |
(PECL)
maxdb_stmt_execute(no version information, might be only in CVS)
stmt->execute -- Executes a prepared QueryProcedural style:
bool maxdb_stmt_execute ( resource stmt )Object oriented style (method):
class stmt {The maxdb_stmt_execute() function executes a query that has been previously prepared using the maxdb_prepare() function represented by the stmt resource. When executed any parameter markers which exist will automatically be replaced with the appropiate data.
If the statement is UPDATE, DELETE, or INSERT, the total number of affected rows can be determined by using the maxdb_stmt_affected_rows() function. Likewise, if the query yields a result set the maxdb_fetch() function is used.
Nota: When using maxdb_stmt_execute(), the maxdb_fetch() function must be used to fetch the data prior to preforming any additional queries.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
11111 (Georgetown,NY) 22222 (Hubbatown,CA) |
(PECL)
maxdb_stmt_fetch(no version information, might be only in CVS)
stmt->fetch -- Fetch results from a prepared statement into the bound variablesProcedural style:
bool maxdb_stmt_fetch ( resource stmt )Object oriented style (method):
class stmt {maxdb_stmt_fetch() returns row data using the variables bound by maxdb_stmt_bind_result().
Nota: Note that all columns must be bound by the application before calling maxdb_stmt_fetch().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
12203 (Albany) 60601 (Chicago) 60615 (Chicago) 45211 (Cincinnati) 33575 (Clearwater) 75243 (Dallas) 32018 (Daytona Beach) 33441 (Deerfield Beach) 48226 (Detroit) 90029 (Hollywood) 92714 (Irvine) 90804 (Long Beach) 11788 (Long Island) 90018 (Los Angeles) 70112 (New Orleans) 10019 (New York) 10580 (New York) 92262 (Palm Springs) 97213 (Portland) 60018 (Rosemont) 95054 (Santa Clara) 20903 (Silver Spring) 20005 (Washington) 20019 (Washington) 20037 (Washington) |
(PECL)
maxdb_stmt_free_result(no version information, might be only in CVS)
stmt->free_result -- Frees stored result memory for the given statement handleProcedural style:
void maxdb_stmt_free_result ( resource stmt )Object oriented style (method):
class stmt {The maxdb_stmt_free_result() function frees the result memory associated with the statement represented by the stmt parameter, which was allocated by maxdb_stmt_store_result().
(PECL)
maxdb_stmt_init(no version information, might be only in CVS)
maxdb->stmt_init -- Initializes a statement and returns an resource for use with maxdb_stmt_prepareProcedural style :
resource maxdb_stmt_init ( resource link )Object oriented style (property):
class maxdb {Allocates and initializes a statement resource suitable for maxdb_stmt_prepare().
Nota: Any subsequent calls to any maxdb_stmt function will fail until maxdb_stmt_prepare() was called.
(PECL)
maxdb_stmt_num_rows(no version information, might be only in CVS)
stmt->num_rows -- Return the number of rows in statements result setProcedural style :
int maxdb_stmt_num_rows ( resource stmt )Object oriented style (property):
class stmt {Returns the number of rows in the result set.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Number of rows: 25. |
(PECL)
maxdb_stmt_param_count(no version information, might be only in CVS)
stmt->param_count -- Returns the number of parameter for the given statementProcedural style:
int maxdb_stmt_param_count ( resource stmt )Object oriented style (property):
class stmt {maxdb_stmt_param_count() returns the number of parameter markers present in the prepared statement.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Statement has 2 markers. |
(PECL)
maxdb_stmt_prepare(no version information, might be only in CVS)
stmt->prepare -- Prepare a SQL statement for executionProcedure style:
bool maxdb_stmt_prepare ( resource stmt, string query )Object oriented style (method)
class stmt {maxdb_stmt_prepare() prepares the SQL query pointed to by the null-terminated string query. The statement resource has to be allocated by maxdb_stmt_init(). The query must consist of a single SQL statement.
Nota: You should not add a terminating semicolon or \g to the statement.
The parameter query can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.
Nota: The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.
However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.
The parameter markers must be bound to application variables using maxdb_stmt_bind_param() and/or maxdb_stmt_bind_result() before executing the statement or fetching rows.
maxdb_stmt_init(), maxdb_stmt_execute(), maxdb_stmt_fetch(), maxdb_stmt_bind_param(), maxdb_stmt_bind_result(), maxdb_stmt_close()
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Portland is in district OR |
(PECL)
maxdb_stmt_reset(no version information, might be only in CVS)
stmt->reset -- Resets a prepared statementProcedural style:
bool maxdb_stmt_reset ( resource stmt )Object oriented style (method):
class stmt {Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Procedural style:
resource maxdb_stmt_result_metadata ( resource stmt )Object oriented style (method):
class stmt {If a statement passed to maxdb_prepare() is one that produces a result set, maxdb_stmt_result_metadata() returns the result resource that can be used to process the meta information such as total number of fields and individual field information.
Nota: This result set pointer can be passed as an argument to any of the field-based functions that process result set metadata, such as:
The result set structure should be freed when you are done with it, which you can do by passing it to maxdb_free_result()
Nota: The result set returned by maxdb_stmt_result_metadata() contains only metadata. It does not contain any row results. The rows are obtained by using the statement handle with maxdb_fetch().
maxdb_stmt_result_metadata() returns a result resource or FALSE if an error occured.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Fieldname: ID |
(PECL)
maxdb_stmt_send_long_data(no version information, might be only in CVS)
stmt->send_long_data -- Send data in blocksProcedural style:
bool maxdb_stmt_send_long_data ( resource stmt, int param_nr, string data )Object oriented style (method)
class stmt {Allows to send parameter data to the server in pieces (or chunks). This function can be called multiple times to send the parts of a character or binary data value for a column, which must be one of the TEXT or BLOB datatypes.
param_nr indicates which parameter to associate the data with. Parameters are numbered beginning with 0. data is a string containing data to be sent.
Nota: For efficiency reasons, this function should be used after calling maxdb_execute(). In this case, the data is not stored on the client side. The end of the sequence must end with a call to maxdb_stmt_close_long_data().
Returns a string containing the SQLSTATE error code for the most recently invoked prepared statement function that can succeed or fail. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC.
Nota: Note that not all MaxDB errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.
Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...> Error: 42000. |
(PECL)
maxdb_stmt_store_result(no version information, might be only in CVS)
maxdb->store_result -- Transfers a result set from a prepared statementProcedural style:
bool maxdb_stmt_store_result ( resource stmt )Object oriented style (method):
class maxdb {maxdb_stmt_store_result() has no functionally effect and should not be used for retrieving data from MaxDB server.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Number of rows: 25. |
(PECL)
maxdb_store_result(no version information, might be only in CVS)
maxdb->store_result -- Transfers a result set from the last queryProcedural style:
resource maxdb_store_result ( resource link )Object oriented style (method):
class maxdb {This function has no functionally effect.
(PECL)
maxdb_thread_id(no version information, might be only in CVS)
maxdb->thread_id -- Returns the thread ID for the current connectionProcedural style:
int maxdb_thread_id ( resource link )Object oriented style (property):
class maxdb {The maxdb_thread_id() function returns the thread ID for the current connection which can then be killed using the maxdb_kill() function. If the connection is lost and you reconnect with maxdb_ping(), the thread ID will be other. Therefore you should get the thread ID only when you need it.
Nota: The thread ID is assigned on a connection-by-connection basis. Hence, if the connection is broken and then re-established a new thread ID will be assigned.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Warning: maxdb_query(): -10821 Session not connected <...> Error: Session not connected |
(no version information, might be only in CVS)
maxdb_thread_safe -- Returns whether thread safety is given or notProcedural style:
bool maxdb_thread_safe ( void )maxdb_thread_safe() indicates whether the client library is compiled as thread-safe.
(PECL)
maxdb_use_result(no version information, might be only in CVS)
maxdb->use_result -- Initiate a result set retrievalProcedural style:
resource maxdb_use_result ( resource link )Object oriented style (method):
class maxdb {maxdb_use_result() has no effect.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
a |
(PECL)
maxdb_warning_count(no version information, might be only in CVS)
maxdb->warning_count -- Returns the number of warnings from the last query for the given linkProcedural style:
int maxdb_warning_count ( resource link )Object oriented style (property):
class maxdb {maxdb_warning_count() returns the number of warnings from the last query in the connection represented by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Warning: maxdb_query(): -8004 POS(62) Constant must be compatible with column type and length <...> Number of warning: 0 |
MCAL stands for Modular Calendar Access Library.
Libmcal is a C library for accessing calendars. It's written to be very modular, with pluggable drivers. MCAL is the calendar equivalent of the IMAP module for mailboxes.
With mcal support, a calendar stream can be opened much like the mailbox stream with the IMAP support. Calendars can be local file stores, remote ICAP servers, or other formats that are supported by the mcal library.
Calendar events can be pulled up, queried, and stored. There is also support for calendar triggers (alarms) and recurring events.
With libmcal, central calendar servers can be accessed, removing the need for any specific database or local file programming.
Most of the functions use an internal event structure that is unique for each stream. This alleviates the need to pass around large objects between functions. There are convenience functions for setting, initializing, and retrieving the event structure values.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.0.0.
Nota: PHP had an ICAP extension previously, but the original library and the PHP extension is not supported anymore. The suggested replacement is MCAL.
Nota: Questo modulo non è disponibile su piattaforme Windows.
This extension requires the mcal library to be installed. Grab the latest version from http://mcal.chek.com/ and compile and install it.
After you installed the mcal library, to get these functions to work, you have to compile PHP -with-mcal[=DIR].
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
mcal_append_event() stores the global event into an MCAL calendar for the stream mcal_stream.
Returns the id of the newly inserted event.
Creates a new calendar named calendar.
mcal_date_compare() Compares the two given dates, returns <0, 0, >0 if a<b, a==b, a>b respectively.
(PHP 3 >= 3.0.13, PHP 4, PECL)
mcal_date_valid -- Returns TRUE if the given year, month, day is a valid datemcal_date_valid() Returns TRUE if the given year, month and day is a valid date, FALSE if not.
mcal_day_of_week() returns the day of the week of the given date. Possible return values range from 0 for Sunday through 6 for Saturday.
mcal_day_of_year() returns the day of the year of the given date.
mcal_days_in_month() returns the number of days in the month month, taking into account if the considered year is a leap year or not.
Deletes the calendar named calendar.
mcal_delete_event() deletes the calendar event specified by the event_id.
Returns TRUE.
(PHP 3 >= 3.0.15, PHP 4, PECL)
mcal_event_add_attribute -- Adds an attribute and a value to the streams global event structuremcal_event_add_attribute() adds an attribute to the stream's global event structure with the value given by "value".
mcal_event_init() initializes a streams global event structure. this effectively sets all elements of the structure to 0, or the default settings.
(PHP 3 >= 3.0.13, PHP 4, PECL)
mcal_event_set_alarm -- Sets the alarm of the streams global event structuremcal_event_set_alarm() sets the streams global event structure's alarm to the given minutes before the event.
(PHP 3 >= 3.0.13, PHP 4, PECL)
mcal_event_set_category -- Sets the category of the streams global event structuremcal_event_set_category() sets the streams global event structure's category to the given string.
(PHP 3 >= 3.0.13, PHP 4, PECL)
mcal_event_set_class -- Sets the class of the streams global event structuremcal_event_set_class() sets the streams global event structure's class to the given value. The class is either 1 for public, or 0 for private.
(PHP 3 >= 3.0.13, PHP 4, PECL)
mcal_event_set_description -- Sets the description of the streams global event structuremcal_event_set_description() sets the streams global event structure's description to the given string.
(PHP 3 >= 3.0.13, PHP 4, PECL)
mcal_event_set_end -- Sets the end date and time of the streams global event structuremcal_event_set_end() sets the streams global event structure's end date and time to the given values.
(PHP 3 >= 3.0.13, PHP 4, PECL)
mcal_event_set_recur_daily -- Sets the recurrence of the streams global event structuremcal_event_set_recur_daily() sets the streams global event structure's recurrence to the given value to be reoccurring on a daily basis, ending at the given date.
(PHP 3 >= 3.0.13, PHP 4, PECL)
mcal_event_set_recur_monthly_mday -- Sets the recurrence of the streams global event structuremcal_event_set_recur_monthly_mday() sets the streams global event structure's recurrence to the given value to be reoccurring on a monthly by month day basis, ending at the given date.
(PHP 3 >= 3.0.13, PHP 4, PECL)
mcal_event_set_recur_monthly_wday -- Sets the recurrence of the streams global event structuremcal_event_set_recur_monthly_wday() sets the streams global event structure's recurrence to the given value to be reoccurring on a monthly by week basis, ending at the given date.
(PHP 3 >= 3.0.15, PHP 4, PECL)
mcal_event_set_recur_none -- Sets the recurrence of the streams global event structuremcal_event_set_recur_none() sets the streams global event structure to not recur (event->recur_type is set to MCAL_RECUR_NONE).
(PHP 3 >= 3.0.13, PHP 4, PECL)
mcal_event_set_recur_weekly -- Sets the recurrence of the streams global event structuremcal_event_set_recur_weekly() sets the streams global event structure's recurrence to the given value to be reoccurring on a weekly basis, ending at the given date.
(PHP 3 >= 3.0.13, PHP 4, PECL)
mcal_event_set_recur_yearly -- Sets the recurrence of the streams global event structuremcal_event_set_recur_yearly() sets the streams global event structure's recurrence to the given value to be reoccurring on a yearly basis,ending at the given date.
(PHP 3 >= 3.0.13, PHP 4, PECL)
mcal_event_set_start -- Sets the start date and time of the streams global event structuremcal_event_set_start() sets the streams global event structure's start date and time to the given values.
(PHP 3 >= 3.0.13, PHP 4, PECL)
mcal_event_set_title -- Sets the title of the streams global event structuremcal_event_set_title() sets the streams global event structure's title to the given string.
(no version information, might be only in CVS)
mcal_expunge -- Deletes all events marked for being expungedmcal_expunge() deletes all events which have been previously marked for deletion.
(PHP 3 >= 3.0.13, PHP 4, PECL)
mcal_fetch_current_stream_event -- Returns an object containing the current streams event structuremcal_fetch_current_stream_event() returns the current stream's event structure as an object containing:
int id - ID of that event.
int public - TRUE if the event if public, FALSE if it is private.
string category - Category string of the event.
string title - Title string of the event.
string description - Description string of the event.
int alarm - number of minutes before the event to send an alarm/reminder.
object start - Object containing a datetime entry.
object end - Object containing a datetime entry.
int recur_type - recurrence type
int recur_interval - recurrence interval
datetime recur_enddate - recurrence end date
int recur_data - recurrence data
int year - year
int month - month
int mday - day of month
int hour - hour
int min - minutes
int sec - seconds
int alarm - minutes before event to send an alarm
mcal_fetch_event() fetches an event from the calendar stream specified by id.
Returns an event object consisting of:
int id - ID of that event.
int public - TRUE if the event if public, FALSE if it is private.
string category - Category string of the event.
string title - Title string of the event.
string description - Description string of the event.
int alarm - number of minutes before the event to send an alarm/reminder.
object start - Object containing a datetime entry.
object end - Object containing a datetime entry.
int recur_type - recurrence type
int recur_interval - recurrence interval
datetime recur_enddate - recurrence end date
int recur_data - recurrence data
int year - year
int month - month
int mday - day of month
int hour - hour
int min - minutes
int sec - seconds
int alarm - minutes before event to send an alarm
0 - Indicates that this event does not recur
1 - This event recurs daily
2 - This event recurs on a weekly basis
3 - This event recurs monthly on a specific day of the month (e.g. the 10th of the month)
4 - This event recurs monthly on a sequenced day of the week (e.g. the 3rd Saturday)
5 - This event recurs on an annual basis
mcal_is_leap_year() returns 1 if the given year is a leap year, 0 if not.
(PHP 3 >= 3.0.13, PHP 4, PECL)
mcal_list_alarms -- Return a list of events that has an alarm triggered at the given datetimeReturns an array of event ID's that has an alarm going off between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.
mcal_list_events() function takes in an optional beginning date and an end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.
(PHP 3 >= 3.0.13, PHP 4, PECL)
mcal_list_events -- Return a list of IDs for a date or a range of datesReturns an array of ID's that are between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.
mcal_list_events() takes in an beginning date and an optional end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.
mcal_next_recurrence() returns an object filled with the next date the event occurs, on or after the supplied date. Returns empty date field if event does not occur or something is invalid. Uses weekstart to determine what day is considered the beginning of the week.
Returns an MCAL stream on success, FALSE on error.
mcal_open() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also. The streams internal event structure is also initialized upon connection.
Returns an MCAL stream on success, FALSE on error.
mcal_popen() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also. The streams internal event structure is also initialized upon connection.
Renames the calendar old_name to new_name.
Reopens an MCAL stream to a new calendar.
mcal_reopen() reopens an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also.
mcal_snooze() turns off an alarm for a calendar event specified by the stream_id and event_id.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
mcal_store_event() stores the modifications to the current global event for the given stream.
Returns the event id of the modified event on success and FALSE on error.
(PHP 3 >= 3.0.13, PHP 4, PECL)
mcal_time_valid -- Returns TRUE if the given hour, minutes and seconds is a valid timemcal_time_valid() Returns TRUE if the given hour, minutes and seconds is a valid time, FALSE if not.
This is an interface to the mcrypt library, which supports a wide variety of block algorithms such as DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST in CBC, OFB, CFB and ECB cipher modes. Additionally, it supports RC6 and IDEA which are considered "non-free".
These functions work using mcrypt. To use it, download libmcrypt-x.x.tar.gz from http://mcrypt.sourceforge.net/ and follow the included installation instructions. Windows users will find all the needed compiled mcrypt binaries at http://ftp.emini.dk/pub/php/win32/mcrypt/.
As of PHP 5.0.0 you will need libmcrypt Version 2.5.6 or greater.
If you linked against libmcrypt 2.4.x or higher, the following additional block algorithms are supported: CAST, LOKI97, RIJNDAEL, SAFERPLUS, SERPENT and the following stream ciphers: ENIGMA (crypt), PANAMA, RC4 and WAKE. With libmcrypt 2.4.x or higher another cipher mode is also available; nOFB.
You need to compile PHP with the --with-mcrypt[=DIR] parameter to enable this extension. DIR is the mcrypt install directory. Make sure you compile libmcrypt with the option --disable-posix-threads.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Mcrypt configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
mcrypt.algorithms_dir | NULL | PHP_INI_ALL | Available since PHP 4.0.2. |
mcrypt.modes_dir | NULL | PHP_INI_ALL | Available since PHP 4.0.2. |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Mcrypt can operate in four block cipher modes (CBC, OFB, CFB, and ECB). If linked against libmcrypt-2.4.x or higher the functions can also operate in the block cipher mode nOFB and in STREAM mode. Below you find a list with all supported encryption modes together with the constants that are defines for the encryption mode. For a more complete reference and discussion see Applied Cryptography by Schneier (ISBN 0-471-11709-9).
MCRYPT_MODE_ECB (electronic codebook) is suitable for random data, such as encrypting other keys. Since data there is short and random, the disadvantages of ECB have a favorable negative effect.
MCRYPT_MODE_CBC (cipher block chaining) is especially suitable for encrypting files where the security is increased over ECB significantly.
MCRYPT_MODE_CFB (cipher feedback) is the best mode for encrypting byte streams where single bytes must be encrypted.
MCRYPT_MODE_OFB (output feedback, in 8bit) is comparable to CFB, but can be used in applications where error propagation cannot be tolerated. It's insecure (because it operates in 8bit mode) so it is not recommended to use it.
MCRYPT_MODE_NOFB (output feedback, in nbit) is comparable to OFB, but more secure because it operates on the block size of the algorithm.
MCRYPT_MODE_STREAM is an extra mode to include some stream algorithms like WAKE or RC4.
Some other mode and random device constants:
Here is a list of ciphers which are currently supported by the mcrypt extension. For a complete list of supported ciphers, see the defines at the end of mcrypt.h. The general rule with the mcrypt-2.2.x API is that you can access the cipher from PHP with MCRYPT_ciphername. With the libmcrypt-2.4.x and libmcrypt-2.5.x API these constants also work, but it is possible to specify the name of the cipher as a string with a call to mcrypt_module_open().
MCRYPT_3DES
MCRYPT_ARCFOUR_IV (libmcrypt > 2.4.x only)
MCRYPT_ARCFOUR (libmcrypt > 2.4.x only)
MCRYPT_BLOWFISH
MCRYPT_CAST_128
MCRYPT_CAST_256
MCRYPT_CRYPT
MCRYPT_DES
MCRYPT_DES_COMPAT (libmcrypt 2.2.x only)
MCRYPT_ENIGMA (libmcrypt > 2.4.x only, alias for MCRYPT_CRYPT)
MCRYPT_GOST
MCRYPT_IDEA (non-free)
MCRYPT_LOKI97 (libmcrypt > 2.4.x only)
MCRYPT_MARS (libmcrypt > 2.4.x only, non-free)
MCRYPT_PANAMA (libmcrypt > 2.4.x only)
MCRYPT_RIJNDAEL_128 (libmcrypt > 2.4.x only)
MCRYPT_RIJNDAEL_192 (libmcrypt > 2.4.x only)
MCRYPT_RIJNDAEL_256 (libmcrypt > 2.4.x only)
MCRYPT_RC2
MCRYPT_RC4 (libmcrypt 2.2.x only)
MCRYPT_RC6 (libmcrypt > 2.4.x only)
MCRYPT_RC6_128 (libmcrypt 2.2.x only)
MCRYPT_RC6_192 (libmcrypt 2.2.x only)
MCRYPT_RC6_256 (libmcrypt 2.2.x only)
MCRYPT_SAFER64
MCRYPT_SAFER128
MCRYPT_SAFERPLUS (libmcrypt > 2.4.x only)
MCRYPT_SERPENT(libmcrypt > 2.4.x only)
MCRYPT_SERPENT_128 (libmcrypt 2.2.x only)
MCRYPT_SERPENT_192 (libmcrypt 2.2.x only)
MCRYPT_SERPENT_256 (libmcrypt 2.2.x only)
MCRYPT_SKIPJACK (libmcrypt > 2.4.x only)
MCRYPT_TEAN (libmcrypt 2.2.x only)
MCRYPT_THREEWAY
MCRYPT_TRIPLEDES (libmcrypt > 2.4.x only)
MCRYPT_TWOFISH (for older mcrypt 2.x versions, or mcrypt > 2.4.x )
MCRYPT_TWOFISH128 (TWOFISHxxx are available in newer 2.x versions, but not in the 2.4.x versions)
MCRYPT_TWOFISH192
MCRYPT_TWOFISH256
MCRYPT_WAKE (libmcrypt > 2.4.x only)
MCRYPT_XTEA (libmcrypt > 2.4.x only)
You must (in CFB and OFB mode) or can (in CBC mode) supply an initialization vector (IV) to the respective cipher function. The IV must be unique and must be the same when decrypting/encrypting. With data which is stored encrypted, you can take the output of a function of the index under which the data is stored (e.g. the MD5 key of the filename). Alternatively, you can transmit the IV together with the encrypted data (see chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9) for a discussion of this topic).
Mcrypt can be used to encrypt and decrypt using the above mentioned ciphers. If you linked against libmcrypt-2.2.x, the four important mcrypt commands (mcrypt_cfb(), mcrypt_cbc(), mcrypt_ecb(), and mcrypt_ofb()) can operate in both modes which are named MCRYPT_ENCRYPT and MCRYPT_DECRYPT, respectively.
If you linked against libmcrypt 2.4.x or 2.5.x, these functions are still available, but it is recommended that you use the advanced functions.
Esempio 2. Encrypt an input value with TripleDES under 2.4.x and higher in ECB mode
|
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.
(PHP 3 >= 3.0.8, PHP 4, PHP 5)
mcrypt_create_iv -- Create an initialization vector (IV) from a random sourcemcrypt_create_iv() is used to create an IV.
Parameter size determines the size of the IV, parameter source (defaults to random value) specifies the source of the IV.
The source can be MCRYPT_RAND (system random number generator), MCRYPT_DEV_RANDOM (read data from /dev/random) and MCRYPT_DEV_URANDOM (read data from /dev/urandom). MCRYPT_RAND is the only one supported on Windows because Windows (of course) doesn't have /dev/random or /dev/urandom.
Nota: When using MCRYPT_RAND, remember to call srand() before mcrypt_create_iv() to initialize the random number generator; it is not seeded automatically like rand() is.
The IV is only meant to give an alternative seed to the encryption routines. This IV does not need to be secret at all, though it can be desirable. You even can send it along with your ciphertext without losing security.
More information can be found at http://www.ciphersbyritter.com/GLOSSARY.HTM#IV, http://fn2.freenet.edmonton.ab.ca/~jsavard/crypto/co0409.htm and in chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9) for a discussion of this topic.
mcrypt_decrypt() decrypts the data and returns the unencrypted data.
Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.
Key is the key with which the data is encrypted. If it's smaller that the required keysize, it is padded with '\0'.
Data is the data that will be decrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'.
Mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".
The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to '\0'.
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
This function is deprecated and should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.
This function returns the name of the algorithm.
Esempio 1. mcrypt_enc_get_algorithms_name() example
Il precedente esempio visualizzerà:
|
This function returns the block size of the algorithm specified by the encryption descriptor td in bytes.
This function returns the size of the iv of the algorithm specified by the encryption descriptor in bytes. If it returns '0' then the IV is ignored in the algorithm. An IV is used in cbc, cfb and ofb modes, and in some algorithms in stream mode.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_enc_get_key_size -- Returns the maximum supported keysize of the opened modeThis function returns the maximum supported key size of the algorithm specified by the encryption descriptor td in bytes.
This function returns the name of the mode.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_enc_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithmReturns an array with the key sizes supported by the algorithm specified by the encryption descriptor. If it returns an empty array then all key sizes between 1 and mcrypt_enc_get_key_size() are supported by the algorithm.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_enc_is_block_algorithm_mode -- Checks whether the encryption of the opened mode works on blocksThis function returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE. (e.g. FALSE for stream, and TRUE for cbc, cfb, ofb).
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_enc_is_block_algorithm -- Checks whether the algorithm of the opened mode is a block algorithmThis function returns TRUE if the algorithm is a block algorithm, or FALSE if it is a stream algorithm.
This function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs bytes. (e.g. TRUE for cbc and ecb, and FALSE for cfb and stream).
This function runs the self test on the algorithm specified by the descriptor td. If the self test succeeds it returns FALSE. In case of an error, it returns TRUE.
mcrypt_encrypt() encrypts the data and returns the encrypted data.
Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.
Key is the key with which the data will be encrypted. If it's smaller that the required keysize, it is padded with '\0'. It is better not to use ASCII strings for keys. It is recommended to use the mhash functions to create a key from a string.
Data is the data that will be encrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'. The returned crypttext can be larger that the size of the data that is given by data.
Mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".
The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to '\0'.
Esempio 1. mcrypt_encrypt() Example
Il precedente esempio visualizzerà:
|
See also mcrypt_module_open() for a more advanced API and an example.
This function terminates encryption specified by the encryption descriptor (td). It clears all buffers, but does not close the module. You need to call mcrypt_module_close() yourself. (But PHP does this for you at the end of the script.) Returns FALSE on error, or TRUE on success.
See for an example mcrypt_module_open() and the entry on mcrypt_generic_init().
Avvertimento |
This function is deprecated, use mcrypt_generic_deinit() instead. It can cause crashes when used with mcrypt_module_close() due to multiple buffer frees. |
This function terminates encryption specified by the encryption descriptor (td). Actually it clears all buffers, and closes all the modules used. Returns FALSE on error, or TRUE on success.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_generic_init -- This function initializes all buffers needed for encryptionThe maximum length of the key should be the one obtained by calling mcrypt_enc_get_key_size() and every value smaller than this is legal. The IV should normally have the size of the algorithms block size, but you must obtain the size by calling mcrypt_enc_get_iv_size(). IV is ignored in ECB. IV MUST exist in CFB, CBC, STREAM, nOFB and OFB modes. It needs to be random and unique (but not secret). The same IV must be used for encryption/decryption. If you do not want to use it you should set it to zeros, but this is not recommended.
The function returns a negative value on error, -3 when the key length was incorrect, -4 when there was a memory allocation problem and any other return value is an unknown error. If an error occurs a warning will be displayed accordingly. FALSE is returned if incorrect parameters were passed.
You need to call this function before every call to mcrypt_generic() or mdecrypt_generic().
See for an example mcrypt_module_open().
This function encrypts data. The data is padded with "\0" to make sure the length of the data is n * blocksize. This function returns the encrypted data. Note that the length of the returned string can in fact be longer then the input, due to the padding of the data.
If you want to store the encrypted data in a database make sure to store the entire string as returned by mcrypt_generic, or the string will not entirely decrypt properly. If your original string is 10 characters long and the block size is 8 (use mcrypt_enc_get_block_size() to determine the blocksize), you would need at least 16 characters in your database field. Note the string returned by mdecrypt_generic() will be 16 characters as well...use rtrim()($str, "\0") to remove the padding.
If you are for example storing the data in a MySQL database remember that varchar fields automatically have trailing spaces removed during insertion. As encrypted data can end in a space (ASCII 32), the data will be damaged by this removal. Store data in a tinyblob/tinytext (or larger) field instead.
The encryption handle should always be initialized with mcrypt_generic_init() with a key and an IV before calling this function. Where the encryption is done, you should free the encryption buffers by calling mcrypt_generic_deinit(). See mcrypt_module_open() for an example.
See also mdecrypt_generic(), mcrypt_generic_init(), and mcrypt_generic_deinit().
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.
mcrypt_get_block_size() is used to get the size of a block of the specified cipher (in combination with an encryption mode).
It is more useful to use the mcrypt_enc_get_block_size() function as this uses the resource returned by mcrypt_module_open().
This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x.
See also: mcrypt_get_key_size(), mcrypt_enc_get_block_size() and mcrypt_encrypt().
mcrypt_get_cipher_name() is used to get the name of the specified cipher.
mcrypt_get_cipher_name() takes the cipher number as an argument (libmcrypt 2.2.x) or takes the cipher name as an argument (libmcrypt 2.4.x or higher) and returns the name of the cipher or FALSE, if the cipher does not exist.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_get_iv_size -- Returns the size of the IV belonging to a specific cipher/mode combinationmcrypt_get_iv_size() returns the size of the Initialisation Vector (IV) in bytes. On error the function returns FALSE. If the IV is ignored in the specified cipher/mode combination zero is returned.
cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.
mode is one of the MCRYPT_MODE_modename constants or one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream". The IV is ignored in ECB mode as this mode does not require it. You will need to have the same IV (think: starting point) both at encryption and decryption stages, otherwise your encryption will fail.
It is more useful to use the mcrypt_enc_get_iv_size() function as this uses the resource returned by mcrypt_module_open().
See also mcrypt_get_block_size(), mcrypt_enc_get_iv_size() and mcrypt_create_iv().
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.
mcrypt_get_key_size() is used to get the size of a key of the specified cipher (in combination with an encryption mode).
This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x. It is more useful to use the mcrypt_enc_get_key_size() function as this uses the resource returned by mcrypt_module_open().
Esempio 1. mcrypt_get_block_size() example
|
See also: mcrypt_get_block_size(), mcrypt_end_get_key_size() and mcrypt_encrypt().
mcrypt_list_algorithms() is used to get an array of all supported algorithms in the lib_dir parameter.
mcrypt_list_algorithms() takes an optional lib_dir parameter which specifies the directory where all algorithms are located. If not specifies, the value of the mcrypt.algorithms_dir php.ini directive is used.
mcrypt_list_modes() is used to get an array of all supported modes in the lib_dir.
mcrypt_list_modes() takes as optional parameter a directory which specifies the directory where all modes are located. If not specifies, the value of the mcrypt.modes_dir php.ini directive is used.
Esempio 1. mcrypt_list_modes() Example
The above example will produce a list with all supported algorithms in the default mode directory. If it is not set with the ini directive mcrypt.modes_dir, the default directory of mcrypt is used (which is /usr/local/lib/libmcrypt). |
This function closes the specified encryption handle.
See mcrypt_module_open() for an example.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_get_algo_block_size -- Returns the blocksize of the specified algorithmThis function returns the block size of the algorithm specified in bytes. The optional lib_dir parameter can contain the location where the mode module is on the system.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_get_algo_key_size -- Returns the maximum supported keysize of the opened modeThis function returns the maximum supported key size of the algorithm specified in bytes. The optional lib_dir parameter can contain the location where the mode module is on the system.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithmReturns an array with the key sizes supported by the specified algorithm. If it returns an empty array then all key sizes between 1 and mcrypt_module_get_algo_key_size() are supported by the algorithm. The optional lib_dir parameter can contain the location where the mode module is on the system.
See also mcrypt_enc_get_supported_key_sizes() which is used on open encryption modules.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_is_block_algorithm_mode -- Returns if the specified module is a block algorithm or notThis function returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE. (e.g. FALSE for stream, and TRUE for cbc, cfb, ofb). The optional lib_dir parameter can contain the location where the mode module is on the system.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_is_block_algorithm -- This function checks whether the specified algorithm is a block algorithmThis function returns TRUE if the specified algorithm is a block algorithm, or FALSE is it is a stream algorithm. The optional lib_dir parameter can contain the location where the algorithm module is on the system.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_is_block_mode -- Returns if the specified mode outputs blocks or notThis function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs just bytes. (e.g. TRUE for cbc and ecb, and FALSE for cfb and stream). The optional lib_dir parameter can contain the location where the mode module is on the system.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_open -- Opens the module of the algorithm and the mode to be usedThis function opens the module of the algorithm and the mode to be used. The name of the algorithm is specified in algorithm, e.g. "twofish" or is one of the MCRYPT_ciphername constants. The module is closed by calling mcrypt_module_close(). Normally it returns an encryption descriptor, or FALSE on error.
The algorithm_directory and mode_directory are used to locate the encryption modules. When you supply a directory name, it is used. When you set one of these to the empty string (""), the value set by the mcrypt.algorithms_dir or mcrypt.modes_dir ini-directive is used. When these are not set, the default directories that are used are the ones that were compiled in into libmcrypt (usually /usr/local/lib/libmcrypt).
The first line in the example above will try to open the DES cipher from the default directory and the EBC mode from the directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher and mode, this only works when the extension is linked against libmcrypt 2.4.x or 2.5.x.
Esempio 2. Using mcrypt_module_open() in encryption
|
The first line in the example above will try to open the DES cipher from the default directory and the EBC mode from the directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher and mode, this only works when the extension is linked against libmcrypt 2.4.x or 2.5.x.
See also mcrypt_module_close(), mcrypt_generic(), mdecrypt_generic(), mcrypt_generic_init(), and mcrypt_generic_deinit().
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_self_test -- This function runs a self test on the specified moduleThis function runs the self test on the algorithm specified. The optional lib_dir parameter can contain the location of where the algorithm module is on the system.
The function returns TRUE if the self test succeeds, or FALSE when if fails.
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.
This function decrypts data. Note that the length of the returned string can in fact be longer then the unencrypted string, due to the padding of the data.
Esempio 1. mdecrypt_generic() example
|
The above example shows how to check if the data before the encryption is the same as the data after the decryption. It is very important to reinitialize the encryption buffer with mcrypt_generic_init() before you try to decrypt the data.
The decryption handle should always be initialized with mcrypt_generic_init() with a key and an IV before calling this function. Where the encryption is done, you should free the encryption buffers by calling mcrypt_generic_deinit(). See mcrypt_module_open() for an example.
See also mcrypt_generic(), mcrypt_generic_init(), and mcrypt_generic_deinit().
These functions interface the MCVE API (libmcve), allowing you to work directly with MCVE from your PHP scripts. MCVE is Main Street Softworks' solution to direct credit card processing for Linux / Unix ( http://www.mainstreetsoftworks.com/ ). It lets you directly address the credit card clearing houses via your *nix box, modem and/or internet connection (bypassing the need for an additional service such as Authorize.Net or Pay Flow Pro). Using the MCVE module for PHP, you can process credit cards directly through MCVE via your PHP scripts. The following references will outline the process.
Nota: MCVE is the replacement for RedHat's CCVS. They contracted with RedHat in late 2001 to migrate all existing clientele to the MCVE platform.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.1.0.
Nota: Questo modulo non è disponibile su piattaforme Windows.
To enable MCVE Support in PHP, first verify your LibMCVE installation directory. You will then need to configure PHP with the --with-mcve option. If you use this option without specifying the path to your MCVE installation, PHP will attempt to look in the default LibMCVE Install location (/usr/local). If MCVE is in a non-standard location, run configure with: --with-mcve=$mcve_path, where $mcve_path is the path to your MCVE installation. Please note that MCVE support requires that $mcve_path/lib and $mcve_path/include exist, and include mcve.h under the include directory and libmcve.so and/or libmcve.a under the lib directory.
Since MCVE has true server/client separation, there are no additional requirements for running PHP with MCVE support. To test your MCVE extension in PHP, you may connect to testbox.mcve.com on port 8333 for IP, or port 8444 for SSL using the MCVE PHP API. Use 'vitale' for your username, and 'test' for your password. Additional information about test facilities are available at http://www.mainstreetsoftworks.com/.
Additional documentation about MCVE's PHP API can be found at http://www.mainstreetsoftworks.com/docs/phpapi.pdf. Main Street's documentation is complete and should be the primary reference for functions.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_completeauthorizations -- Number of complete authorizations in queue, returning an array of their identifiers
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
mcve_connectionerror -- Get a textual representation of why a connection failed
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_getcell -- Get a specific cell from a comma delimited response by column name
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_getcellbynum -- Get a specific cell from a comma delimited response by column number
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_getcommadelimited -- Get the RAW comma delimited data returned from MCVE
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
mcve_maxconntimeout -- The maximum amount of time the API will attempt a connection to MCVE
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_monitor -- Perform communication with MCVE (send/receive data) Non-blocking
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_parsecommadelimited -- Parse the comma delimited response so mcve_getcell, etc will work
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_preauthcompletion -- Complete a PREAUTHORIZATION, ready it for settlement
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.3, PHP 5)
mcve_setssl_files -- Set certificate key files and certificates if server requires client certificate verification
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_transactionauth -- Get the authorization number returned for the transaction (alpha-numeric)
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_transactionbatch -- Get the batch number associated with the transaction
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_transactionitem -- Get the ITEM number in the associated batch for this transaction
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_transactiontext -- Get verbiage (text) return from MCVE or processing institution
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
mcve_verifyconnection -- Set whether or not to PING upon connect to verify connection
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
mcve_verifysslcert -- Set whether or not to verify the server ssl certificate
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.
This module doesn't have native support of multiple servers, but you still can implement it yourself in your application. Establish several memcached connections, set priority level for each server etc.
More information about memcached can be found at http://www.danga.com/memcached/.
This module uses functions of zlib to support on-the-fly data compression. Zlib is required to install this module.
PHP 4.3.3 or newer is required to use the memcache extension.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/memcache.
In order to use these functions you must compile PHP with Memcache support by using the --enable-memcache[=DIR] option.
Windows users will enable php_memcache.dll inside of php.ini in order to use these functions. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Tabella 1. MemCache Constants
Name | Description |
---|---|
MEMCACHE_COMPRESSED (integer) | Used to turn on-the-fly data compression on with Memcache::set(), Memcache::add() e Memcache::replace(). |
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
There is only one resource type used in memcache module - it's the link identifier for a cache server connection.
Esempio 1. memcache extension overview example
|
In the above example, an object is being saved in the cache and then retrieved back. Object and other non-scalar types are serialized before saving, so it's impossible to store resources (i.e. connection identifiers and others) in the cache.
Memcache::add() stores variable var with key only if such key doesn't exist at the server yet. Memcache::add() returns FALSE if such key already exist. For the rest Memcache::add() behaves similarly to Memcache::set().
Also you can use memcache_add() function. See example below.
Memcache::add() returns TRUE on success or FALSE on failure.
See also Memcache::set(), Memcache::replace().
Memcache::close() closes connection to memcached server. This function doesn't close persistent connections, which are closed only during web-server shutdown/restart.
Also you can use memcache_close() function. See example below.
Esempio 1. Memcache::close() example
|
Memcache::close() returns FALSE if an error occured.
See also Memcache::connect(), Memcache::pconnect().
Memcache::connect() establishes a connection to the memcached server. Parameters host and port point to the host and port, where memcached is listening for connections. Parameter port is optional, it's default value is 11211. Also you can define a timeout (in seconds), which will be used when connecting to the daemon. Think twice before changing the default value - you can loose all the advantages of caching if your connection is too slow.
The connection, which was opened using Memcache::connect() will be automatically closed at the end of script execution. Also you can close it with Memcache::close().
Also you can use memcache_connect() function. See example below.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also Memcache::pconnect() and Memcache::close().
memcache_debug() turns on debug output if parameter on_off is equal to 1 and turns off if it's 0.
Nota: memcache_debug() is accessible only if PHP was built with --enable-debug option and always returns TRUE in this case. Otherwise, this function has no effect and always returns FALSE.
Memcache::decrement() decrements value of the item by value. Similarly to Memcache::increment(), current value of the item is being converted to numerical and after that value is substracted.
Parameter value is optional. It's default is 1.
Nota: New item's value will not be less than zero.
Nota: Do not use Memcache::decrement() with item, which was stored compressed, because consequent call to Memcache::get() will fail.
Also you can use memcache_decrement() function. See example below.
Esempio 1. Memcache::decrement() example
|
Memcache::decrement() does not create an item if it didn't exist.
Memcache::decrement() returns item's new value on success or FALSE on failure.
See also Memcache::increment(), Memcache::replace().
Memcache::delete() deletes item with the key. If parameter timeout is specified, the item will expire after timeout seconds.
Also you can use memcache_delete() function. See example below.
Esempio 1. Memcache::delete() example
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
Memcache::flush -- Flush all existing items at the serverMemcache::flush() immediately invalidates all existing items. Memcache::flush() doesn't actually free any resources, it only marks all the items as expired, so occupied memory will be overwritten by new items.
Also you can use memcache_flush() function. See example below.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Memcache::get() returns previously stored data if an item with such key exists on the server at this moment.
Esempio 1. Memcache::get() example
|
Memcache::get() returns FALSE on failure or if such key was not found.
Memcache::getStats() returns an associative array with server's statistics. Array keys correspond to stats parameters and values to parameter's values.
Also you can use memcache_get_stats() function.
Memcache::getStats() returns FALSE in case of an error.
See also Memcache::getVersion().
Memcache::getVersion() returns a string with server's version number.
Also you can use memcache_get_version() function. See example below.
Memcache::getVersion() returns FALSE if an error occured.
See also Memcache::getStats().
Memcache::increment() increments value of the item on the specified value. If item with key key was not numeric and cannot be converted to number, it will change it's value to value.
Parameter value is optional. It's default value is 1.
Nota: Do not use Memcache::increment() with item, which was stored compressed, because consequent call to Memcache::get() will fail.
Also you can use memcache_increment() function. See example below.
Esempio 1. Memcache::increment() example
|
Memcache::increment() returns new item's value on success or FALSE on failure.
Memcache::increment() does not create an item if it didn't exist.
See also Memcache::decrement(), Memcache::replace().
(no version information, might be only in CVS)
Memcache::pconnect -- Open memcached server persistent connectionMemcache::pconnect() is similar to Memcache::connect() with the difference, that the connection it establishes is persistent. This connection is not closed after the end of script execution and by Memcache::close() function.
Also you can use memcache_pconnect() function. See example below.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also Memcache::connect().
(no version information, might be only in CVS)
Memcache::replace -- Replace value of the existing itemMemcache::replace() should be used to replace value of existing item with key. In case if item with such key doesn't exists, Memcache::replace() returns FALSE. For the rest Memcache::replace() behaves similarly to Memcache::set().
Also you can use memcache_replace() function. See example below.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also Memcache::set(), Memcache::add().
Memcache::set() stores an item var with key on the memcached server. Parameter expire is expiration time in seconds. If it's 0, the item never expires (but memcached server doesn't guarantee this item to be stored all the time, it could be deleted from the cache to make place for other items).
You can use MEMCACHE_COMPRESSED constant as flag value if you want to use on-the-fly compression (uses zlib).
Also you can use memcache_set() function. See example below.
Nota: Remember that resource variables (i.e. file and connection descriptors) cannot be stored in the cache, because they cannot be adequately represented in serialized state.
Esempio 1. Memcache::set() example
|
Esempio 2. Memcache::set() example
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also Memcache::add(), Memcache::replace().
These functions are intended to work with mhash. Mhash can be used to create checksums, message digests, message authentication codes, and more.
This is an interface to the mhash library. mhash supports a wide variety of hash algorithms such as MD5, SHA1, GOST, and many others. For a complete list of supported hashes, refer to the documentation of mhash. The general rule is that you can access the hash algorithm from PHP with MHASH_HASHNAME. For example, to access TIGER you use the PHP constant MHASH_TIGER.
To use it, download the mhash distribution from its web site and follow the included installation instructions.
You need to compile PHP with the --with-mhash[=DIR] parameter to enable this extension. DIR is the mhash install directory.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Here is a list of hashes which are currently supported by mhash. If a hash is not listed here, but is listed by mhash as supported, you can safely assume that this documentation is outdated.
MHASH_ADLER32
MHASH_CRC32
MHASH_CRC32B
MHASH_GOST
MHASH_HAVAL128
MHASH_HAVAL160
MHASH_HAVAL192
MHASH_HAVAL256
MHASH_MD4
MHASH_MD5
MHASH_RIPEMD160
MHASH_SHA1
MHASH_SHA256
MHASH_TIGER
MHASH_TIGER128
MHASH_TIGER160
Esempio 1. Compute the MD5 digest and hmac and print it out as hex
This will produce:
|
mhash_count() returns the highest available hash id. Hashes are numbered from 0 to this hash id.
mhash_get_block_size() is used to get the size of a block of the specified hash.
mhash_get_block_size() takes one argument, the hash and returns the size in bytes or FALSE, if the hash does not exist.
mhash_get_hash_name() is used to get the name of the specified hash.
mhash_get_hash_name() takes the hash id as an argument and returns the name of the hash or FALSE, if the hash does not exist.
mhash_keygen_s2k() generates a key that is bytes long, from a user given password. This is the Salted S2K algorithm as specified in the OpenPGP document (RFC 2440). That algorithm will use the specified hash algorithm to create the key. The salt must be different and random enough for every key you generate in order to create different keys. That salt must be known when you check the keys, thus it is a good idea to append the key to it. Salt has a fixed length of 8 bytes and will be padded with zeros if you supply less bytes.
Keep in mind that user supplied passwords are not really suitable to be used as keys in cryptographic algorithms, since users normally choose keys they can write on keyboard. These passwords use only 6 to 7 bits per character (or less). It is highly recommended to use some kind of transformation (like this function) to the user supplied key.
mhash() applies a hash function specified by hash to the data and returns the resulting hash (also called digest). If the key is specified it will return the resulting HMAC. HMAC is keyed hashing for message authentication, or simply a message digest that depends on the specified key. Not all algorithms supported in mhash can be used in HMAC mode. In case of an error returns FALSE.
Avvertimento |
This extension has been deprecated as the PECL extension fileinfo provides the same functionality (and more) in a much cleaner way. |
The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.
This extension is derived from Apache mod_mime_magic, which is itself based on the file command maintained by Ian F. Darwin. See the source code for further historic and copyright information.
You must compile PHP with the configure switch --with-mime-magic to get support for mime-type functions. The extension needs a copy of the simplified magic file that is distributed with the Apache httpd.
Nota: The configure option has been changed from --enable-mime-magic to --with-mime-magic since PHP 4.3.2
Nota: This extension is not capable of handling the fully decorated magic file that generally comes with standard Linux distro's and is supposed to be used with recent versions of file command.
Note to Win32 Users: In order to use this module on a Windows environment, you must set the path to the bundled magic.mime file in your php.ini.
Remember to substitute the $PHP_INSTALL_DIR for your actual path to PHP in the above example. e.g. c:\php
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Mimetype configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
mime_magic.debug | "0" | PHP_INI_SYSTEM | Available since PHP 5.0.0. |
mime_magic.magicfile | "/path/to/php/magic.mime" | PHP_INI_SYSTEM | Available since PHP 4.3.0. |
Breve descrizione dei parametri di configurazione.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
First of all: Ming is not an acronym. Ming is an open-source (LGPL) library which allows you to create SWF ("Flash") format movies. Ming supports almost all of Flash 4's features, including: shapes, gradients, bitmaps (pngs and jpegs), morphs ("shape tweens"), text, buttons, actions, sprites ("movie clips"), streaming mp3, and color transforms --the only thing that's missing is sound events.
Note that all values specifying length, distance, size, etc. are in "twips", twenty units per pixel. That's pretty much arbitrary, though, since the player scales the movie to whatever pixel size is specified in the embed/object tag, or the entire frame if not embedded.
Ming offers a number of advantages over the existing PHP/libswf module. You can use Ming anywhere you can compile the code, whereas libswf is closed-source and only available for a few platforms, Windows not one of them. Ming provides some insulation from the mundane details of the SWF file format, wrapping the movie elements in PHP objects. Also, Ming is still being maintained; if there's a feature that you want to see, just let us know ming@opaque.net.
Ming was added in PHP 4.0.5.
To use Ming with PHP, you first need to build and install the Ming library. Source code and installation instructions are available at the Ming home page: http://ming.sourceforge.net/ along with examples, a small tutorial, and the latest news.
Download the ming archive. Unpack the archive. Go in the Ming directory. make. make install.
This will build libming.so and install it into /usr/lib/, and copy ming.h into /usr/include/. Edit the PREFIX= line in the Makefile to change the installation directory.
Now either just add extension=php_ming.so to your php.ini file, or put dl('php_ming.so'); at the head of all of your Ming scripts.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Queste classi sono definite da questa estensione, e sono disponibili solo quando l'estensione è stata compilata nel PHP o caricata come modulo dinamico al runtime.
Ming introduces 13 new objects in PHP, all with matching methods and attributes. To use them, you need to know about objects.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfaction() creates a new Action, and compiles the given script into an SWFAction object.
The script syntax is based on the C language, but with a lot taken out- the SWF bytecode machine is just too simpleminded to do a lot of things we might like. For instance, we can't implement function calls without a tremendous amount of hackery because the jump bytecode has a hardcoded offset value. No pushing your calling address to the stack and returning- every function would have to know exactly where to return to.
So what's left? The compiler recognises the following tokens:
break
for
continue
if
else
do
while
There is no typed data; all values in the SWF action machine are stored as strings. The following functions can be used in expressions:
Returns the number of milliseconds (?) elapsed since the movie started.
Returns a pseudo-random number in the range 0-seed.
Returns the length of the given expression.
Returns the given number rounded down to the nearest integer.
Returns the concatenation of the given expressions.
Returns the ASCII code for the given character
Returns the character for the given ASCII code
Returns the substring of length length at location location of the given string string.
Additionally, the following commands may be used:
Duplicate the named movie clip (aka sprite). The new movie clip has name name and is at depth depth.
Removes the named movie clip.
Write the given expression to the trace log. Doubtful that the browser plugin does anything with this.
Start dragging the movie clip target. The lock argument indicates whether to lock the mouse (?)- use 0 (FALSE) or 1 (TRUE). Optional parameters define a bounding area for the dragging.
Stop dragging my heart around. And this movie clip, too.
Call the named frame as a function.
Load the given URL into the named target. The target argument corresponds to HTML document targets (such as "_top" or "_blank"). The optional method argument can be POST or GET if you want to submit variables back to the server.
Load the given URL into the named target. The target argument can be a frame name (I think), or one of the magical values "_level0" (replaces current movie) or "_level1" (loads new movie on top of current movie).
Go to the next frame.
Go to the last (or, rather, previous) frame.
Start playing the movie.
Stop playing the movie.
Toggle between high and low quality.
Stop playing all sounds.
Go to frame number num. Frame numbers start at 0.
Go to the frame named name. Which does a lot of good, since I haven't added frame labels yet.
Sets the context for action. Or so they say- I really have no idea what this does.
Movie clips (all together now- aka sprites) have properties. You can read all of them (or can you?), you can set some of them, and here they are:
x
y
xScale
yScale
currentFrame - (read-only)
totalFrames - (read-only)
alpha - transparency level
visible - 1=on, 0=off (?)
width - (read-only)
height - (read-only)
rotation
target - (read-only) (???)
framesLoaded - (read-only)
name
dropTarget - (read-only) (???)
url - (read-only) (???)
highQuality - 1=high, 0=low (?)
focusRect - (???)
soundBufTime - (???)
This simple example will move the red square across the window.
Esempio 1. swfaction() example
|
This simple example tracks down your mouse on the screen.
Esempio 2. swfaction() example
|
Same as above, but with nice colored balls...
Esempio 3. swfaction() example
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbitmap->getheight() returns the bitmap's height in pixels.
See also swfbitmap->getwidth().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbitmap->getwidth() returns the bitmap's width in pixels.
See also swfbitmap->getheight().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbitmap() creates a new SWFBitmap object from the Jpeg or DBL file in file. alphafile is a MSK file to be used as an alpha mask for a Jpeg image. Both parameters can be fopen() resources or binary strings.
Nota: We can only deal with baseline (frame 0) jpegs, no baseline optimized or progressive scan jpegs!
SWFBitmap has the following methods : swfbitmap->getwidth() and swfbitmap->getheight().
You can't import png images directly, though- have to use the png2dbl utility to make a dbl ("define bits lossless") file from the png. The reason for this is that I don't want a dependency on the png library in ming- autoconf should solve this, but that's not set up yet.
Esempio 1. Import PNG files
|
And you can put an alpha mask on a jpeg fill.
Esempio 2. swfbitmap() example
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbutton->addaction() adds the action action to this button for the given conditions. The following flags are valid: SWFBUTTON_MOUSEOVER, SWFBUTTON_MOUSEOUT, SWFBUTTON_MOUSEUP, SWFBUTTON_MOUSEUPOUTSIDE, SWFBUTTON_MOUSEDOWN, SWFBUTTON_DRAGOUT and SWFBUTTON_DRAGOVER.
See also swfbutton->addshape() and swfaction().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbutton->addshape() adds the shape shape to this button. The following flags' values are valid: SWFBUTTON_UP, SWFBUTTON_OVER, SWFBUTTON_DOWN or SWFBUTTON_HIT. SWFBUTTON_HIT isn't ever displayed, it defines the hit region for the button. That is, everywhere the hit shape would be drawn is considered a "touchable" part of the button.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbutton->setaction() sets the action to be performed when the button is clicked. Alias for addAction(shape, SWFBUTTON_MOUSEUP). action is a swfaction().
See also swfbutton->addshape() and swfaction().
(no version information, might be only in CVS)
SWFbutton->setdown -- Alias for addShape(shape, SWFBUTTON_DOWN)Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbutton->setdown() alias for addShape(shape, SWFBUTTON_DOWN).
See also swfbutton->addshape() and swfaction().
(no version information, might be only in CVS)
SWFbutton->setHit -- Alias for addShape(shape, SWFBUTTON_HIT)Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbutton->sethit() alias for addShape(shape, SWFBUTTON_HIT).
See also swfbutton->addshape() and swfaction().
(no version information, might be only in CVS)
SWFbutton->setOver -- Alias for addShape(shape, SWFBUTTON_OVER)Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbutton->setover() alias for addShape(shape, SWFBUTTON_OVER).
See also swfbutton->addshape() and swfaction().
(no version information, might be only in CVS)
SWFbutton->setUp -- Alias for addShape(shape, SWFBUTTON_UP)Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbutton->setup() alias for addShape(shape, SWFBUTTON_UP).
See also swfbutton->addshape() and swfaction().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbutton() creates a new Button. Roll over it, click it, see it call action code. Swank.
SWFButton has the following methods : swfbutton->addshape(), swfbutton->setup(), swfbutton->setover() swfbutton->setdown(), swfbutton->sethit() swfbutton->setaction() and swfbutton->addaction().
This simple example will show your usual interactions with buttons : rollover, rollon, mouseup, mousedown, noaction.
Esempio 1. swfbutton() example
|
This simple example will enables you to drag draw a big red button on the windows. No drag-and-drop, just moving around.
Esempio 2. swfbutton->addaction() example
|
(no version information, might be only in CVS)
SWFDisplayItem->addColor -- Adds the given color to this item's color transformAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->addcolor() adds the color to this item's color transform. The color is given in its RGB form.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
(no version information, might be only in CVS)
SWFDisplayItem->move -- Moves object in relative coordinatesAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->move() moves the current object by (dx,dy) from its current position.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->moveto().
(no version information, might be only in CVS)
SWFDisplayItem->moveTo -- Moves object in global coordinatesAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->moveto() moves the current object to (x,y) in global coordinates.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->move().
(no version information, might be only in CVS)
SWFDisplayItem->multColor -- Multiplies the item's color transformAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->multcolor() multiplies the item's color transform by the given values.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
This simple example will modify your picture's atmosphere to Halloween (use a landscape or bright picture).
Esempio 1. swfdisplayitem->multcolor() example
|
(no version information, might be only in CVS)
SWFDisplayItem->remove -- Removes the object from the movieAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->remove() removes this object from the movie's display list.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfmovie->add().
(no version information, might be only in CVS)
SWFDisplayItem->Rotate -- Rotates in relative coordinatesAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->rotate() rotates the current object by ddegrees degrees from its current rotation.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->rotateto().
(no version information, might be only in CVS)
SWFDisplayItem->rotateTo -- Rotates the object in global coordinatesAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->rotateto() set the current object rotation to degrees degrees in global coordinates.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
This example bring three rotating string from the background to the foreground. Pretty nice.
Esempio 1. swfdisplayitem->rotateto() example
|
See also swfdisplayitem->rotate().
(no version information, might be only in CVS)
SWFDisplayItem->scale -- Scales the object in relative coordinatesAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->scale() scales the current object by (dx,dy) from its current size.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->scaleto().
(no version information, might be only in CVS)
SWFDisplayItem->scaleTo -- Scales the object in global coordinatesAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->scaleto() scales the current object to (x,y) in global coordinates.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->scale().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->setdepth() sets the object's z-order to depth. Depth defaults to the order in which instances are created (by adding a shape/text to a movie)- newer ones are on top of older ones. If two objects are given the same depth, only the later-defined one can be moved.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->setname() sets the object's name to name, for targetting with action script. Only useful on sprites.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->setratio() sets the object's ratio to ratio. Obviously only useful for morphs.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
This simple example will morph nicely three concentric circles.
Esempio 1. swfdisplayitem->setname() example
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->skewx() adds ddegrees to current x-skew.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->skewx(), swfdisplayitem->skewy() and swfdisplayitem->skewyto().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->skewxto() sets the x-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is more forward, less is more backward.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->skewx(), swfdisplayitem->skewy() and swfdisplayitem->skewyto().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->skewy() adds ddegrees to current y-skew.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->skewyto(), swfdisplayitem->skewx() and swfdisplayitem->skewxto().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->skewyto() sets the y-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is more upward, less is more downward.
The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().
See also swfdisplayitem->skewy(), swfdisplayitem->skewx() and swfdisplayitem->skewxto().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem() creates a new swfdisplayitem object.
Here's where all the animation takes place. After you define a shape, a text object, a sprite, or a button, you add it to the movie, then use the returned handle to move, rotate, scale, or skew the thing.
SWFDisplayItem has the following methods : swfdisplayitem->move(), swfdisplayitem->moveto(), swfdisplayitem->scaleto(), swfdisplayitem->scale(), swfdisplayitem->rotate(), swfdisplayitem->rotateto(), swfdisplayitem->skewxto(), swfdisplayitem->skewx(), swfdisplayitem->skewyto() swfdisplayitem->skewyto(), swfdisplayitem->setdepth() swfdisplayitem->remove(), swfdisplayitem->setname() swfdisplayitem->setratio(), swfdisplayitem->addcolor() and swfdisplayitem->multcolor().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swffill->moveto() moves fill's origin to (x,y) in global coordinates.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swffill->rotateto() sets fill's rotation to degrees degrees.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swffill->scaleto() sets fill's scale to x in the x-direction, y in the y-direction.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swffill->skewxto() sets fill x-skew to x. For x is 1.0, it is a 45-degree forward slant. More is more forward, less is more backward.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swffill->skewyto() sets fill y-skew to y. For y is 1.0, it is a 45-degree upward slant. More is more upward, less is more downward.
The swffill() object allows you to transform (scale, skew, rotate) bitmap and gradient fills. swffill() objects are created by the swfshape->addfill() methods.
SWFFill has the following methods: swffill->moveto() and swffill->scaleto(), swffill->rotateto(), swffill->skewxto() and swffill->skewyto().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swffont->getwidth() returns the string string's width, using font's default scaling. You'll probably want to use the swftext() version of this method which uses the text object's scale.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
If filename is the name of an FDB file (i.e., it ends in ".fdb"), load the font definition found in said file. Otherwise, create a browser-defined font reference.
FDB ("font definition block") is a very simple wrapper for the SWF DefineFont2 block which contains a full description of a font. One may create FDB files from SWT Generator template files with the included makefdb utility- look in the util directory off the main ming distribution directory.
Browser-defined fonts don't contain any information about the font other than its name. It is assumed that the font definition will be provided by the movie player. The fonts _serif, _sans, and _typewriter should always be available. For example:
<?php $f = newSWFFont("_sans"); ?> |
swffont() returns a reference to the font definition, for use in the swftext->setfont() and the swftextfield->setfont() methods.
SWFFont has the following methods : swffont->getwidth().
(no version information, might be only in CVS)
SWFGradient->addEntry -- Adds an entry to the gradient listAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfgradient->addentry() adds an entry to the gradient list. ratio is a number between 0 and 1 indicating where in the gradient this color appears. Thou shalt add entries in order of increasing ratio.
red, green, blue is a color (RGB mode). Last parameter a is optional.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfgradient() creates a new SWFGradient object.
After you've added the entries to your gradient, you can use the gradient in a shape fill with the swfshape->addfill() method.
SWFGradient has the following methods : swfgradient->addentry().
This simple example will draw a big black-to-white gradient as background, and a reddish disc in its center.
Esempio 1. swfgradient() example
|
(no version information, might be only in CVS)
SWFMorph->getshape1 -- Gets a handle to the starting shapeAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmorph->getshape1() gets a handle to the morph's starting shape. swfmorph->getshape1() returns an swfshape() object.
(no version information, might be only in CVS)
SWFMorph->getshape2 -- Gets a handle to the ending shapeAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmorph->getshape2() gets a handle to the morph's ending shape. swfmorph->getshape2() returns an swfshape() object.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmorph() creates a new SWFMorph object.
Also called a "shape tween". This thing lets you make those tacky twisting things that make your computer choke. Oh, joy!
The methods here are sort of weird. It would make more sense to just have newSWFMorph(shape1, shape2);, but as things are now, shape2 needs to know that it's the second part of a morph. (This, because it starts writing its output as soon as it gets drawing commands- if it kept its own description of its shapes and wrote on completion this and some other things would be much easier.)
SWFMorph has the following methods : swfmorph->getshape1() and swfmorph->getshape1().
This simple example will morph a big red square into a smaller blue black-bordered square.
Esempio 1. swfmorph() example
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->add() adds instance to the current movie. instance is any type of data : Shapes, text, fonts, etc. must all be added to the movie to make this work.
For displayable types (shape, text, button, sprite), this returns an swfdisplayitem(), a handle to the object in a display list. Thus, you can add the same shape to a movie multiple times and get separate handles back for each separate instance.
See also all other objects (adding this later), and swfmovie->remove()
See examples in : swfdisplayitem->rotateto() and swfshape->addfill().
(no version information, might be only in CVS)
SWFMovie->nextframe -- Moves to the next frame of the animationAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->nextframe() moves to the next frame of the animation.
(no version information, might be only in CVS)
SWFMovie->output -- Dumps your lovingly prepared movie outAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->output() dumps your lovingly prepared movie out. In PHP, preceding this with the command
<?php header('Content-type: application/x-shockwave-flash'); ?> |
The compression level can be a value between 0 and 9, defining the swf compression similar to gzip compression.
See also swfmovie->save().
See examples in : swfmovie->streammp3(), swfdisplayitem->rotateto(), swfaction()... Any example will use this method.
(no version information, might be only in CVS)
swfmovie->remove -- Removes the object instance from the display listAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->remove() removes the object instance instance from the display list.
See also swfmovie->add().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->save() saves your movie to the file named filename.
The compression level can be a value between 0 and 9, defining the swf compression similar to gzip compression.
See also swfmovie->output().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->setbackground() sets the background color. Why is there no rgba version? Think about it. (Actually, that's not such a dumb question after all- you might want to let the HTML background show through. There's a way to do that, but it only works on IE4. Search the http://www.macromedia.com/ site for details.)
(no version information, might be only in CVS)
SWFMovie->setdimension -- Sets the movie's width and heightAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->setdimension() sets the movie's width to width and height to height.
(no version information, might be only in CVS)
SWFMovie->setframes -- Sets the total number of frames in the animationAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->setframes() sets the total number of frames in the animation to numberofframes.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->setrate() sets the frame rate to rate, in frame per seconds. Animation will slow down if the player can't render frames fast enough- unless there's a streaming sound, in which case display frames are sacrificed to keep sound from skipping.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->streammp3() streams the mp3 file mp3File. Not very robust in dealing with oddities (can skip over an initial ID3 tag, but that's about it). Like swfshape->addjpegfill(), this isn't a stable function- we'll probably need to make a separate SWFSound object to contain sound types. Parameter mp3File can be a fopen() resource or a binary string.
Note that the movie isn't smart enough to put enough frames in to contain the entire mp3 stream- you'll have to add (length of song * frames per second) frames to get the entire stream in.
Yes, now you can use ming to put that rock and roll devil worship music into your SWF files. Just don't tell the RIAA.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie() creates a new movie object, representing an SWF version 4 movie.
SWFMovie has the following methods : swfmovie->output(),swfmovie->save(), swfmovie->add(), swfmovie->remove(), swfmovie->nextframe(), swfmovie->setbackground(), swfmovie->setrate(), swfmovie->setdimension(), swfmovie->setframes() and swfmovie->streammp3().
See examples in : swfdisplayitem->rotateto(), swfshape->setline(), swfshape->addfill()... Any example will use this object.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
SWFShape->addFill() adds a solid fill to the shape's list of fill styles. SWFShape->addFill() accepts three different types of arguments.
red, green, blue is a color (RGB mode). Last parameter a is optional.
The bitmap argument is an SWFBitmap() object. The flags argument can be one of the following values: SWFFILL_CLIPPED_BITMAP, SWFFILL_TILED_BITMAP, SWFFILL_LINEAR_GRADIENT or SWFFILL_RADIAL_GRADIENT. Default is SWFFILL_TILED_BITMAP for SWFBitmap and SWFFILL_LINEAR_GRADIENT for SWFGradient.
The gradient argument is an SWFGradient() object. The flags argument can be one of the following values : SWFFILL_RADIAL_GRADIENT or SWFFILL_LINEAR_GRADIENT. Default is SWFFILL_LINEAR_GRADIENT. I'm sure about this one. Really.
SWFShape->addFill() returns an SWFFill() object for use with the SWFShape->setLeftFill() and SWFShape->setRightFill() functions described below.
This simple example will draw a frame on a bitmap. Ah, here's another buglet in the flash player- it doesn't seem to care about the second shape's bitmap's transformation in a morph. According to spec, the bitmap should stretch along with the shape in this example..
Esempio 1. SWFShape->addFill() example
|
See also SWFShape->setLeftFill() and SWFShape->setRightFill().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfshape->drawcurve() draws a quadratic curve (using the current line style,set by swfshape->setline()) from the current pen position to the relative position (anchorx,anchory) using relative control point (controlx,controly). That is, head towards the control point, then smoothly turn to the anchor point.
With 6 parameters, it draws a cubic bezier to point (x+targetdx, x+targetdy) with control points (x+controldx, y+controldy) and (x+anchordx, y+anchordy).
See also swfshape->drawlineto(), swfshape->drawline(), swfshape->movepento() and swfshape->movepen().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfshape->drawcurveto() draws a quadratic curve (using the current line style, set by swfshape->setline()) from the current pen position to (anchorx,anchory) using (controlx,controly) as a control point. That is, head towards the control point, then smoothly turn to the anchor point.
With 6 parameters, it draws a cubic bezier to point (targetx, targety) with control points (controlx, controly) and (anchorx, anchory).
See also swfshape->drawlineto(), swfshape->drawline(), swfshape->movepento() and swfshape->movepen().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfshape->drawline() draws a line (using the current line style set by swfshape->setline()) from the current pen position to displacement (dx,dy).
See also swfshape->movepento(), swfshape->drawcurveto(), swfshape->movepen() and swfshape->drawlineto().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfshape->setrightfill() draws a line (using the current line style, set by swfshape->setline()) from the current pen position to point (x,y) in the shape's coordinate space.
See also swfshape->movepento(), swfshape->drawcurveto(), swfshape->movepen() and swfshape->drawline().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfshape->setrightfill() move the shape's pen from coordinates (current x,current y) to (current x + dx, current y + dy) in the shape's coordinate space.
See also swfshape->movepento(), swfshape->drawcurveto(), swfshape->drawlineto() and swfshape->drawline().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfshape->setrightfill() move the shape's pen to (x,y) in the shape's coordinate space.
See also swfshape->movepen(), swfshape->drawcurveto(), swfshape->drawlineto() and swfshape->drawline().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
What this nonsense is about is, every edge segment borders at most two fills. When rasterizing the object, it's pretty handy to know what those fills are ahead of time, so the swf format requires these to be specified.
swfshape->setleftfill() sets the fill on the left side of the edge- that is, on the interior if you're defining the outline of the shape in a counter-clockwise fashion. The fill object is an SWFFill object returned from one of the addFill functions above.
This seems to be reversed when you're defining a shape in a morph, though. If your browser crashes, just try setting the fill on the other side.
Shortcut for swfshape->setleftfill($s->addfill($r, $g, $b [, $a]));.
See also swfshape->setrightfill().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfshape->setline() sets the shape's line style. width is the line's width. If width is 0, the line's style is removed (then, all other arguments are ignored). If width > 0, then line's color is set to red, green, blue. Last parameter a is optional.
You must declare all line styles before you use them (see example).
This simple example will draw a big "!#%*@", in funny colors and gracious style.
Esempio 1. swfshape->setline() example
|
(no version information, might be only in CVS)
SWFShape->setRightFill -- Sets right rasterizing colorAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
See also swfshape->setleftfill().
Shortcut for swfshape->setrightfill($s->addfill($r, $g, $b [, $a]));.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfshape() creates a new shape object.
SWFShape has the following methods : swfshape->setline(), swfshape->addfill(), swfshape->setleftfill(), swfshape->setrightfill(), swfshape->movepento(), swfshape->movepen(), swfshape->drawlineto(), swfshape->drawline(), swfshape->drawcurveto() and swfshape->drawcurve().
This simple example will draw a big red elliptic quadrant.
Esempio 1. swfshape() example
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfsprite->add() adds a swfshape(), a swfbutton(), a swftext(), a swfaction() or a swfsprite() object.
For displayable types (swfshape(), swfbutton(), swftext(), swfaction() or swfsprite()), this returns a handle to the object in a display list.
(no version information, might be only in CVS)
SWFSprite->nextframe -- Moves to the next frame of the animationAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfsprite->setframes() moves to the next frame of the animation.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfsprite->remove() remove a swfshape(), a swfbutton(), a swftext(), a swfaction() or a swfsprite() object from the sprite.
(no version information, might be only in CVS)
SWFSprite->setframes -- Sets the total number of frames in the animationAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfsprite->setframes() sets the total number of frames in the animation to numberofframes.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfsprite() are also known as a "movie clip", this allows one to create objects which are animated in their own timelines. Hence, the sprite has most of the same methods as the movie.
swfsprite() has the following methods : swfsprite->add(), swfsprite->remove(), swfsprite->nextframe() and swfsprite->setframes().
This simple example will spin gracefully a big red square.
Esempio 1. swfsprite() example
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext->addstring() draws the string string at the current pen (cursor) location. Pen is at the baseline of the text; i.e., ascending text is in the -y direction.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext->addstring() returns the rendered width of the string string at the text object's current font, scale, and spacing settings.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext->moveto() moves the pen (or cursor, if that makes more sense) to (x,y) in text object's coordinate space. If either is zero, though, value in that dimension stays the same. Annoying, should be fixed.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext->setspacing() changes the current text color. Default is black. I think. Color is represented using the RGB system.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext->setfont() sets the current font to font.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext->setheight() sets the current font height to height. Default is 240.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext->setspacing() sets the current font spacing to spacingspacing. Default is 1.0. 0 is all of the letters written at the same point. This doesn't really work that well because it inflates the advance across the letter, doesn't add the same amount of spacing between the letters. I should try and explain that better, prolly. Or just fix the damn thing to do constant spacing. This was really just a way to figure out how letter advances work, anyway.. So nyah.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext() creates a new SWFText object, fresh for manipulating.
SWFText has the following methods : swftext->setfont(), swftext->setheight(), swftext->setspacing(), swftext->setcolor(), swftext->moveto(), swftext->addstring() and swftext->getwidth().
This simple example will draw a big yellow "PHP generates Flash with Ming" text, on white background.
Esempio 1. swftext() example
|
(no version information, might be only in CVS)
SWFTextField->addstring -- Concatenates the given string to the text fieldAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setname() concatenates the string string to the text field.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->align() sets the text field alignment to alignement. Valid values for alignement are : SWFTEXTFIELD_ALIGN_LEFT, SWFTEXTFIELD_ALIGN_RIGHT, SWFTEXTFIELD_ALIGN_CENTER and SWFTEXTFIELD_ALIGN_JUSTIFY.
(no version information, might be only in CVS)
SWFTextField->setbounds -- Sets the text field width and heightAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setbounds() sets the text field width to width and height to height. If you don't set the bounds yourself, Ming makes a poor guess at what the bounds are.
(no version information, might be only in CVS)
SWFTextField->setcolor -- Sets the color of the text fieldAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setcolor() sets the color of the text field. Default is fully opaque black. Color is represented using RGB system.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setfont() sets the text field font to the [browser-defined?] font font.
(no version information, might be only in CVS)
SWFTextField->setHeight -- Sets the font height of this text field fontAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setheight() sets the font height of this text field font to the given height height. Default is 240.
(no version information, might be only in CVS)
SWFTextField->setindentation -- Sets the indentation of the first lineAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setindentation() sets the indentation of the first line in the text field, to width.
(no version information, might be only in CVS)
SWFTextField->setLeftMargin -- Sets the left margin width of the text fieldAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setleftmargin() sets the left margin width of the text field to width. Default is 0.
(no version information, might be only in CVS)
SWFTextField->setLineSpacing -- Sets the line spacing of the text fieldAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setlinespacing() sets the line spacing of the text field to the height of height. Default is 40.
(no version information, might be only in CVS)
SWFTextField->setMargins -- Sets the margins width of the text fieldAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setmargins() set both margins at once, for the man on the go.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setname() sets the variable name of this text field to name, for form posting and action scripting purposes.
(no version information, might be only in CVS)
SWFTextField->setrightMargin -- Sets the right margin width of the text fieldAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setrightmargin() sets the right margin width of the text field to width. Default is 0.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield() creates a new text field object. Text Fields are less flexible than swftext() objects- they can't be rotated, scaled non-proportionally, or skewed, but they can be used as form entries, and they can use browser-defined fonts.
The optional flags change the text field's behavior. It has the following possibles values :
SWFTEXTFIELD_DRAWBOX draws the outline of the textfield
SWFTEXTFIELD_HASLENGTH
SWFTEXTFIELD_HTML allows text markup using HTML-tags
SWFTEXTFIELD_MULTILINE allows multiple lines
SWFTEXTFIELD_NOEDIT indicates that the field shouldn't be user-editable
SWFTEXTFIELD_NOSELECT makes the field non-selectable
SWFTEXTFIELD_PASSWORD obscures the data entry
SWFTEXTFIELD_WORDWRAP allows text to wrap
<?php $t = newSWFTextField(SWFTEXTFIELD_PASSWORD | SWFTEXTFIELD_NOEDIT); ?> |
SWFTextField has the following methods : swftextfield->setfont(), swftextfield->setbounds(), swftextfield->align(), swftextfield->setheight(), swftextfield->setleftmargin(), swftextfield->setrightmargin(), swftextfield->setmargins(), swftextfield->setindentation(), swftextfield->setlinespacing(), swftextfield->setcolor(), swftextfield->setname() and swftextfield->addstring().
These functions were placed here because none of the other categories seemed to fit.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Misc. Configuration Options
Name | Default | Changeable | Changelog |
---|---|---|---|
ignore_user_abort | "0" | PHP_INI_ALL | |
highlight.string | "#DD0000" | PHP_INI_ALL | |
highlight.comment | "#FF8000" | PHP_INI_ALL | |
highlight.keyword | "#007700" | PHP_INI_ALL | |
highlight.bg | "#FFFFFF" | PHP_INI_ALL | |
highlight.default | "#0000BB" | PHP_INI_ALL | |
highlight.html | "#000000" | PHP_INI_ALL | |
browscap | NULL | PHP_INI_SYSTEM |
Breve descrizione dei parametri di configurazione.
TRUE by default. If changed to FALSE scripts will be terminated as soon as they try to output something after a client has aborted their connection.
See also ignore_user_abort().
Colors for Syntax Highlighting mode. Anything that's acceptable in <font color="??????"> would work.
Name (e.g.: browscap.ini) and location of browser capabilities file. See also get_browser().
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Returns TRUE if client disconnected. See the Connection Handling description in the Features chapter for a complete explanation.
See also connection_status(), and ignore_user_abort().
Returns the connection status bitfield. See the Connection Handling description in the Features chapter for a complete explanation.
See also connection_aborted(), and ignore_user_abort().
Returns TRUE if script timed out.
Deprecated |
This function is deprecated, and doesn't even exist anymore as of 4.0.5. |
See the Connection Handling description in the Features chapter for a complete explanation.
See also connection_status().
constant() will return the value of the constant indicated by name.
constant() is useful if you need to retrieve the value of a constant, but do not know its name. I.e. it is stored in a variable or returned by a function.
This function works also with class constants.
Defines a named constant. See the section on constants for more details.
The name of the constant is given by name; the value is given by value.
The optional third parameter case_insensitive is also available. If the value TRUE is given, then the constant will be defined case-insensitive. The default behaviour is case-sensitive; i.e. CONSTANT and Constant represent different values.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also defined(), constant() and the section on Constants.
Returns TRUE if the named constant given by name has been defined, FALSE otherwise.
Nota: If you want to see if a variable exists, use isset() as defined() only applies to constants. If you want to see if a function exists, use function_exists().
See also define(), constant(), get_defined_constants(), function_exists(), and the section on Constants.
eval() evaluates the string given in code_str as PHP code. Among other things, this can be useful for storing code in a database text field for later execution.
There are some factors to keep in mind when using eval(). Remember that the string passed must be valid PHP code, including things like terminating statements with a semicolon so the parser doesn't die on the line after the eval(), and properly escaping things in code_str.
Also remember that variables given values under eval() will retain these values in the main script afterwards.
A return statement will terminate the evaluation of the string immediately. As of PHP 4, eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned. In case of a parse error in the evaluated code, eval() returns FALSE. In case of a fatal error in the evaluated code, the whole script exits. In PHP 3, eval() does not return a value.
Esempio 1. eval() example - simple text merge
Il precedente esempio visualizzerà:
|
Suggerimento: Come con qualsiasi cosa che invia il risultato direttamente al browser, è possibile utilizzare la funzione output-control per catturare l'uscita di questa funzione e salvarla - per esempio - in una stringa.
See also call_user_func().
Nota: This is not a real function, but a language construct.
Nota: PHP >= 4.2.0 does NOT print the status if it is an integer.
The exit() function terminates execution of the script. It prints status just before exiting.
If status is an integer, that value will also be used as the exit status. Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully.
Nota: The die() function is an alias for exit().
See also: register_shutdown_function().
get_browser() attempts to determine the capabilities of the user's browser. This is done by looking up the browser's information in the browscap.ini file.
By default, the value of HTTP User-Agent header is used; however, you can alter this (i.e., look up another browser's info) by passing the optional user_agent parameter to get_browser(). You can bypass user_agent parameter with NULL value.
The information is returned in an object, which will contain various data elements representing, for instance, the browser's major and minor version numbers and ID string; TRUE/FALSE values for features such as frames, JavaScript, and cookies; and so forth.
As of PHP 4.3.2, if the optional parameter return_array is TRUE, this function will return an array instead of an object.
Esempio 1. Listing all information about the users browser
Il precedente esempio visualizzerà qualcosa simile a:
|
The cookies value simply means that the browser itself is capable of accepting cookies and does not mean the user has enabled the browser to accept cookies or not. The only way to test if cookies are accepted is to set one with setcookie(), reload, and check for the value.
Nota: In order for this to work, your browscap configuration setting in php.ini must point to the correct location of the browscap.ini file on your system.
browscap.ini is not bundled with PHP, but you may find an up-to-date php_browscap.ini file here.
While browscap.ini contains information on many browsers, it relies on user updates to keep the database current. The format of the file is fairly self-explanatory.
This function halts the execution of the compiler. This can be useful to embed data in PHP scripts, like the installation files. Byte position of the data start can be determined by the __COMPILER_HALT_OFFSET__ constant which is defined only if there is a __halt_compiler() presented in the file.
Nota: __halt_compiler() can only be used from the outermost scope.
Esempio 1. A __halt_compiler() example
|
The highlight_file() function prints out a syntax highlighted version of the code contained in filename using the colors defined in the built-in syntax highlighter for PHP.
If the second parameter return is set to TRUE then highlight_file() will return the highlighted code as a string instead of printing it out. If the second parameter is not set to TRUE then highlight_file() will return TRUE on success, FALSE on failure.
Nota: The return parameter became available in PHP 4.2.0. Before this time it behaved like the default, which is FALSE
Nota: Since PHP 4.2.1 this function is also affected by safe_mode and open_basedir.
Attenzione |
Care should be taken when using the highlight_file() function to make sure that you do not inadvertently reveal sensitive information such as passwords or any other type of information that might create a potential security risk. |
Many servers are configured to automatically highlight files with a phps extension. For example, example.phps when viewed will show the syntax highlighted source of the file. To enable this, add this line to the httpd.conf:
AddType application/x-httpd-php-source .phps |
See also highlight_string().
The highlight_string() function outputs a syntax highlighted version of str using the colors defined in the built-in syntax highlighter for PHP.
If the second parameter return is set to TRUE then highlight_string() will return the highlighted code as a string instead of printing it out. If the second parameter is not set to TRUE then highlight_string() will return TRUE on success, FALSE on failure.
Esempio 1. highlight_string() example
The above example will output (in PHP 4):
The above example will output (in PHP 5):
|
Nota: The return parameter became available in PHP 4.2.0. Before this time it behaved like the default, which is FALSE
See also highlight_file().
(PHP 3 >= 3.0.7, PHP 4, PHP 5)
ignore_user_abort -- Set whether a client disconnect should abort script executionThis function sets whether a client disconnect should cause a script to be aborted. It will return the previous setting and can be called without an argument to not change the current setting and only return the current setting. See the Connection Handling section in the Features chapter for a complete description of connection handling in PHP.
See also connection_aborted(), and connection_status().
Pack given arguments into binary string according to format. Returns binary string containing data.
The idea to this function was taken from Perl and all formatting codes work the same as there, however, there are some formatting codes that are missing such as Perl's "u" format code. The format string consists of format codes followed by an optional repeater argument. The repeater argument can be either an integer value or * for repeating to the end of the input data. For a, A, h, H the repeat count specifies how many characters of one data argument are taken, for @ it is the absolute position where to put the next data, for everything else the repeat count specifies how many data arguments are consumed and packed into the resulting binary string. Currently implemented are
Tabella 1. pack() format characters
Code | Description |
---|---|
a | NUL-padded string |
A | SPACE-padded string |
h | Hex string, low nibble first |
H | Hex string, high nibble first |
c | signed char |
C | unsigned char |
s | signed short (always 16 bit, machine byte order) |
S | unsigned short (always 16 bit, machine byte order) |
n | unsigned short (always 16 bit, big endian byte order) |
v | unsigned short (always 16 bit, little endian byte order) |
i | signed integer (machine dependent size and byte order) |
I | unsigned integer (machine dependent size and byte order) |
l | signed long (always 32 bit, machine byte order) |
L | unsigned long (always 32 bit, machine byte order) |
N | unsigned long (always 32 bit, big endian byte order) |
V | unsigned long (always 32 bit, little endian byte order) |
f | float (machine dependent size and representation) |
d | double (machine dependent size and representation) |
x | NUL byte |
X | Back up one byte |
@ | NUL-fill to absolute position |
Note that the distinction between signed and unsigned values only affects the function unpack(), where as function pack() gives the same result for signed and unsigned format codes.
Also note that PHP internally stores integer values as signed values of a machine dependent size. If you give it an unsigned integer value too large to be stored that way it is converted to a float which often yields an undesired result.
See also unpack().
For technical reasons, this function is deprecated and removed from PHP. Instead, use php -l somefile.php from the commandline.
The php_check_syntax() function performs a syntax (lint) check on the specified filename testing for scripting errors. This is similar to using php -l from the commandline except php_check_syntax() will execute (but not output) the checked file_name. For example, if a function is defined in file_name, this defined function will be available to the file that executed php_check_syntax(), but output from file_name will be suppressed.
The name of the file being checked.
If the error_message parameter is used, it will contain the error message generated by the syntax check. error_message is passed by reference.
Returns TRUE if the lint check passed, and FALSE if the link check failed or if file_name cannot be opened.
Versione | Descrizione |
---|---|
5.0.5 | This function was removed from PHP. |
5.0.3 | Calling exit() after php_check_syntax() resulted in a Segfault. |
5.0.1 | error_message is passed by reference. |
php -l somefile.php |
Il precedente esempio visualizzerà qualcosa simile a:
PHP Parse error: unexpected T_STRING in /tmp/somefile.php on line 81 |
Returns the PHP source code in filename with PHP comments and whitespace removed. This may be useful for determining the amount of actual code in your scripts compared with the amount of comments. This is similar to using php -w from the commandline.
Nota: This function works as described as of PHP 5.0.1. Before this it would only return an empty string. For more information on this bug and its prior behavior, see bug report #29606.
The stripped source code will be returned on success, or an empty string on failure.
Esempio 1. php_strip_whitespace() example
Il precedente esempio visualizzerà:
Notice the PHP comments are gone, as are the whitespace and newline after the first echo statement. |
The sleep() function delays program execution for the given number of seconds.
See also usleep() and set_time_limit()
Delays program execution for the given number of seconds and nanoseconds.
seconds must be a positive integer, and nanoseconds must be a positive integer less than 1 billion.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
If the delay was interrupted by a signal, an associative array will be returned with the components:
seconds - number of seconds remaining in the delay
nanoseconds - number of nanoseconds remaining in the delay
Esempio 1. time_nanosleep() example
|
Nota: Questa funzione non è implementata su piattaforme Windows
This function will make the script sleep until the specified timestamp. If the specified timestamp is in the past, time_sleep_until() will generate a E_WARNING and return FALSE.
Nota: Questa funzione non è implementata su piattaforme Windows
uniqid() returns a prefixed unique identifier based on the current time in microseconds. prefix is optional but can be useful, for instance, if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond. Up until PHP 4.3.1, prefix could only be a maximum of 114 characters long.
If the optional more_entropy parameter is TRUE, uniqid() will add additional entropy (using the combined linear congruential generator) at the end of the return value, which should make the results more unique.
With an empty prefix, the returned string will be 13 characters long. If more_entropy is TRUE, it will be 23 characters.
Nota: The prefix parameter became optional in PHP 5.
If you need a unique identifier or token and you intend to give out that token to the user via the network (i.e. session cookies), it is recommended that you use something along these lines:
<?php // no prefix $token = md5(uniqid()); // better, difficult to guess $better_token = md5(uniqid(rand(), true)); ?> |
This will create a 32 character identifier (a 128 bit hex number) that is extremely difficult to predict.
unpack() from binary string into array according to format. Returns array containing unpacked elements of binary string.
unpack() works slightly different from Perl as the unpacked data is stored in an associative array. To accomplish this you have to name the different format codes and separate them by a slash /.
Attenzione |
Note that PHP internally stores integral values as signed. If you unpack a large unsigned long and it is of the same size as PHP internally stored values the result will be a negative number even though unsigned unpacking was specified. |
See also pack() for an explanation of the format codes.
The usleep() function delays program execution for the given number of micro_seconds. A microsecond is one millionth of a second.
Nota: This function did not work on Windows systems until PHP 5.0.0
See also sleep() and set_time_limit().
These functions allow you to access the mnoGoSearch (former UdmSearch) free search engine. mnoGoSearch is a full-featured search engine software for intranet and internet servers, distributed under the GNU license. mnoGoSearch has a number of unique features, which makes it appropriate for a wide range of applications from search within your site to a specialized search system such as cooking recipes or newspaper search, FTP archive search, news articles search, etc. It offers full-text indexing and searching for HTML, PDF, and text documents. mnoGoSearch consists of two parts. The first is an indexing mechanism (indexer). The purpose of the indexer is to walk through HTTP, FTP, NEWS servers or local files, recursively grabbing all the documents and storing meta-data about that documents in a SQL database in a smart and effective manner. After every document is referenced by its corresponding URL, meta-data is collected by the indexer for later use in a search process. The search is performed via Web interface. C, CGI, PHP and Perl search front ends are included.
More information about mnoGoSearch can be found at http://www.mnogosearch.org/.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.1.0.
Nota: Questo modulo non è disponibile su piattaforme Windows.
Download mnoGosearch from http://www.mnogosearch.org/ and install it on your system. You need at least version 3.1.10 of mnoGoSearch installed to use these functions.
In order to have these functions available, you must compile PHP with mnoGosearch support by using the --with-mnogosearchoption. If you use this option without specifying the path to mnoGosearch, PHP will look for mnoGosearch under /usr/local/mnogosearch path by default. If you installed mnoGosearch at a different location you should specify it: --with-mnogosearch=DIR.
Nota: PHP contains built-in MySQL access library, which can be used to access MySQL. It is known that mnoGoSearch is not compatible with this built-in library and can work only with generic MySQL libraries. Thus, if you use mnoGoSearch with MySQL, during PHP configuration you have to indicate the directory of your MySQL installation, that was used during mnoGoSearch configuration, i.e. for example: --with-mnogosearch --with-mysql=/usr.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
udm_add_search_limit() adds search restrictions. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
agent - a link to Agent, received after call to udm_alloc_agent().
var - defines parameter, indicating limit.
val - defines the value of the current parameter.
Possible var values:
UDM_LIMIT_URL - defines document URL limitations to limit the search through subsection of the database. It supports SQL % and _ LIKE wildcards, where % matches any number of characters, even zero characters, and _ matches exactly one character. E.g. http://www.example.___/catalog may stand for http://www.example.com/catalog and http://www.example.net/catalog.
UDM_LIMIT_TAG - defines site TAG limitations. In indexer-conf you can assign specific TAGs to various sites and parts of a site. Tags in mnoGoSearch 3.1.x are lines, that may contain metasymbols % and _. Metasymbols allow searching among groups of tags. E.g. there are links with tags ABCD and ABCE, and search restriction is by ABC_ - the search will be made among both of the tags.
UDM_LIMIT_LANG - defines document language limitations.
UDM_LIMIT_CAT - defines document category limitations. Categories are similar to tag feature, but nested. So you can have one category inside another and so on. You have to use two characters for each level. Use a hex number going from 0-F or a 36 base number going from 0-Z. Therefore a top-level category like 'Auto' would be 01. If it has a subcategory like 'Ford', then it would be 01 (the parent category) and then 'Ford' which we will give 01. Put those together and you get 0101. If 'Auto' had another subcategory named 'VW', then it's id would be 01 because it belongs to the 'Ford' category and then 02 because it's the next category. So it's id would be 0102. If VW had a sub category called 'Engine' then it's id would start at 01 again and it would get the 'VW' id 02 and 'Auto' id of 01, making it 010201. If you want to search for sites under that category then you pass it cat=010201 in the URL.
UDM_LIMIT_DATE - defines limitation by date the document was modified.
Format of parameter value: a string with first character < or >, then with no space - date in unixtime format, for example:
If > character is used, then the search will be restricted to those documents having a modification date greater than entered, if <, then smaller.
udm_alloc_agent_array() will create an agent with multiple database connections. The array databases must contain one database URL per element, analog to the first parameter of udm_alloc_agent().
See also: udm_alloc_agent().
Returns a mnogosearch agent identifier on success, FALSE on failure. This function creates a session with database parameters.
dbaddr - URL-style database description, with options (type, host, database name, port, user and password) to connect to SQL database. Do not matter for built-in text files support. Format for dbaddr: DBType:[//[DBUser[:DBPass]@]DBHost[:DBPort]]/DBName/. Currently supported DBType values are: mysql, pgsql, msql, solid, mssql, oracle, and ibase. Actually, it does not matter for native libraries support, but ODBC users should specify one of the supported values. If your database type is not supported, you may use unknown instead.
dbmode - You may select the SQL database mode of words storage. Possible values of dbmode are: single, multi, crc, or crc-multi. When single is specified, all words are stored in the same table. If multi is selected, words will be located in different tables depending of their lengths. "multi" mode is usually faster, but requires more tables in the database. If "crc" mode is selected, mnoGoSearch will store 32 bit integer word IDs calculated by CRC32 algorithm instead of words. This mode requires less disk space and it is faster comparing with "single" and "multi" modes. crc-multi uses the same storage structure with the "crc" mode, but also stores words in different tables depending on words lengths like in "multi" mode.
Nota: dbaddr and dbmode must match those used during indexing.
Nota: In fact this function does not open a connection to the database and thus does not check the entered login and password. Establishing a connection to the database and login/password verification is done by udm_find().
udm_api_version() returns the mnoGoSearch API version number. E.g. if mnoGoSearch 3.1.10 API is used, this function will return 30110.
This function allows the user to identify which API functions are available, e.g. udm_get_doc_count() function is only available in mnoGoSearch 3.1.11 or later.
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)
udm_cat_list -- Get all the categories on the same level with the current oneReturns an array listing all categories of the same level as the current category in the categories tree. agent is the agent identifier returned by a previous call to >udm_alloc_agent().
The function can be useful for developing categories tree browser.
The returned array consists of pairs. Elements with even index numbers contain the category paths, odd elements contain the corresponding category names.
$array[0] will contain '020300' $array[1] will contain 'Audi' $array[2] will contain '020301' $array[3] will contain 'BMW' $array[4] will contain '020302' $array[5] will contain 'Opel' ... etc. |
Following is an example of displaying links of the current level in format:
Audi BMW Opel ... |
See also udm_cat_path().
Returns an array describing the path in the categories tree from the tree root to the current one, specified by category. agent is the agent identifier returned by a previous call to >udm_alloc_agent().
The returned array consists of pairs. Elements with even index numbers contain the category paths, odd elements contain the corresponding category names.
For example, the call $array=udm_cat_path($agent, '02031D'); may return the following array:
$array[0] will contain '' $array[1] will contain 'Root' $array[2] will contain '02' $array[3] will contain 'Sport' $array[4] will contain '0203' $array[5] will contain 'Auto' $array[4] will contain '02031D' $array[5] will contain 'Ferrari' |
Esempio 1. Specifying path to the current category in the following format: '> Root > Sport > Auto > Ferrari'
|
See also udm_cat_list().
(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)
udm_check_charset -- Check if the given charset is known to mnogosearch
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)
udm_clear_search_limits -- Clear all mnoGoSearch search restrictionsudm_clear_search_limits() resets defined search limitations and returns TRUE.
See also udm_add_search_limit().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
udm_errno() returns mnoGoSearch error number, zero if no error.
agent - link to agent identifier, received after call to udm_alloc_agent().
Receiving numeric agent error code.
udm_error() returns mnoGoSearch error message, empty string if no error.
agent - link to agent identifier, received after call to udm_alloc_agent().
Receiving agent error message.
Returns a result link identifier on success, or FALSE on failure.
The search itself. The first argument - session, the next one - query itself. To find something just type words you want to find and press SUBMIT button. For example, "mysql odbc". You should not use quotes " in query, they are written here only to divide a query from other text. mnoGoSearch will find all documents that contain word "mysql" and/or word "odbc". Best documents having bigger weights will be displayed first. If you use search mode ALL, search will return documents that contain both (or more) words you entered. In case you use mode ANY, the search will return list of documents that contain any of the words you entered. If you want more advanced results you may use query language. You should select "bool" match mode in the search from.
mnoGoSearch understands the following boolean operators:
& - logical AND. For example, "mysql & odbc". mnoGoSearch will find any URLs that contain both "mysql" and "odbc".
| - logical OR. For example "mysql|odbc". mnoGoSearch will find any URLs, that contain word "mysql" or word "odbc".
~ - logical NOT. For example "mysql & ~odbc". mnoGoSearch will find URLs that contain word "mysql" and do not contain word "odbc" at the same time. Note that ~ just excludes given word from results. Query "~odbc" will find nothing!
() - group command to compose more complex queries. For example "(mysql | msql) & ~postgres". Query language is simple and powerful at the same time. Just consider query as usual boolean expression.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
agent - link to agent identifier, received ` after call to udm_alloc_agent().
Freeing up memory allocated for agent session.
udm_free_ispell_data() always returns TRUE.
agent - agent link identifier, received after call to udm_alloc_agent().
Nota: This function is supported beginning from version 3.1.12 of mnoGoSearch and it does not do anything in previous versions.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
res - a link to result identifier, received after call to udm_find().
Freeing up memory allocated for results.
udm_get_doc_count() returns the number of documents in the database.
agent - link to agent identifier, received after call to udm_alloc_agent().
Nota: This function is supported only in mnoGoSearch 3.1.11 or later.
udm_get_res_field() returns result field value on success, FALSE on error.
res - a link to result identifier, received after call to udm_find().
row - the number of the link on the current page. May have values from 0 to UDM_PARAM_NUM_ROWS-1.
field - field identifier, may have the following values:
UDM_FIELD_URL - document URL field
UDM_FIELD_CONTENT - document Content-type field (for example, text/html).
UDM_FIELD_CATEGORY - document category field. Use udm_cat_path() to get full path to current category from the categories tree root. (This parameter is available only in PHP 4.0.6 or later).
UDM_FIELD_TITLE - document title field.
UDM_FIELD_KEYWORDS - document keywords field (from META KEYWORDS tag).
UDM_FIELD_DESC - document description field (from META DESCRIPTION tag).
UDM_FIELD_TEXT - document body text (the first couple of lines to give an idea of what the document is about).
UDM_FIELD_SIZE - document size.
UDM_FIELD_URLID - unique URL ID of the link.
UDM_FIELD_RATING - page rating (as calculated by mnoGoSearch).
UDM_FIELD_MODIFIED - last-modified field in unixtime format.
UDM_FIELD_ORDER - the number of the current document in set of found documents.
UDM_FIELD_CRC - document CRC.
udm_get_res_param() returns result parameter value on success, FALSE on error.
res - a link to result identifier, received after call to udm_find().
param - parameter identifier, may have the following values:
UDM_PARAM_NUM_ROWS - number of received found links on the current page. It is equal to UDM_PARAM_PAGE_SIZE for all search pages, on the last page - the rest of links.
UDM_PARAM_FOUND - total number of results matching the query.
UDM_PARAM_WORDINFO - information on the words found. E.g. search for "a good book" will return "a: stopword, good:5637, book: 120"
UDM_PARAM_SEARCHTIME - search time in seconds.
UDM_PARAM_FIRST_DOC - the number of the first document displayed on current page.
UDM_PARAM_LAST_DOC - the number of the last document displayed on current page.
udm_hash32() will take a string str and return a quite unique 32-bit hash number from it. Requires an allocated agent.
See also: udm_alloc_agent().
udm_load_ispell_data() loads ispell data. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
agent - agent link identifier, received after call to udm_alloc_agent().
var - parameter, indicating the source for ispell data. May have the following values:
After using this function to free memory allocated for ispell data, please use udm_free_ispell_data(), even if you use UDM_ISPELL_TYPE_SERVER mode.
The fastest mode is UDM_ISPELL_TYPE_SERVER. UDM_ISPELL_TYPE_TEXT is slower and UDM_ISPELL_TYPE_DB is the slowest. The above pattern is TRUE for mnoGoSearch 3.1.10 - 3.1.11. It is planned to speed up DB mode in future versions and it is going to be faster than TEXT mode.
UDM_ISPELL_TYPE_DB - indicates that ispell data should be loaded from SQL. In this case, parameters val1 and val2 are ignored and should be left blank. flag should be equal to 1.
Nota: flag indicates that after loading ispell data from defined source it should be sorted (it is necessary for correct functioning of ispell). In case of loading ispell data from files there may be several calls to udm_load_ispell_data(), and there is no sense to sort data after every call, but only after the last one. Since in db mode all the data is loaded by one call, this parameter should have the value 1. In this mode in case of error, e.g. if ispell tables are absent, the function will return FALSE and code and error message will be accessible through udm_error() and udm_errno().
UDM_ISPELL_TYPE_AFFIX - indicates that ispell data should be loaded from file and initiates loading affixes file. In this case val1 defines double letter language code for which affixes are loaded, and val2 - file path. Please note, that if a relative path entered, the module looks for the file not in UDM_CONF_DIR, but in relation to current path, i.e. to the path where the script is executed. In case of error in this mode, e.g. if file is absent, the function will return FALSE, and an error message will be displayed. Error message text cannot be accessed through udm_error() and udm_errno(), since those functions can only return messages associated with SQL. Please, see flag parameter description in UDM_ISPELL_TYPE_DB.
Esempio 2. udm_load_ispell_data() example
|
Nota: flag is equal to 1 only in the last call.
UDM_ISPELL_TYPE_SPELL - indicates that ispell data should be loaded from file and initiates loading of ispell dictionary file. In this case val1 defines double letter language code for which affixes are loaded, and val2 - file path. Please note, that if a relative path entered, the module looks for the file not in UDM_CONF_DIR, but in relation to current path, i.e. to the path where the script is executed. In case of error in this mode, e.g. if file is absent, the function will return FALSE, and an error message will be displayed. Error message text cannot be accessed through udm_error() and udm_errno(), since those functions can only return messages associated with SQL. Please, see flag parameter description in UDM_ISPELL_TYPE_DB.
<?php if ((! Udm_Load_Ispell_Data($udm, UDM_ISPELL_TYPE_AFFIX, 'en', '/opt/ispell/en.aff', 0)) || (! Udm_Load_Ispell_Data($udm, UDM_ISPELL_TYPE_AFFIX, 'ru', '/opt/ispell/ru.aff', 0)) || (! Udm_Load_Ispell_Data($udm, UDM_ISPELL_TYPE_SPELL, 'en', '/opt/ispell/en.dict', 0)) || (! Udm_Load_Ispell_Data($udm, UDM_ISPELL_TYPE_SPELL, 'ru', '/opt/ispell/ru.dict', 1))) { exit; } ?> |
Nota: flag is equal to 1 only in the last call.
UDM_ISPELL_TYPE_SERVER - enables spell server support. val1 parameter indicates address of the host running spell server. val2 ` is not used yet, but in future releases it is going to indicate number of port used by spell server. flag parameter in this case is not needed since ispell data is stored on spellserver already sorted.
Spelld server reads spell-data from a separate configuration file (/usr/local/mnogosearch/etc/spelld.conf by default), sorts it and stores in memory. With clients server communicates in two ways: to indexer all the data is transferred (so that indexer starts faster), from search.cgi server receives word to normalize and then passes over to client (search.cgi) list of normalized word forms. This allows fastest, compared to db and text modes processing of search queries (by omitting loading and sorting all the spell data).
udm_load_ispell_data() function in UDM_ISPELL_TYPE_SERVER mode does not actually load ispell data, but only defines server address. In fact, server is automatically used by udm_find() function when performing search. In case of errors, e.g. if spellserver is not running or invalid host indicated, there are no messages returned and ispell conversion does not work.
Nota: This function is available in mnoGoSearch 3.1.12 or later.
Example:
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. Defines mnoGoSearch session parameters.
The following parameters and their values are available:
UDM_PARAM_PAGE_NUM - used to choose search results page number (results are returned by pages beginning from 0, with UDM_PARAM_PAGE_SIZE results per page).
UDM_PARAM_PAGE_SIZE - number of search results displayed on one page.
UDM_PARAM_SEARCH_MODE - search mode. The following values available: UDM_MODE_ALL - search for all words; UDM_MODE_ANY - search for any word; UDM_MODE_PHRASE - phrase search; UDM_MODE_BOOL - boolean search. See udm_find() for details on boolean search.
UDM_PARAM_CACHE_MODE - turns on or off search result cache mode. When enabled, the search engine will store search results to disk. In case a similar search is performed later, the engine will take results from the cache for faster performance. Available values: UDM_CACHE_ENABLED, UDM_CACHE_DISABLED.
UDM_PARAM_TRACK_MODE - turns on or off trackquery mode. Since version 3.1.2 mnoGoSearch has a query tracking support. Note that tracking is implemented in SQL version only and not available in built-in database. To use tracking, you have to create tables for tracking support. For MySQL, use create/mysql/track.txt. When doing a search, front-end uses those tables to store query words, a number of found documents and current Unix timestamp in seconds. Available values: UDM_TRACK_ENABLED, UDM_TRACK_DISABLED.
UDM_PARAM_PHRASE_MODE - defines whether index database using phrases ("phrase" parameter in indexer.conf). Possible values: UDM_PHRASE_ENABLED and UDM_PHRASE_DISABLED. Please note, that if phrase search is enabled (UDM_PHRASE_ENABLED), it is still possible to do search in any mode (ANY, ALL, BOOL or PHRASE). In 3.1.10 version of mnoGoSearch phrase search is supported only in sql and built-in database modes, while beginning with 3.1.11 phrases are supported in cachemode as well.
Examples of phrase search:
"Arizona desert" - This query returns all indexed documents that contain "Arizona desert" as a phrase. Notice that you need to put double quotes around the phrase
UDM_PARAM_CHARSET - defines local charset. Available values: set of charsets supported by mnoGoSearch, e.g. koi8-r, cp1251, ...
UDM_PARAM_STOPFILE - Defines name and path to stopwords file. (There is a small difference with mnoGoSearch - while in mnoGoSearch if relative path or no path entered, it looks for this file in relation to UDM_CONF_DIR, the module looks for the file in relation to current path, i.e. to the path where the PHP script is executed.)
UDM_PARAM_STOPTABLE - Load stop words from the given SQL table. You may use several StopwordTable commands. This command has no effect when compiled without SQL database support.
UDM_PARAM_WEIGHT_FACTOR - represents weight factors for specific document parts. Currently body, title, keywords, description, url are supported. To activate this feature please use degrees of 2 in *Weight commands of the indexer.conf. Let's imagine that we have these weights:
URLWeight 1
BodyWeight 2
TitleWeight 4
KeywordWeight 8
DescWeight 16
As far as indexer uses bit OR operation for word weights when some word presents several time in the same document, it is possible at search time to detect word appearance in different document parts. Word which appears only in the body will have 00000010 aggregate weight (in binary notation). Word used in all document parts will have 00011111 aggregate weight.
This parameter's value is a string of hex digits ABCDE. Each digit is a factor for corresponding bit in word weight. For the given above weights configuration:
E is a factor for weight 1 (URL Weight bit)
D is a factor for weight 2 (BodyWeight bit)
C is a factor for weight 4 (TitleWeight bit)
B is a factor for weight 8 (KeywordWeight bit)
A is a factor for weight 16 (DescWeight bit)
Examples:
UDM_PARAM_WEIGHT_FACTOR=00001 will search through URLs only.
UDM_PARAM_WEIGHT_FACTOR=00100 will search through Titles only.
UDM_PARAM_WEIGHT_FACTOR=11100 will search through Title,Keywords,Description but not through URL and Body.
UDM_PARAM_WEIGHT_FACTOR=F9421 will search through:
Description with factor 15 (F hex)
Keywords with factor 9
Title with factor 4
Body with factor 2
URL with factor 1
If UDM_PARAM_WEIGHT_FACTOR variable is omitted, original weight value is taken to sort results. For a given above weight configuration it means that document description has a most big weight 16.
UDM_PARAM_WORD_MATCH - word match. You may use this parameter to choose word match type. This feature works only in "single" and "multi" modes using SQL based and built-in database. It does not work in cachemode and other modes since they use word CRC and do not support substring search. Available values:
UDM_MATCH_BEGIN - word beginning match;
UDM_MATCH_END - word ending match;
UDM_MATCH_WORD - whole word match;
UDM_MATCH_SUBSTR - word substring match.
UDM_PARAM_MIN_WORD_LEN - defines minimal word length. Any word shorter this limit is considered to be a stopword. Please note that this parameter value is inclusive, i.e. if UDM_PARAM_MIN_WORD_LEN=3, a word 3 characters long will not be considered a stopword, while a word 2 characters long will be. Default value is 1.
UDM_PARAM_ISPELL_PREFIXES - Possible values: UDM_PREFIXES_ENABLED and UDM_PREFIXES_DISABLED, that respectively enable or disable using prefixes. E.g. if a word "tested" is in search query, also words like "test", "testing", etc. Only suffixes are supported by default. Prefixes usually change word meanings, for example if somebody is searching for the word "tested" one hardly wants "untested" to be found. Prefixes support may also be found useful for site's spelling checking purposes. In order to enable ispell, you have to load ispell data with udm_load_ispell_data().
UDM_PARAM_CROSS_WORDS - enables or disables crosswords support. Possible values: UDM_CROSS_WORDS_ENABLED and UDM_CROSS_WORDS_DISABLED.
The crosswords feature allows to assign words between <a href="xxx"> and </a> also to a document this link leads to. It works in SQL database mode and is not supported in built-in database and Cachemode.
Nota: Crosswords are supported only in mnoGoSearch 3.1.11 or later.
UDM_PARAM_VARDIR - specifies a custom path to directory where indexer stores data when using built-in database and in cache mode. By default /var directory of mnoGoSearch installation is used. Can have only string values. The parameter is available in PHP 4.1.0 or later.
Queste funzioni permettono di accedere ad un database MS SQL Server.
Requisiti per le piattaforme Win32
Per potere funzionare è richiesto che sia installato il MS SQL Client Tools sullo stesso sistema su cui è il installato il PHP. Il Client Tools può essere installato o dal cd di MS SQL Server, o copiando il file ntwdblib.dll dalla directory \winnt\system32 del server alla directory \winnt\system32 della macchina su cui è installato il PHP. La copia del file ntwdblib.dll permette solo l'accesso al database. La configurazione del client richiede comunque l'installazione di tutto il pacchetto MS SQL Client Tools.
Requisiti per le piattaforme Unix/Linux
Per potere utilizzare l'estensione MSSQl su piattaforme Unix/Linux, occorre compilare ed installare la libreria FreeTDS. Il codice sorgente e le istruzioni per l'installazione sono disponibili nel sito di FreeTDS: http://www.freetds.org/
Nota: Nella piattaforma Windows si utilizzano le DBLIB di Microsoft. Quindi le funzioni che restituiscono il nome della colonna si basano sulla funzione dbcolname() della DBLIB. La DBLIB è stata sviluppata per SQL Server 6.x che ammetteva nomi di colonna lunghi al massimo 30 caratteri. Per questo motivo il numero massimo di caratteri per il nome colonna ammessi sono 30. Nelle piattaforme in cui si utilizza FreeTDS (Linux) non si ha questo problema.
Il modulo MSSQL si abilita aggiungendo extension=php_mssql.dll al file di configurazione php.ini.
Per attivare queste funzionalità occorre compilare il PHP con --with-mssql[=DIR], dove DIR è la directory in cui è installato FreeTDS. Il pacchetto FreeTDS dovrebbe essere compilato utilizzando --enable-msdblib.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Parametri di configurazione per il modulo MS SQL Server
Nome | Default | Modificabile | Log Variazioni |
---|---|---|---|
mssql.allow_persistent | "1" | PHP_INI_SYSTEM | |
mssql.max_persistent | "-1" | PHP_INI_SYSTEM | |
mssql.max_links | "-1" | PHP_INI_SYSTEM | |
mssql.min_error_severity | "10" | PHP_INI_ALL | |
mssql.min_message_severity | "10" | PHP_INI_ALL | |
mssql.compatability_mode | "0" | PHP_INI_ALL | |
mssql.connect_timeout | "5" | PHP_INI_ALL | |
mssql.timeout | "60" | PHP_INI_ALL | Disponibile da PHP 4.1.0 |
mssql.textsize | "-1" | PHP_INI_ALL | |
mssql.textlimit | "-1" | PHP_INI_ALL | |
mssql.batchsize | "0" | PHP_INI_ALL | Disponibile da PHP 4.0.4 |
mssql.datetimeconvert | "1" | PHP_INI_ALL | Disponibile da PHP 4.2.0 |
mssql.secure_connection | "0" | PHP_INI_SYSTEM | Disponibile da PHP 4.3.0 |
mssql.max_procs | "25" | PHP_INI_ALL | Disponibile da PHP 4.3.0 |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
(PHP 4 >= 4.1.0, PHP 5)
mssql_bind -- Aggiunge un parametro ad una procedura memorizzata (stored procedure) locale o remotaAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche mssql_execute(), mssql_free_statement() e mssql_init().
La funzione mssql_close() chiude la connessione ad un database MS SQL Server che è associata all' argomento id_connessione. Se l' id_connessione non viene indicato, si fa riferimento all'ultima connessione aperta.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: solitamente non è necessario l'uso della funzione, dato che tutte le connessioni non-persistenti sono chiuse automaticamente al termine dell'esecuzione dello script.
mssql_close() non chiude i collegamenti persistenti aperti utilizzando mssql_pconnect().
Vedere anche: mssql_connect() e mssql_pconnect().
Restituisce: un identificativo di connessione MS SQL se l'operazione riesce, oppure FALSE se si verifica un errore.
La funzione mssql_connect() realizza una connessione con un server MS SQL. L' argomento nome_server deve essere un nome valido di server come definito nel file 'interfaces'.
Qualora la funzione mssql_connect() venga eseguita una seconda volta con i medesimi parametri, non viene realizzata una nuova connessione, ma, invece, viene restituito l'identificativo della connessione già aperta.
La connessione con il server verrà chiusa non appena lo script terminerà l'esecuzione, a meno che la connessione non sia già stata chiusa utilizzando la funzione mssql_close().
Vedere anche mssql_pconnect(), e mssql_close().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione mssql_data_seek() sposta il puntatore di riga, interno al risultato associato all'identificativo di risultato, alla riga indicata dall'argomento numero_riga, la prima riga inzia con il numero 0. La chiamata successiva a mssql_fetch_row() restituirà la riga richiesta.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Se le stored procedure restituiscono parametri oppure valori, questi saranno disponibili successivamente all'esecuzione della funzione mssql_execute() a meno che non sia restituito più di un set di risultati. In questo caso occorre utilizzare mssql_next_result() per spostarsi tra i risultati. Una volta terminato lo scorrimento dei set di risultati, sia i parametri di output sia i valori di ritorno saranno disponibili.
Vedere anche mssql_bind(), mssql_free_statement() e mssql_init().
(PHP 3, PHP 4, PHP 5)
mssql_fetch_array -- Restituisce una riga in un array associativo, numerico o entrambiLa funzione restituisce: un array corrispondente alla riga estratta, oppure falso se non vi sono più righe.
La funzione mssql_fetch_array() è un' estensione della funzione mssql_fetch_row(). Oltre a memorizzare i dati in un array con indice numerico, la funzione memorizza i dati in un array associativo in cui la chiave è costituita dal nome del campo.
Un aspetto da notare è che la funzione mssql_fetch_array() NON è significativamente più lenta rispetto a mssql_fetch_row(), mentre nel contempo fornisce funzionalità maggiori.
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Nota: This function sets NULL fields to PHP NULL value.
Per ulteriori dettagli vedere anche mssql_fetch_row().
(PHP 4 >= 4.2.0, PHP 5)
mssql_fetch_assoc -- Restituisce un array associativo con i dati di una riga dal set di risultati indicato da id_risultatoAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione restituisce un oggetto contenente le informazioni sul campo.
La funzione mssql_fetch_field() può essere utilizzata per ottenere informazioni sui campi presenti nel risultato di una certa query. Se non viene specificato l'argomento offset_campo, la funzione restituisce il campo successivo che non è ancora stato restituito da mssql_fetch_field().
Le proprietà dell'oggetto sono:
name - nome della colonna. Se la colonna è il risultato di una funzione, questa proprietà è valorizzata con "computed#N", dove #N è un numero progressivo.
column_source - tabella da cui sono ricavate le colonne
max_length - lunghezza massima della colonna
numeric - 1 se la colonna è numerica
type - tipo di colonna.
Vedere anche mssql_field_seek().
La funzione restituisce un oggetto le cui proprietà corrispondono alla riga estratta, oppure falso se non vi sono più righe.
La funzione mssql_fetch_object() è simile a mssql_fetch_array(), tranne che per una differenza, la prima restituisce un oggetto, la seconda un array. Indirettamente questo significa che si può accedere ai dati solo attraverso il nome dei campi e non tramite il loro offset (i numeri non sono dei validi nomi di proprietà).
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Nota: This function sets NULL fields to PHP NULL value.
A livello di velocità il comportamento è simile a mssql_fetch_array(), e quasi veloce come mssql_fetch_row() (la differenza è insignificante ).
Vedere anche mssql_fetch_array() e mssql_fetch_row().
La funzione restituisce un array che corrisponde alla riga estratta, oppure falso se non vi sono più righe.
La funzione mssql_fetch_row() estrae una riga di dati dal risultato associato all'identificativo di risultato passato. La riga viene restituita in un array. Ciascuna colonna è memorizzata in un campo dell'array. Il primo ha indice 0.
Esecuzione successive di mssql_fetch_row() restituiscono le righe successive presenti nel risultato, oppure falso se non vi sono più righe.
Nota: This function sets NULL fields to PHP NULL value.
Vedere anche mssql_fetch_array(), mssql_fetch_object(), mssql_data_seek(), mssql_fetch_lengths() e mssql_result().
Questa funzione restituisce il valore del campo numero offset dalla query indicata da result. Se si omette offset la funzione resituisce il valore per il campo corrente.
Nota per gli utenti Win32: A causa delle limitazione delle sottostanti API utilizzate dal PHP (MS DbLib C API), la lunghezza dei campi VARCHAR è limitata a 255. Se si ha necessità di memorizzare maggiori informazioni, utilizzare il tipo TEXT
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Si posiziona sul campo richiesto. Eseguendo successivamente la funzione mssql_fetch_field() senza indicare alcun campo, quest'ultima restituirà il campo richiesto tramite mssql_fetch_field().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche mssql_fetch_field().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
E' necessario l'utilizzo della funzione mssql_free_result() solo quando si è preoccupati dell'occupazione di memoria durante l'esecuzione dello script. Normalmente tutti i dati verranno rimossi automaticamente dalla memoria al termine dell'esecuzione dello script.E' tuttavia possibile eseguire mssql_free_result(), per liberare la memoria occupata dai dati indicati dal parametro id_risultato
mssql_free_statement() only needs to be called if you are worried about using too much memory while your script is running. All statement memory will automatically be freed when the script ends. You may call mssql_free_statement() with the statement identifier as an argument and the associated statement memory will be freed.
See also mssql_bind(), mssql_execute(), and mssql_init()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
mssql_guid_string -- Converte il GUID dal formato binario a 16 bit al formato stringaAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche: mssql_bind(), mssql_execute() e mssql_free_statement()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nel caso in cui si eseguano più di una istruzione SQL al server, oppure si eseguano delle procedure memorizzate (stored procedure) con possibilità di molteplici risultati, il server restituirà un set di diversi risultati. Questa funzione verifica se esistono ulteriori risultati dal server. Se effettivamente esiste un'altro risultato, questa funzione libera la memoria dal risultato corrente e si predispone per la ricezione del risultato successivo. La funzione restituisce TRUE se è disponibile un'altro risultato, FALSE in caso contrario.
Esempio 1. mssql_next_result() Esempio di utilizzo
|
La funzione mssql_num_fields() restituisce il numero di campi presenti in un risultato.
Vedere anche: mssql_query(), mssql_fetch_field() e mssql_num_rows().
La funzione mssql_num_rows() restituisce il numero di righe presenti in un risultato.
Vedere anche: mssql_query() e mssql_fetch_row().
La funzione restituisce: o un identificativo di connessione persistente, o FALSE se si verifica un errore.
La funzione mssql_pconnect() agisce come mssql_connect() tranne che per due differenze.
Prima differenza, quando si cerca di stabilire la connessione, la funzione per prima cosa cerca di trovare una connessione (persistente) già aperta verso lo stesso server, con i medesimi utenti e password. Se ne viene trovata una, la funzione restituisce l'identificativo di quella connessione, invece di stabilirne una nuova.
Seconda differenza, la connessione con il server SQL non verrà chiusa al termine dello script. Il collegamento resterà aperto per utilizzi futuri (la funzione mssql_close() non chiude i collegamenti aperti da mssql_pconnect()).
Per questo motivo questo tipo di collegamento viene definito 'persistente'.
La funzione restituisce un identificativo di risultato in caso di esecuzione corretta, TRUE se non sono restituite reighe, oppure falso in caso di errore.
La funzione mssql_query() invia una query al database attivo sul server attraverso la connessione specificata da id_connessione. Se l'argomento id_connessione non viene fornito, si utilizza l'ultima connessione aperta in ordine di tempo. Se non vi sono connessioni aperte, la funzione tenta di stabilire una connessione, come se fosse utilizzata la funzione mssql_connect(), e utilizza quella.
Vedere anche: mssql_select_db() e mssql_connect().
La funzione mssql_result() restituisce il contenuto di una cella da un risultato di una query a MS SQL. L'argomento campo può essere la posizione di un campo, oppure il suo nome, oppure nome tabella punto nome campo ( nome_tabella.nome_campo ). Se il nome della colonna ha un sostituto, ('select foo as bar from...'), usare quello anzichè il nome originale.
Quando si lavora con risultati abbastanza grossi, si dovrebbe considerare l'utilizzo di funzioni che restituiscono l'intera riga ( indicate di seguito ), dato che queste restituiscono il contenuto di molte celle in una chiamata sola. Pertanto sono MOLTO più veloci di mssql_result(). Da notare inoltre, che specificando la posizione per l'argomento campo, la funzione è molto più veloce rispetto al caso in cui si indica il nome del campo o della tabella.
Le alternative più veloci raccomandate sono: mssql_fetch_row(), mssql_fetch_array(), e mssql_fetch_object().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione mssql_select_db() setta il database attivo sul server attraverso la connessione specificata da id_connessione. Se l'argomento id_connessione non viene fornito, si utilizza l'ultima connessione aperta in ordine di tempo. Se non vi sono connessioni aperte, la funzione tenta di stabilire una connessione, come se fosse utilizzata la funzione mssql_connect(), e utilizza quella.
Ciascuna esecuzione di mssql_query() sarà fatta sul database attivo.
Per potere selezionare un database contenente un nome o un trattivo ("-") nel nome occorre racchiudere il nome stesso tra parantesi quadre, come illustrato nell'esempio seguente:
Vedere anche: mssql_connect(), mssql_pconnect(), e mssql_query()
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
On Windows, you should use the PDO_ODBC driver to connect to Microsoft SQL Server and Sybase databases, as the native Windows DB-LIB is ancient, thread un-safe and no longer supported by Microsoft.
(no version information, might be only in CVS)
PDO_DBLIB DSN -- Connecting to Microsoft SQL Server and Sybase databasesThe PDO_DBLIB Data Source Name (DSN) is composed of the following elements:
The DSN prefix is sybase: if PDO_DBLIB was linked against the FreeTDS libraries, mssql: if PDO_DBLIB was linked against the Microsoft SQL Server libraries, or dblib: if linked against any other variety of DB-lib.
The hostname on which the database server resides.
The name of the database.
msession is an interface to a high speed session daemon which can run either locally or remotely. It is designed to provide consistent session management for a PHP web farm. More Information about msession and the session server software itself can be found at http://devel.mohawksoft.com/msession.html.
Nota: Questo modulo non è disponibile su piattaforme Windows.
To enable Msession support configure PHP --with-msession[=DIR], where DIR is the Msession install directory.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Returns an associative array of value/session for all sessions with a variable named name.
Used for searching sessions with common attributes.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
msession_plugin -- Call an escape function within the msession personality pluginAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
These functions allow you to access mSQL database servers. More information about mSQL can be found at http://www.hughes.com.au/.
In order to have these functions available, you must compile PHP with msql support by using the --with-msql[=DIR] option. DIR is the mSQL base install directory, defaults to /usr/local/msql3.
Note to Win32 Users: In order to enable this module on a Windows environment, you must copy msql.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. mSQL configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
msql.allow_persistent | "1" | PHP_INI_ALL | |
msql.max_persistent | "-1" | PHP_INI_ALL | |
msql.max_links | "-1" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
There are two resource types used in the mSQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
This simple example shows how to connect, execute a query, print resulting rows and disconnect from a mSQL database.
Esempio 1. mSQL usage example
|
Returns number of affected rows by the last SELECT, UPDATE or DELETE query associated with result.
The result resource that is being evaluated. This result comes from a call to msql_query().
msql_close() closes the non-persistent connection to the mSQL server that's associated with the specified link identifier.
Using msql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. See also freeing resources.
The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.
msql_connect() establishes a connection to a mSQL server.
In case a second call is made to msql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.
The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling msql_close().
The hostname can also include a port number. e.g. hostname,port.
If not specified, the connection is established by the means of a Unix domain socket, being then more efficient then a localhost TCP socket connection.
Nota: While this function will accept a colon (:) as a host/port separator, a comma (,) is the preferred method.
msql_create_db() attempts to create a new database on the mSQL server.
The name of the mSQL database.
The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.
msql_data_seek() moves the internal row pointer of the mSQL result associated with the specified query identifier to point to the specified row number. The next call to msql_fetch_row() would return that row.
The result resource that is being evaluated. This result comes from a call to msql_query().
The seeked row number.
msql_db_query() selects a database and executes a query on it.
The name of the mSQL database.
The SQL query.
The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.
msql_drop_db() attempts to drop (remove) a database from the mSQL server.
The name of the database.
The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.
msql_error() returns the last issued error by the mSQL server. Note that only the last error message is accessible with msql_error().
msql_fetch_array() is an extended version of msql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.
An important thing to note is that using msql_fetch_array() is NOT significantly slower than using msql_fetch_row(), while it provides a significant added value.
The result resource that is being evaluated. This result comes from a call to msql_query().
A constant that can take the following values: MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH with MSQL_BOTH being the default.
Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
Esempio 1. msql_fetch_array() example
|
msql_fetch_field() can be used in order to obtain information about fields in a certain query result.
The result resource that is being evaluated. This result comes from a call to msql_query().
The field offset. If not specified, the next field that wasn't yet retrieved by msql_fetch_field() is retrieved.
Returns an object containing field information. The properties of the object are:
name - column name
table - name of the table the column belongs to
not_null - 1 if the column cannot be NULL
unique - 1 if the column is a unique key
type - the type of the column
msql_fetch_object() is similar to msql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
Speed-wise, the function is identical to msql_fetch_array(), and almost as quick as msql_fetch_row() (the difference is insignificant).
The result resource that is being evaluated. This result comes from a call to msql_query().
Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.
Esempio 1. msql_fetch_object() example
|
msql_fetch_row() fetches one row of data from the result associated with the specified query identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
Subsequent call to msql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.
The result resource that is being evaluated. This result comes from a call to msql_query().
Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
Esempio 1. msql_fetch_row() example
|
msql_field_flags() returns the field flags of the specified field.
The result resource that is being evaluated. This result comes from a call to msql_query().
The numerical field offset. The field_offset starts at 1.
Returns a string containing the field flags of the specified key. This can be: primary key not null, not null, primary key, unique not null or unique.
msql_field_len() returns the length of the specified field.
The result resource that is being evaluated. This result comes from a call to msql_query().
The numerical field offset. The field_offset starts at 1.
msql_field_name() gets the name of the specified field index.
The result resource that is being evaluated. This result comes from a call to msql_query().
The numerical field offset. The field_offset starts at 1.
Seeks to the specified field offset. If the next call to msql_fetch_field() won't include a field offset, this field would be returned.
The result resource that is being evaluated. This result comes from a call to msql_query().
The numerical field offset. The field_offset starts at 1.
Returns the name of the table that the specified field is in.
The result resource that is being evaluated. This result comes from a call to msql_query().
The numerical field offset. The field_offset starts at 1.
msql_field_type() gets the type of the specified field index.
The result resource that is being evaluated. This result comes from a call to msql_query().
The numerical field offset. The field_offset starts at 1.
The type of the field. One of int, char, real, ident, null or unknown. This functions will return FALSE on failure.
msql_free_result() frees the memory associated with query_identifier. When PHP completes a request, this memory is freed automatically, so you only need to call this function when you want to make sure you don't use too much memory while the script is running.
The result resource that is being evaluated. This result comes from a call to msql_query().
msql_list_tables() lists the databases available on the specified link_identifier.
The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.
Returns a result set which may be traversed with any function that fetches result sets, such as msql_fetch_array(). On failure, this function will return FALSE.
msql_list_fields() returns information about the given table.
The name of the database.
The name of the table.
The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.
Returns a result set which may be traversed with any function that fetches result sets, such as msql_fetch_array(). On failure, this function will return FALSE.
msql_list_tables() lists the tables on the specified database.
The name of the database.
The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.
Returns a result set which may be traversed with any function that fetches result sets, such as msql_fetch_array(). On failure, this function will return FALSE.
msql_num_fields() returns the number of fields in a result set.
The result resource that is being evaluated. This result comes from a call to msql_query().
msql_num_rows() returns the number of rows in a result set.
The result resource that is being evaluated. This result comes from a call to msql_query().
msql_pconnect() acts very much like msql_connect() with two major differences.
First, when connecting, the function would first try to find a (persistent) link that's already open with the same host. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (msql_close() will not close links established by this function).
The hostname can also include a port number. e.g. hostname,port.
If not specified, the connection is established by the means of a Unix domain socket, being then more efficient then a localhost TCP socket connection.
Nota: While this function will accept a colon (:) as a host/port separator, a comma (,) is the preferred method.
msql_query() sends a query to the currently active database on the server that's associated with the specified link identifier.
The SQL query.
The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.
Esempio 1. msql_query() example
|
msql_result() returns the contents of one cell from a mSQL result set.
When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they are often much quicker than msql_result().
Recommended high-performance alternatives: msql_fetch_row(), msql_fetch_array(), and msql_fetch_object().
The result resource that is being evaluated. This result comes from a call to msql_query().
The row offset.
Can be the field's offset, or the field's name, or the field's table dot field's name (tablename.fieldname.). If the column name has been aliased ('select foo as bar from ...'), use the alias instead of the column name.
Nota: Specifying a numeric field offset is much quicker than specifying a fieldname or tablename.fieldname.
Returns the contents of the cell at the row and offset in the specified mSQL result set.
msql_select_db() sets the current active database on the server that's associated with the specified link_identifier.
Subsequent calls to msql_query() will be made on the active database.
The database name.
The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.
While there are many languages in which every necessary character can be represented by a one-to-one mapping to a 8-bit value, there are also several languages which require so many characters for written communication that cannot be contained within the range a mere byte can code. Multibyte character encoding schemes were developed to express that many (more than 256) characters in the regular bytewise coding system.
When you manipulate (trim, split, splice, etc.) strings encoded in a multibyte encoding, you need to use special functions since two or more consecutive bytes may represent a single character in such encoding schemes. Otherwise, if you apply a non-multibyte-aware string function to the string, it probably fails to detect the beginning or ending of the multibyte character and ends up with a corrupted garbage string that most likely loses its original meaning.
mbstring provides these multibyte specific string functions that help you deal with multibyte encodings in PHP, which is basically supposed to be used with single byte encodings. In addition to that, mbstring handles character encoding conversion between the possible encoding pairs.
mbstring is also designed to handle Unicode-based encodings such as UTF-8 and UCS-2 and many single-byte encodings for convenience (listed below), whereas mbstring was originally developed for use in Japanese web pages.
Encodings of the following types are safely used with PHP.
A singlebyte encoding,
which has ASCII-compatible (ISO646 compatible) mappings for the characters in range of 00h to 7fh.
A multibyte encoding,
which has ASCII-compatible mappings for the characters in range of 00h to 7fh.
which don't use ISO2022 escape sequences.
which don't use a value from 00h to 7fh in any of the compounded bytes that represents a single character.
These are examples of character encodings that are unlikely to work with PHP.
Although PHP scripts written in any of those encodings might not work, especially in the case where encoded strings appear as identifiers or literals in the script, you can almost avoid using these encodings by setting up the mbstring's transparent encoding filter function for incoming HTTP queries.
Nota: It's highly discouraged to use SJIS, BIG5, CP936, CP949 and GB18030 for the internal encoding unless you are familiar with the parser, the scanner and the character encoding.
Nota: If you have some database connected with PHP, it is recommended that you use the same character encoding for both database and the internal encoding for ease of use and better performance.
If you are using PostgreSQL, the character encoding used in the database and the one used in the PHP may differ as it supports automatic character set conversion between the backend and the frontend.
mbstring is a non-default extension. This means it is not enabled by default. You must explicitly enable the module with the configure option. See the Install section for details.
The following configure options are related to the mbstring module.
--enable-mbstring=LANG: Enable mbstring functions. This option is required to use mbstring functions.
As of PHP 4.3.0, mbstring extension provides enhanced support for Simplified Chinese, Traditional Chinese, Korean, and Russian in addition to Japanese. To enable that feature, you will have to supply either one of the following options to the LANG parameter; --enable-mbstring=cn for Simplified Chinese support, --enable-mbstring=tw for Traditional Chinese support, --enable-mbstring=kr for Korean support, --enable-mbstring=ru for Russian support, and --enable-mbstring=ja for Japanese support.
Also --enable-mbstring=all is convenient for you to enable all the supported languages listed above.
Nota: Japanese language support is also enabled by --enable-mbstring without any options for the sake of backwards compatibility.
--enable-mbstr-enc-trans : Enable HTTP input character encoding conversion using mbstring conversion engine. If this feature is enabled, HTTP input character encoding may be converted to mbstring.internal_encoding automatically.
Nota: As of PHP 4.3.0, the option --enable-mbstr-enc-trans was eliminated and replaced with the runtime setting mbstring.encoding_translation. HTTP input character encoding conversion is enabled when this is set to On (the default is Off).
--enable-mbregex: Enable regular expression functions with multibyte character support.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. mbstring configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
mbstring.language | "neutral" | PHP_INI_PERDIR | Available since PHP 4.3.0. |
mbstring.detect_order | NULL | PHP_INI_ALL | Available since PHP 4.0.6. |
mbstring.http_input | "pass" | PHP_INI_ALL | Available since PHP 4.0.6. |
mbstring.http_output | "pass" | PHP_INI_ALL | Available since PHP 4.0.6. |
mbstring.internal_encoding | NULL | PHP_INI_ALL | Available since PHP 4.0.6. |
mbstring.script_encoding | NULL | PHP_INI_ALL | Available since PHP 4.3.0. |
mbstring.substitute_character | NULL | PHP_INI_ALL | Available since PHP 4.0.6. |
mbstring.func_overload | "0" | PHP_INI_PERDIR | PHP_INI_SYSTEM in PHP <= 4.2.3. Available since PHP 4.2.0. |
mbstring.encoding_translation | "0" | PHP_INI_PERDIR | Available since PHP 4.3.0. |
Breve descrizione dei parametri di configurazione.
The default national language setting (NLS) used in mbstring. Note that this option automagically defines mbstring.internal_encoding and mbstring.internal_encoding should be placed after mbstring.language in php.ini
Enables the transparent character encoding filter for the incoming HTTP queries, which performs detection and conversion of the input encoding to the internal character encoding.
Defines the default internal character encoding.
Defines the default HTTP input character encoding.
Defines the default HTTP output character encoding.
Defines default character code detection order. See also mb_detect_order().
Defines character to substitute for invalid character encoding.
Overloads a set of single byte functions by the mbstring counterparts. See Function overloading for more information.
According to the HTML 4.01 specification, Web browsers are allowed to encode a form being submitted with a character encoding different from the one used for the page. See mb_http_input() to detect character encoding used by browsers.
Although popular browsers are capable of giving a reasonably accurate guess to the character encoding of a given HTML document, it would be better to set the charset parameter in the Content-Type HTTP header to the appropriate value by header() or default_charset ini setting.
Esempio 1. php.ini setting examples
|
Esempio 2. php.ini setting for EUC-JP users
|
Esempio 3. php.ini setting for SJIS users
|
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
HTTP input/output character encoding conversion may convert binary data also. Users are supposed to control character encoding conversion if binary data is used for HTTP input/output.
Nota: In PHP 4.3.2 or earlier versions, there was a limitation in this functionality that mbstring does not perform character encoding conversion in POST data if the enctype attribute in the form element is set to multipart/form-data. So you have to convert the incoming data by yourself in this case if necessary.
Beginning with PHP 4.3.3, if enctype for HTML form is set to multipart/form-data and mbstring.encoding_translation is set to On in php.ini the POST'ed variables and the names of uploaded files will be converted to the internal character encoding as well. However, the conversion isn't applied to the query keys.
HTTP Input
There is no way to control HTTP input character conversion from PHP script. To disable HTTP input character conversion, it has to be done in php.ini.
When using PHP as an Apache module, it is possible to override those settings in each Virtual Host directive in httpd.conf or per directory with .htaccess. Refer to the Configuration section and Apache Manual for details.
HTTP Output
There are several ways to enable output character encoding conversion. One is using php.ini, another is using ob_start() with mb_output_handler() as ob_start callback function.
Nota: PHP3-i18n users should note that mbstring's output conversion differs from PHP3-i18n. Character encoding is converted using output buffer.
Currently the following character encodings are supported by the mbstring module. Any of those Character encodings can be specified in the encoding parameter of mbstring functions.
The following character encoding is supported in this PHP extension:
UCS-4
UCS-4BE
UCS-4LE
UCS-2
UCS-2BE
UCS-2LE
UTF-32
UTF-32BE
UTF-32LE
UTF-16
UTF-16BE
UTF-16LE
UTF-7
UTF7-IMAP
UTF-8
ASCII
EUC-JP
SJIS
eucJP-win
SJIS-win
ISO-2022-JP
JIS
ISO-8859-1
ISO-8859-2
ISO-8859-3
ISO-8859-4
ISO-8859-5
ISO-8859-6
ISO-8859-7
ISO-8859-8
ISO-8859-9
ISO-8859-10
ISO-8859-13
ISO-8859-14
ISO-8859-15
byte2be
byte2le
byte4be
byte4le
BASE64
HTML-ENTITIES
7bit
8bit
EUC-CN
CP936
HZ
EUC-TW
CP950
BIG-5
EUC-KR
UHC (CP949)
ISO-2022-KR
Windows-1251 (CP1251)
Windows-1252 (CP1252)
CP866 (IBM866)
KOI8-R
php.ini entry, which accepts encoding name, accepts "auto" and "pass" also. mbstring functions, which accepts encoding name, and accepts "auto".
If "pass" is set, no character encoding conversion is performed.
If "auto" is set, it is expanded to the list of encodings defined per the NLS. For instance, if the NLS is set to Japanese, the value is assumed to be "ASCII,JIS,UTF-8,EUC-JP,SJIS".
See also mb_detect_order()
You might often find it difficult to get an existing PHP application work in a given multibyte environment. That's mostly because lots of PHP applications out there are written with the standard string functions such as substr(), which are known to not properly handle multibyte-encoded strings.
mbstring supports 'function overloading' feature which enables you to add multibyte awareness to such an application without code modification by overloading multibyte counterparts on the standard string functions. For example, mb_substr() is called instead of substr() if function overloading is enabled. This feature makes it easy to port applications that only support single-byte encodings to a multibyte environment in many cases.
To use the function overloading, set mbstring.func_overload in php.ini to a positive value that represents a combination of bitmasks specifying the categories of functions to be overloaded. It should be set to 1 to overload the mail() function. 2 for string functions, 4 for regular expression functions. For example, if is set for 7, mail, strings and regular expression functions should be overloaded. The list of overloaded functions are shown below.
Tabella 2. Functions to be overloaded
value of mbstring.func_overload | original function | overloaded function |
---|---|---|
1 | mail() | mb_send_mail() |
2 | strlen() | mb_strlen() |
2 | strpos() | mb_strpos() |
2 | strrpos() | mb_strrpos() |
2 | substr() | mb_substr() |
2 | strtolower() | mb_strtolower() |
2 | strtoupper() | mb_strtoupper() |
2 | substr_count() | mb_substr_count() |
4 | ereg() | mb_ereg() |
4 | eregi() | mb_eregi() |
4 | ereg_replace() | mb_ereg_replace() |
4 | eregi_replace() | mb_eregi_replace() |
4 | split() | mb_split() |
Nota: It is not recommended to use the function overloading option in the per-directory context, because it's not confirmed yet to be stable enough in a production environment and may lead to undefined behaviour.
It is often said quite hard to figure out how Japanese texts are handled in the computer. This is not only because Japanese characters can only be represented by multibyte encodings, but because different encoding standards are adopted for different purposes / platforms. Moreover, not a few character set standards are used there, which are slightly different from one another. Those facts have often led developers to inevitable mess-up.
To create a working web application that would be put in the Japanese environment, it is important to use the proper character encoding and character set for the task in hand.
Storage for a character can be up to six bytes
Most of multibyte characters often appear twice as wide as a single-byte character on display. Those characters are called "zen-kaku" in Japanese which means "full width", and the other (narrower) characters are called "han-kaku" - means half width. However the graphical properties of the characters depend on the glyphs of the type faces used to display them or print them out.
Some character encodings use shift(escape) sequences defined in ISO2022 to switch the code map of the specific code area (00h to 7fh).
ISO-2022-JP should be used in SMTP/NNTP, and headers and entities should be reencoded as per RFC requirements. Although those are not requisites, it's still a good idea because several popular user agents cannot recognize any other encoding methods.
Webpages created for mobile phone services such as i-mode, Vodafone live!, or EZweb are supposed to use Shift_JIS.
Multibyte character encoding schemes and the related issues are very complicated. There should be too few space to cover in sufficient details. Please refer to the following URLs and other resources for further readings.
Unicode materials
Japanese/Korean/Chinese character information
Summaries of supported encodings
Name in the IANA character set registry: ISO-10646-UCS-4
Underlying character set: ISO 10646
Description: The Universal Character Set with 31-bit code space, standardized as UCS-4 by ISO/IEC 10646. It is kept synchronized with the latest version of the Unicode code map.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry: ISO-10646-UCS-4
Underlying character set: UCS-4
Description: See above.
Additional note: In contrast to UCS-4, strings are always assumed to be in big endian form.
Name in the IANA character set registry: ISO-10646-UCS-4
Underlying character set: UCS-4
Description: See above.
Additional note: In contrast to UCS-4, strings are always assumed to be in little endian form.
Name in the IANA character set registry: ISO-10646-UCS-2
Underlying character set: UCS-2
Description: The Universal Character Set with 16-bit code space, standardized as UCS-2 by ISO/IEC 10646. It is kept synchronized with the latest version of the unicode code map.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry: ISO-10646-UCS-2
Underlying character set: UCS-2
Description: See above.
Additional note: In contrast to UCS-2, strings are always assumed to be in big endian form.
Name in the IANA character set registry: ISO-10646-UCS-2
Underlying character set: UCS-2
Description: See above.
Additional note: In contrast to UCS-2, strings are always assumed to be in little endian form.
Name in the IANA character set registry: UTF-32
Underlying character set: Unicode
Description: Unicode Transformation Format of 32-bit unit width, whose encoding space refers to the Unicode's codeset standard. This encoding scheme wasn't identical to UCS-4 because the code space of Unicode were limited to a 21-bit value.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry: UTF-32BE
Underlying character set: Unicode
Description: See above
Additional note: In contrast to UTF-32, strings are always assumed to be in big endian form.
Name in the IANA character set registry: UTF-32LE
Underlying character set: Unicode
Description: See above
Additional note: In contrast to UTF-32, strings are always assumed to be in little endian form.
Name in the IANA character set registry: UTF-16
Underlying character set: Unicode
Description: Unicode Transformation Format of 16-bit unit width. It's worth a note that UTF-16 is no longer the same specification as UCS-2 because the surrogate mechanism has been introduced since Unicode 2.0 and UTF-16 now refers to a 21-bit code space.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry: UTF-16BE
Underlying character set: Unicode
Description: See above.
Additional note: In contrast to UTF-16, strings are always assumed to be in big endian form.
Name in the IANA character set registry: UTF-16BE
Underlying character set: Unicode
Description: See above.
Additional note: In contrast to UTF-16, strings are always assumed to be in big endian form.
Name in the IANA character set registry: UTF-8
Underlying character set: Unicode / UCS
Description: Unicode Transformation Format of 8-bit unit width.
Additional note: none
Name in the IANA character set registry: UTF-7
Underlying character set: Unicode
Description: A mail-safe transformation format of Unicode, specified in RFC2152.
Additional note: none
Name in the IANA character set registry: (none)
Underlying character set: Unicode
Description: A variant of UTF-7 which is specialized for use in the IMAP protocol.
Additional note: none
Name in the IANA character set registry: US-ASCII (preferred MIME name) / iso-ir-6 / ANSI_X3.4-1986 / ISO_646.irv:1991 / ASCII / ISO646-US / us / IBM367 / CP367 / csASCII
Underlying character set: ASCII / ISO 646
Description: American Standard Code for Information Interchange is a commonly-used 7-bit encoding. Also standardized as an international standard, ISO 646.
Additional note: (none)
Name in the IANA character set registry: EUC-JP (preferred MIME name) / Extended_UNIX_Code_Packed_Format_for_Japanese / csEUCPkdFmtJapanese
Underlying character set: Compound of US-ASCII / JIS X0201:1997 (hankaku kana part) / JIS X0208:1990 / JIS X0212:1990
Description: As you see the name is derived from an abbreviation of Extended UNIX Code Packed Format for Japanese, this encoding is mostly used on UNIX or alike platforms. The original encoding scheme, Extended UNIX Code, is designed on the basis of ISO 2022.
Additional note: The character set referred to by EUC-JP is different to IBM932 / CP932, which are used by OS/2® and Microsoft® Windows®. For information interchange with those platforms, use EUCJP-WIN instead.
Name in the IANA character set registry: Shift_JIS (preferred MIME name) / MS_Kanji / csShift_JIS
Underlying character set: Compound of JIS X0201:1997 / JIS X0208:1997
Description: Shift_JIS was developed in early 80's, at the time personal Japanese word processors were brought into the market, in order to maintain compatiblities with the legacy encoding scheme JIS X 0201:1976. According to the IANA definition the codeset of Shift_JIS is slightly different to IBM932 / CP932. However, the names "SJIS" / "Shift_JIS" are often wrongly used to refer to these codesets.
Additional note: For the CP932 codemap, use SJIS-WIN instead.
Name in the IANA character set registry: (none)
Underlying character set: Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions
Description: While this "encoding" uses the same encoding scheme as EUC-JP, the underlying character set is different. That is, some code points map to different characters than EUC-JP.
Additional note: none
Name in the IANA character set registry: Windows-31J / csWindows31J
Underlying character set: Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions
Description: While this "encoding" uses the same encoding scheme as Shift_JIS, the underlying character set is different. That means some code points map to different characters than Shift_JIS.
Additional note: (none)
Name in the IANA character set registry: ISO-2022-JP (preferred MIME name) / csISO2022JP
Underlying character set: US-ASCII / JIS X0201:1976 / JIS X0208:1978 / JIS X0208:1983
Description: RFC1468
Additional note: (none)
Name in the IANA character set registry: JIS
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-1
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-2
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-3
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-4
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-5
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-6
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-7
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-8
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-9
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-10
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-13
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-14
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-15
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: byte2be
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: byte2le
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: byte4be
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: byte4le
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: BASE64
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: HTML-ENTITIES
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: 7bit
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: 8bit
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: EUC-CN
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: CP936
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: HZ
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: EUC-TW
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: CP950
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: BIG-5
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: EUC-KR
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: UHC (CP949)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-2022-KR
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: Windows-1251 (CP1251)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: Windows-1252 (CP1252)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: CP866 (IBM866)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: KOI8-R
Underlying character set:
Description:
Additional note:
mb_convert_case() returns case folded version of string converted in the way specified by mode.
mode can be one of MB_CASE_UPPER, MB_CASE_LOWER or MB_CASE_TITLE.
encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.
The return value is str with the appropriate case folding applied.
By contrast to the standard case folding functions such as strtolower() and strtoupper(), case folding is performed on the basis of the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as A-umlaut (Ä).
For more information about the Unicode properties, please see http://www.unicode.org/unicode/reports/tr21/.
Esempio 1. mb_convert_case() example
|
See also mb_strtolower(), mb_strtoupper(), strtolower(), strtoupper(), ucfirst() e ucwords()
mb_convert_encoding() converts character encoding of string str from from_encoding to to_encoding.
str : String to be converted.
from_encoding is specified by character code name before conversion. it can be array or string - comma separated enumerated list. If it is not specified, the internal encoding will be used.
Esempio 1. mb_convert_encoding() example
|
See also mb_detect_order().
(PHP 4 >= 4.0.6, PHP 5)
mb_convert_kana -- Convert "kana" one from another ("zen-kaku", "han-kaku" and more)mb_convert_kana() performs "han-kaku" - "zen-kaku" conversion for string str. It returns converted string. This function is only useful for Japanese.
option is conversion option. Default value is "KV".
encoding is character encoding. If it is omitted, internal character encoding is used.
Specify with combination of following options. Default value is KV.
Tabella 1. Applicable Conversion Options
Option | Meaning |
---|---|
r | Convert "zen-kaku" alphabets to "han-kaku" |
R | Convert "han-kaku" alphabets to "zen-kaku" |
n | Convert "zen-kaku" numbers to "han-kaku" |
N | Convert "han-kaku" numbers to "zen-kaku" |
a | Convert "zen-kaku" alphabets and numbers to "han-kaku" |
A | Convert "han-kaku" alphabets and numbers to "zen-kaku" (Characters included in "a", "A" options are U+0021 - U+007E excluding U+0022, U+0027, U+005C, U+007E) |
s | Convert "zen-kaku" space to "han-kaku" (U+3000 -> U+0020) |
S | Convert "han-kaku" space to "zen-kaku" (U+0020 -> U+3000) |
k | Convert "zen-kaku kata-kana" to "han-kaku kata-kana" |
K | Convert "han-kaku kata-kana" to "zen-kaku kata-kana" |
h | Convert "zen-kaku hira-gana" to "han-kaku kata-kana" |
H | Convert "han-kaku kata-kana" to "zen-kaku hira-gana" |
c | Convert "zen-kaku kata-kana" to "zen-kaku hira-gana" |
C | Convert "zen-kaku hira-gana" to "zen-kaku kata-kana" |
V | Collapse voiced sound notation and convert them into a character. Use with "K","H" |
mb_convert_variables() convert character encoding of variables vars in encoding from_encoding to encoding to_encoding. It returns character encoding before conversion for success, FALSE for failure.
mb_convert_variables() join strings in Array or Object to detect encoding, since encoding detection tends to fail for short strings. Therefore, it is impossible to mix encoding in single array or object.
It from_encoding is specified by array or comma separated string, it tries to detect encoding from from-coding. When encoding is omitted, detect_order is used.
vars (3rd and larger) is reference to variable to be converted. String, Array and Object are accepted. mb_convert_variables() assumes all parameters have the same encoding.
mb_decode_mimeheader() decodes encoded-word string str in MIME header.
It returns decoded string in internal character encoding.
See also mb_encode_mimeheader().
Convert numeric string reference of string str in specified block to character. It returns converted string.
convmap is array to specifies code area to convert.
encoding is character encoding. If it is omitted, internal character encoding is used.
Esempio 1. convmap example
|
See also mb_encode_numericentity().
mb_detect_encoding() detects character encoding in string str. It returns detected character encoding.
encoding_list is list of character encoding. Encoding order may be specified by array or comma separated list string.
If encoding_list is omitted, detect_order is used.
Esempio 1. mb_detect_encoding() example
|
See also mb_detect_order().
mb_detect_order() sets automatic character encoding detection order to encoding_list. It returns TRUE for success, FALSE for failure.
encoding_list is array or comma separated list of character encoding. ("auto" is expanded to "ASCII, JIS, UTF-8, EUC-JP, SJIS")
If encoding_list is omitted, it returns current character encoding detection order as array.
This setting affects mb_detect_encoding() and mb_send_mail().
Nota: mbstring currently implements following encoding detection filters. If there is an invalid byte sequence for following encoding, encoding detection will fail.
Nota: UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP
For ISO-8859-*, mbstring always detects as ISO-8859-*.
For UTF-16, UTF-32, UCS2 and UCS4, encoding detection will fail always.
Esempio 2. mb_detect_order() examples
|
See also mb_internal_encoding(), mb_http_input(), mb_http_output() and mb_send_mail().
mb_encode_mimeheader() encodes a given string str by the MIME header encoding scheme. Returns a converted version of the string represented in ASCII.
charset specifies the name of the character set in which str is represented in. The default value is determined by the current NLS setting (mbstring.language).
transfer_encoding specifies the scheme of MIME encoding. It should be either "B" (Base64) or "Q" (Quoted-Printable). Falls back to "B" if not given.
linefeed specifies the EOL (end-of-line) marker with which mb_encode_mime_header() performs line-folding (a RFC term, the act of breaking a line longer than a certain length into multiple lines. The length is currently hard-coded to 74 characters). Falls back to "\r\n" (CRLF) if not given.
Nota: This function isn't designed to break lines at higher-level contextual break points (word boundaries, etc.). This behaviour may clutter up the original string with unexpected spaces.
See also mb_decode_mimeheader().
mb_encode_numericentity() converts specified character codes in string str from HTML numeric character reference to character code. It returns converted string.
convmap is array specifies code area to convert.
encoding is character encoding.
Esempio 1. convmap example
|
Esempio 2. mb_encode_numericentity() example
|
See also mb_decode_numericentity().
mb_ereg_match() returns TRUE if string matches regular expression pattern, FALSE if not.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
See also: mb_regex_encoding(), mb_ereg().
mb_ereg_replace() scans string for matches to pattern, then replaces the matched text with replacement and returns the result string or FALSE on error. Multibyte character can be used in pattern.
Matching condition can be set by option parameter. If i is specified for this parameter, the case will be ignored. If x is specified, white space will be ignored. If m is specified, match will be executed in multiline mode and line break will be included in '.'. If p is specified, match will be executed in POSIX mode, line break will be considered as normal character. If e is specified, replacement string will be evaluated as PHP expression.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
See also: mb_regex_encoding(), mb_eregi_replace().
mb_ereg_search_getpos() returns the point to start regular expression match for mb_ereg_search(), mb_ereg_search_pos(), mb_ereg_search_regs(). The position is represented by bytes from the head of string.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
See also: mb_regex_encoding(), mb_ereg_search_setpos().
(PHP 4 >= 4.2.0)
mb_ereg_search_getregs -- Retrieve the result from the last multibyte regular expression matchmb_ereg_search_getregs() returns an array including the sub-string of matched part by last mb_ereg_search(), mb_ereg_search_pos(), mb_ereg_search_regs(). If there are some maches, the first element will have the matched sub-string, the second element will have the first part grouped with brackets, the third element will have the second part grouped with brackets, and so on. It returns FALSE on error;
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
See also: mb_regex_encoding(), mb_ereg_search_init().
(PHP 4 >= 4.2.0)
mb_ereg_search_init -- Setup string and regular expression for multibyte regular expression matchmb_ereg_search_init() sets string and pattern for multibyte regular expression. These values are used for mb_ereg_search(), mb_ereg_search_pos(), mb_ereg_search_regs(). It returns TRUE for success, FALSE for error.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
See also: mb_regex_encoding(), mb_ereg_search_regs().
(PHP 4 >= 4.2.0)
mb_ereg_search_pos -- Return position and length of matched part of multibyte regular expression for predefined multibyte stringmb_ereg_search_pos() returns an array including position of matched part for multibyte regular expression. The first element of the array will be the beginning of matched part, the second element will be length (bytes) of matched part. It returns FALSE on error.
The string for match is specified by mb_ereg_search_init(). If it is not specified, the previous one will be used.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
See also: mb_regex_encoding(), mb_ereg_search_init().
mb_ereg_search_regs() executes the multibyte regular expression match, and if there are some matched part, it returns an array including substring of matched part as first element, the first grouped part with brackets as second element, the second grouped part as third element, and so on. It returns FALSE on error.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
See also: mb_regex_encoding(), mb_ereg_search_init().
mb_ereg_search_setpos() sets the starting point of match for mb_ereg_search().
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
See also: mb_regex_encoding(), mb_ereg_search_init().
(PHP 4 >= 4.2.0)
mb_ereg_search -- Multibyte regular expression match for predefined multibyte stringmb_ereg_search() returns TRUE if the multibyte string matches with the regular expression, FALSE for otherwise. The string for matching is set by mb_ereg_search_init(). If pattern is not specified, the previous one is used.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
See also: mb_regex_encoding(), mb_ereg_search_init().
mb_ereg() executes the regular expression match with multibyte support, and returns 1 if matches are found. If the optional third parameter was specified, the function returns the byte length of matched part, and the array regs will contain the substring of matched string. The functions returns 1 if it matches with the empty string. If no matches found or error happend, FALSE will be returned.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
See also: mb_regex_encoding(), mb_eregi()
mb_ereg_replace() scans string for matches to pattern, then replaces the matched text with replacement and returns the result string or FALSE on error. Multibyte character can be used in pattern. The case will be ignored. option has the same meaning as in mb_ereg_replace().
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
See also: mb_regex_encoding(), mb_ereg_replace().
mb_eregi() executes the regular expression match with multibyte support, and returns 1 if matches are found. This function ignore case. If the optional third parameter was specified, the function returns the byte length of matched part, and the array regs will contain the substring of matched string. The functions returns 1 if it matches with the empty string. If no matches found or error happend, FALSE will be returned.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
See also: mb_regex_encoding(), mb_ereg().
mb_get_info() returns internal setting parameter of mbstring.
If type isn't specified or is specified to "all", an array having the elements "internal_encoding", "http_output", "http_input", "func_overload" will be returned.
If type is specified for "http_output", "http_input", "internal_encoding", "func_overload", the specified setting parameter will be returned.
See also mb_internal_encoding(), mb_http_output().
mb_http_input() returns result of HTTP input character encoding detection.
type: Input string specifies input type. "G" for GET, "P" for POST, "C" for COOKIE, "S" for string, "L" for list, "I" for whole list (will return array). If type is omitted, it returns last input type processed.
Return Value: Character encoding name. If mb_http_input() does not process specified HTTP input, it returns FALSE.
See also mb_internal_encoding(), mb_http_output(), mb_detect_order().
If encoding is set, mb_http_output() sets HTTP output character encoding to encoding. Output after this function is converted to encoding. mb_http_output() returns TRUE for success and FALSE for failure.
If encoding is omitted, mb_http_output() returns current HTTP output character encoding.
See also mb_internal_encoding(), mb_http_input(), mb_detect_order().
mb_internal_encoding() sets internal character encoding to encoding If parameter is omitted, it returns current internal encoding.
encoding is used for HTTP input character encoding conversion, HTTP output character encoding conversion and default character encoding for string functions defined by mbstring module.
encoding: Character encoding name
Return Value: If encoding is set,mb_internal_encoding() returns TRUE for success, otherwise returns FALSE. If encoding is omitted, it returns current character encoding name.
See also mb_http_input(), mb_http_output() and mb_detect_order().
mb_language() sets language. If language is omitted, it returns current language as string.
language setting is used for encoding e-mail messages. Valid languages are "Japanese", "ja","English","en" and "uni" (UTF-8). mb_send_mail() uses this setting to encode e-mail.
Language and its setting is ISO-2022-JP/Base64 for Japanese, UTF-8/Base64 for uni, ISO-8859-1/quoted printable for English.
Return Value: If language is set and language is valid, it returns TRUE. Otherwise, it returns FALSE. When language is omitted, it returns language name as string. If no language is set previously, it returns FALSE.
See also mb_send_mail().
mb_list_encodings() returns an array with all supported encodings.
Esempio 1. mb_list_encodings() example
Il precedente esempio visualizzerà:
|
(PHP 4 >= 4.0.6, PHP 5)
mb_output_handler -- Callback function converts character encoding in output buffermb_output_handler() is ob_start() callback function. mb_output_handler() converts characters in output buffer from internal character encoding to HTTP output character encoding.
4.1.0 or later version, this handler adds charset HTTP header when following conditions are met:
Does not set Content-Type by header()
Default MIME type begins with text/
http_output setting is other than pass
contents : Output buffer contents
status : Output buffer status
Return Value: String converted
Nota: If you want to output some binary data such as image from PHP script with PHP 4.3.0 or later, Content-Type: header must be send using header() before any binary data was send to client (e.g. header("Content-Type: image/png")). If Content-Type: header was send, output character encoding conversion will not be performed.
Note that if 'Content-Type: text/*' was send using header(), the sending data is regarded as text, encoding conversion will be performed using character encoding settings.
If you want to output some binary data such as image from PHP script with PHP 4.2.x or earlier, you must set output encoding to "pass" using mb_http_output().
See also ob_start().
mb_parse_str() parses GET/POST/COOKIE data and sets global variables. Since PHP does not provide raw POST/COOKIE data, it can only used for GET data for now. It preses URL encoded data, detects encoding, converts coding to internal encoding and set values to result array or global variables.
encoded_string: URL encoded data.
result: Array contains decoded and character encoding converted values.
Return Value: It returns TRUE for success or FALSE for failure.
See also mb_detect_order(), mb_internal_encoding().
mb_preferred_mime_name() returns MIME charset string for character encoding encoding. It returns charset string.
mb_regex_encoding() returns the character encoding used by multibyte regex functions.
If the optional parameter encoding is specified, it is set to the character encoding for multibyte regex. The default value is the internal character encoding.
See also: mb_internal_encoding(), mb_ereg()
mb_regex_set_options() sets the default options described by options for multibyte regex functions.
Returns the previous options. If options is omitted, it returns the string that describes the current options.
See also mb_split(), mb_ereg() and mb_eregi()
mb_send_mail() sends email. Headers and message are converted and encoded according to mb_language() setting. mb_send_mail() is wrapper function of mail(). See mail() for details.
to is mail addresses send to. Multiple recipients can be specified by putting a comma between each address in to. This parameter is not automatically encoded.
subject is subject of mail.
message is mail message.
additional_headers is inserted at the end of the header. This is typically used to add extra headers. Multiple extra headers are separated with a newline ("\n").
Nota: Content-Type and Content-Transfer-Encoding headers can be redefined as of PHP 5.0.0. In PHP 4, values defined by mb_language() are always used.
additional_parameter is a MTA command line parameter. It is useful when setting the correct Return-Path header when using sendmail.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also mail(), mb_encode_mimeheader(), and mb_language().
mb_split() split multibyte string using regular expression pattern and returns the result as an array.
If optional parameter limit is specified, it will be split in limit elements as maximum.
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
See also: mb_regex_encoding(), mb_ereg().
mb_strcut() returns the portion of str specified by the start and length parameters.
mb_strcut() performs equivalent operation as mb_substr() with different method. If start position is multi-byte character's second byte or larger, it starts from first byte of multi-byte character.
It subtracts string from str that is shorter than length AND character that is not part of multi-byte string or not being middle of shift sequence.
encoding is character encoding. If it is not set, internal character encoding is used.
See also mb_substr(), mb_internal_encoding().
mb_strimwidth() truncates string str to specified width. It returns truncated string.
If trimmarker is set, trimmarker is appended to return value.
start is start position offset. Number of characters from the beginning of string. (First character is 0)
trimmarker is string that is added to the end of string when string is truncated.
encoding is character encoding. If it is omitted, internal encoding is used.
See also mb_strwidth() and mb_internal_encoding().
mb_strlen() returns number of characters in string str having character encoding encoding. A multi-byte character is counted as 1.
encoding is character encoding for str. If encoding is omitted, internal character encoding is used.
See also mb_internal_encoding(), strlen().
mb_strpos() returns the numeric position of the first occurrence of needle in the haystack string. If needle is not found, it returns FALSE.
mb_strpos() performs multi-byte safe strpos() operation based on number of characters. needle position is counted from the beginning of the haystack. First character's position is 0. Second character position is 1, and so on.
If encoding is omitted, internal character encoding is used. mb_strrpos() accepts string for needle where strrpos() accepts only character.
offset is search offset. If it is not specified, 0 is used.
encoding is character encoding name. If it is omitted, internal character encoding is used.
See also mb_strrpos(), mb_internal_encoding(), strpos()
mb_strrpos() returns the numeric position of the last occurrence of needle in the haystack string. If needle is not found, it returns FALSE.
mb_strrpos() performs multi-byte safe strrpos() operation based on number of characters. needle position is counted from the beginning of haystack. First character's position is 0. Second character position is 1.
If encoding is omitted, internal encoding is assumed. mb_strrpos() accepts string for needle where strrpos() accepts only character.
encoding is character encoding. If it is not specified, internal character encoding is used.
See also mb_strpos(), mb_internal_encoding(), strrpos().
mb_strtolower() returns str with all alphabetic characters converted to lowercase.
encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.
For more information about the Unicode properties, please see http://www.unicode.org/unicode/reports/tr21/.
By contrast to strtolower(), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as A-umlaut (Ä).
See also strtolower(), mb_strtoupper() and mb_convert_case().
mb_strtoupper() returns str with all alphabetic characters converted to uppercase.
encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.
By contrast to strtoupper(), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as a-umlaut (ä).
For more information about the Unicode properties, please see http://www.unicode.org/unicode/reports/tr21/.
See also strtoupper(), mb_strtolower() and mb_convert_case().
mb_strwidth() returns width of string str.
Multi-byte character usually twice of width compare to single byte character.
Tabella 1. Characters width
Chars | Width |
---|---|
U+0000 - U+0019 | 0 |
U+0020 - U+1FFF | 1 |
U+2000 - U+FF60 | 2 |
U+FF61 - U+FF9F | 1 |
U+FFA0 - | 2 |
encoding is character encoding. If it is omitted, internal encoding is used.
See also: mb_strimwidth(), mb_internal_encoding().
mb_substitute_character() specifies substitution character when input character encoding is invalid or character code is not exist in output character encoding. Invalid characters may be substituted NULL(no output), string or integer value (Unicode character code value).
This setting affects mb_convert_encoding(), mb_convert_variables(), mb_output_handler(), and mb_send_mail().
substchar : Specify Unicode value as integer or specify as string as follows
"none" : no output
"long" : Output character code value (Example: U+3000,JIS+7E7E)
Return Value: If substchar is set, it returns TRUE for success, otherwise returns FALSE. If substchar is not set, it returns Unicode value or "none"/"long".
mb_substr_count() returns the number of times the needle substring occurs in the haystack string.
encoding specifies the encoding for needle and haystack. If omitted, internal character encoding is used.
See also substr_count(), mb_strpos(), mb_substr().
mb_substr() returns the portion of str specified by the start and length parameters.
mb_substr() performs multi-byte safe substr() operation based on number of characters. Position is counted from the beginning of str. First character's position is 0. Second character position is 1, and so on.
If encoding is omitted, internal encoding is assumed.
encoding is character encoding. If it is omitted, internal character encoding is used.
See also mb_strcut(), mb_internal_encoding().
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
(4.0.5 - 4.2.3 only, PECL)
muscat_close -- Shuts down the muscat session and releases any memory back to PHPAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
[Not back to the system, note!]
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
muscat_setup_net() creates a new muscat session and returns the handle.
muscat_host is the hostname to connect to. port is the port number to connect to.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
size is the amount of memory in bytes to allocate for muscat. muscat_dir is the muscat installation dir e.g. "/usr/local/empower", it defaults to the compile time muscat directory.
Queste funzioni consentono l'accesso ai server di database MySQL. Maggiori informazioni riguardo MySQL possono essere trovate su http://www.mysql.com/.
La documentazione su MySQL può essere trovata su http://dev.mysql.com/doc/.
Al fine di rendere queste funzioni disponibili, si deve compilare PHP con il supporto MySQL.
Usando l'opzione di configurazione --with-mysql[=DIR] si abilita PHP l'accesso ai database MySQL.
In PHP 4, il parametro --with-mysql è abilitato per default. Per disabilitarlo si può utilizzare --without-mysql . Inoltre in PHP 4, se si abilita MySql senza indicare il percorso directory di installazione di MySql, il PHP utilizzerà le librerie incluse nella distribuzione. In Windows non vi sono DLL, è semplicemente compilato nel PHP. Gli utenti che eseguano altre applicazioni basate su MySql (come, ad esempio, auth-mysql), non dovrebbero utilizzare le librerie allegate al PHP, ma, piuttosto, indicare il percorso alla directory di instalalzione di MySQL, come, ad esempio; --with-mysql=/percorso/a/mysql. Questo forzerà PHP ad usare le librerie client installate da MySQL evitando ogni conflitto.
In PHP 5, MySQL non sarà più abilitato per default, e nè la libreria MySQL sarà allegata al PHP. Per maggiori dettagli sul perchè leggere: FAQ.
Questo modulo di interfaccia a MySQL non supporta completamente le tutte le funzioni presenti nelle versioni di MySQL successive alla 4.1.0. Per avere il pieno supporto a queste vedere MySQLi.
Se si desidera installare sia il modulo mysql sia il modulo mysqli utilizzare la stessa libreria client per evitare conflitti.
Avvertimento |
Problemi di blocco e di avvio di PHP possono essere riscontrati quando si carica questa estensione insieme ad estensioni recode. Vedere anche l'estensione recode per maggiori informazioni. |
Nota: Se occorre utilizzare set di caratteri differenti rispetto al latin (il default), si deve installare la libreria esterna (non allegata al PHP) libmysql compilata con il supporto dei set di caratteri.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Opzioni di configurazione di MySQL
Nome | Predefinito | Modificabile in |
---|---|---|
mysql.allow_persistent | "On" | PHP_INI_SYSTEM |
mysql.max_persistent | "-1" | PHP_INI_SYSTEM |
mysql.max_links | "-1" | PHP_INI_SYSTEM |
mysql.default_port | NULL | PHP_INI_ALL |
mysql.default_socket | NULL | PHP_INI_ALL |
mysql.default_host | NULL | PHP_INI_ALL |
mysql.default_user | NULL | PHP_INI_ALL |
mysql.default_password | NULL | PHP_INI_ALL |
mysql.connect_timeout | "0" | PHP_INI_SYSTEM |
Breve descrizione dei parametri di configurazione.
Determina se consentire le connessioni persistenti a MySQL.
Il numero massimo di connessioni persistenti MySQL per processo.
Il numero massimo di connessioni MySQL per processo, incluse le connessioni persistenti.
Il numero di porta TCP predefinito da usare per connettersi ad un server di database se nessuna altra porta viene specificata. Se nessun valore predefinito e specificato, la porta sarà ottenuta dalla variabile d'ambiente MYSQL_TCP_PORT, dalla voce mysql-tcp in /etc/services o dalla costante MYSQL_PORT in fase di compilazione, in questo ordine. Win32 userà solo la costante MYSQL_PORT.
Il nome del socket predefinito da usare per connettersi ad un server di database locale se nessun altro nome di socket viene specificato.
L'host di default del server da usare per connettersi al server di database se nessun altro host viene specificato. Non si applica in safe mode.
Il nome utente predefinito da usare per connettersi al server di database se nessun altro nome viene specificato. Non si applica in safe mode.
La password predefinita da usare per connettrsi al server di database se nessuna altra password viene specificata. Non si appplica in safe mode.
Timeout di connessione in secondi. Per Linux questo timeout è usato anche per attendere la prima risposta dal server.
Ci sono due tipi di risorsa usati nel modulo MySQL. Il primo è l'identificativo di connessione per una connessione ad un database, del secondo tipo sono le risorse che contengono i risultati di una query.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Fin dal PHP 4.3.0 è possibile specificare flag addizionali per il client per le funzioni mysql_connect() e mysql_pconnect(). Sono definite le seguenti costanti:
Tabella 2. Costanti client MySQL
Costante | Descrizione |
---|---|
MYSQL_CLIENT_COMPRESS | Usa la compressione del protocollo |
MYSQL_CLIENT_IGNORE_SPACE | Consente lo spazio dopo i nomi delle funzioni |
MYSQL_CLIENT_INTERACTIVE | Lascia trascorrere interactive_timeout secondi (anziché wait_timeout) di inattività prima di chiudere la connessione |
La funzione mysql_fetch_array() usa una costante per i diversi tipi di array risultato. Sono definite le seguenti costanti:
Tabella 3. Costanti caricamento MySQL
Costante | Descrizione |
---|---|
MYSQL_ASSOC | Le colonne sono restituite in un array avente il nome del campo come indice dell'array |
MYSQL_BOTH | Le colonne sono restituite in un array avente sia un indice numerico sia un indice costituito dal nome del campo |
MYSQL_NUM | Le colonne sono restituite in un array avente un indice numerico per i campi. Questo indice inizia da 0, il primo campo nel risultato |
Questo esempio mostra come connettersi, eseguire una query, stampare le righe risultanti e disconnettersi dal database MySQL.
Esempio 1. Esempio dell'estensione MySQL
|
(PHP 3, PHP 4, PHP 5)
mysql_affected_rows -- Ottiene il numero di righe coinvolte nelle precedenti operazioni MySQLmysql_affected_rows() restituisce il numero di righe coinvolte nell'ultima query INSERT, UPDATE o DELETE associata a identificativo_connessione. Se l'identificativo di connessione non è specificato, viene considerata l'ultima connessione aperta con mysql_connect().
Nota: Se sono usate le transazioni, è necessario richiamare mysql_affected_rows() dopo le query INSERT, UPDATE, o DELETE e non dopo il commit.
Se l'ultima query era una query DELETE senza clausola WHERE, tuti i record saranno cancellati dalla tabella ma questa funzione restituirà zero.
Nota: Usando UPDATE, MySQL non aggiornerà le colonne nelle quali il nuovo valore è uguale al vecchio valore. Questo crea la possibilità che mysql_affected_rows() può non uguagliare realmente il numero di righe corrispondenti ma solo il numero di righe effettivamente coinvolte dalla query.
mysql_affected_rows() non funziona con l'istruzione SELECT ma solo con le istruzioni che modificano i record. Per ricavare il numero di righe restituite da SELECT, usare mysql_num_rows().
Se l'ultima query fallisce, questa funzione restituisce -1.
Esempio 1. Query di eliminazione
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Esempio 2. Query di aggiornamento
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_num_rows(), mysql_info().
mysql_change_user() cambia l'utente dell'attuale connessione attiva o della connessione specificata dal parametro opzionale identificativo_connessione. Se un database is specificato, questo sarà il database corrente dopo che l'utente è stato cambiato. Se l'autorizzazione del nuovo utente e password falllisce, l'attuale utente connesso rimane attivo. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Questa funzione è stata introdotta nel PHP 3.0.13 e richiede MySQL 3.23.3 o successivo. Non è disponibile nel PHP 4.
mysql_client_encoding() restituisce il nome del set di caratteri predefinito per l'attuale connessione.
Esempio 1. Esempio di mysql_client_encoding()
L'esempio riportato sopra produce il seguente output:
|
Vedere anche: mysql_real_escape_string()
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
mysql_close() chiude la connessione al server MySQL associata all'identificativo di connessione specificato. Se identificativo_connessione non è specificato, viene usata l'ultima connessione aperta.
L'uso di mysql_close() non è normalmente necessario, dal momento che le connessioni non persistenti sono chiuse automaticamente alla fine dell'esecuzione dello script. Vedere anche freeing resources.
Nota: mysql_close() non chiude le connessioni persistenti create da mysql_pconnect().
Vedere anche: mysql_connect(), e mysql_pconnect().
Restituisce un identificativo di connessione MySQL in caso di successo oppure FALSE in caso di fallimento.
mysql_connect() stabilice una connessione ad un server MySQL. I seguenti valore predefiniti sono assunti per i parametri opzionali mancanti: server = 'localhost:3306', nome_utente = nome dell'utente proprietario del processo server e password = password vuota.
Il parametro server può anche includere un numero di porta. Es. "hostname:porta" o un percorso ad un socket es. ":/percorso/al/socket" per il localhost.
Nota: il supporto per ":porta" è stato aggiunto nel PHP 3.0B4.
Il supporto per ":/percorso/al/socket" è stato aggiunto nel PHP 3.0.10.
Si può eliminare il messaggio di errore nel caso di fallimento aggiungendo il prefisso @ al un nome della funzione.
Se si fa una seconda chiamata a mysql_connect() con gli stessi argomenti, nessuna nuova connessione sarà stabilita, ma sarà restituito l'identificativo della connessione già aperta. Il paramentro nuova_connessione modifica questo comportamento e fa sì che mysql_connect() apra sempre una nuova connessione, anche se mysql_connect() era stata chiamata prima con gli stessi parametri. il parametro client_flags può essere combinato con le costanti MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE o MYSQL_CLIENT_INTERACTIVE.
Nota: Il paramentro nuova_connessione è stato indrodotto dal PHP 4.2.0
Il parametro client_flags è stato introdotto dal PHP 4.3.0
La connessione al server sarà chiusa prima della fine dell'esecuzione dello script, a meno che questa non sia precedentemente chiusa esplicitamente richiamando mysql_close().
Vedere anche mysql_pconnect() e mysql_close().
mysql_create_db() tenta di creare un nuovo database nel server associato all'identificativo di conmnessione specificato.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. Esempio creazione database MySQL
|
Per motivi di compatibilità con il passato, anche mysql_createdb() può essere usata. Questo è comunque sconsigliato.
Nota: La funzione mysql_create_db() è sconsigliata. Al suo posto è preferibile usare mysql_query() per inviare un'istruzione SQL CREATE DATABASE.
Vedere anche: mysql_drop_db(), mysql_query().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
mysql_data_seek() muove il puntatore di riga interno del risultato MySQL associato all'identificativo specificato per puntare ad un determinato numero di riga. La successiva chiamata a mysql_fetch_row() dovrebbe restituire questa riga.
numero_riga inizia da 0. numero_riga dovrebbe essere un valore nell'intervallo che va da 0 a mysql_num_rows - 1.
Nota: La funzione mysql_data_seek() può essere usata solo insieme a mysql_query(), non con mysql_unbuffered_query().
Esempio 1. Esempio seek dati MySQL
|
Vedere anche: mysql_query(), mysql_num_rows().
mysql_db_name() accetta come primo paramentro il puntatore al risultato dalla chiamata a mysql_list_dbs(). Il parametro riga è un indice compreso nell'intervallo del risultato.
Se intercorre un errore, viene restituito FALSE. Usare mysql_errno() e mysql_error() per determinare la natura dell'errore.
Per motivi di compatibilità con il passato, anche mysql_dbname() è è accettata. Questo comunque è sconsigliato.
Restituisce una risorsa risultato della query se è stato possibile eseguire quest'ultima, oppure FALSE in caso d'errore. La funzione restituisce TRUE/FALSE anche per le query INSERT/UPDATE/DELETE per indicarne il successo/fallimento.
mysql_db_query() seleziona un database ed esegue una query su di esso. Se l'identificativo di connessione opzionale non è specificato, la funzione proverà a cercare una connessione aperta al server MySQL e se tale connessione non viene trovata cercherà di crearne una come se mysql_connect() fosse chiamata senza argomenti.
Si informa che questa funzione NON commuta al database al quale si era connessi prima. in altre parole, non si può usare questa funzione per eseguire temporaneamente una query sql su un altro database, si deve commutare manualmente. Gli utenti sono fortemente incoraggiati ad usare la sintassi database.tabella nelle loro query sql in questa funzione.
Vedere anche mysql_connect() e mysql_query().
Nota: Questa funzione è stata sconsigliata a partire dal PHP 4.0.6. Non usare questa funzione.Usare invece mysql_select_db() e mysql_query().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
mysql_drop_db() tenta di eliminare (cancellare) un intero database dal server associato all'identificativo di connessione specificato.
Per motivi di compatibilità con il passato, anche mysql_dropdb() può essere usato. Questa è comunque sconsigliato.
Nota: La funzione mysql_drop_db() è sconsigliata. Al suo posto è preferibile usare mysql_query() per inviare una istruzione SQL DROP DATABASE.
Vedere anche: mysql_create_db(), mysql_query().
(PHP 3, PHP 4, PHP 5)
mysql_errno -- Restituisce il valore numerico del messaggio di errore della precedente operazione MySQLRestituisce il numero di errore dall'ultima funzione MySQL, oppure 0 (zero) se nessun errore è intercorso.
Gli errori ritornano dal database MySQL senza visualizzare i messaggi di avvertimento. Usando invece mysql_errno() si recupera il codice di errore. Notare che questa funzione restituisce solo il codice errore della più recente funzione MySQL eseguita (ad esclusione di mysql_error() e mysql_errno()), quindi se la si vuole usare, assicurarsi di controllare il valore prima di richiamare un'altra funzione MySQL.
Esempio 1. Esempio di mysql_errno
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Nota: Se l'argomento opzionale è specificato la connessione indicata viene usata per recuperare il codice d'erroe. Altrimenti viene usata l'ultima connessione aperta.
Vedere anche: mysql_error()
(PHP 3, PHP 4, PHP 5)
mysql_error -- Restituisce il testo del messagio di errore della precedente operazione MySQLRestituisce il testo dell'errore dall'ultima funzione MySQL, oppure '' (la stringa vuota) se nessun errore intercorre.
Gli errori ritornano dal database MySQL senza visualizzare i messaggi di avvertimento. Si usa invece mysql_error() per recuperare il testo dell'errore. Notare che questa funzione restituisce solo il testo dell'errore della più recente funzione MySQL eseguita (ad esclusione di mysql_error() e mysql_errno()), quindi se la si vuole usare, assicurarsi di controllare il valore prima di richiamare un'altra funzione MySQL.
Esempio 1. mysql_error Example
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Nota: Se l'argomento opzionale è specificato la connessione indicata viene usata per recuperare il codice d'erroe. Altrimenti viene usata l'ultima connessione aperta.
Vedere anche: mysql_errno()
(PHP 4 >= 4.0.3, PHP 5)
mysql_escape_string -- Aggiunge le sequenze di escape in una stringa per l'uso in mysql_query.Questa funzione aggiunge le sequenze di escape a stringa_senza_escape, in modo che sia sicuro usarla in mysql_query().
Nota: mysql_escape_string() non aggiunge le sequenze di escape a % ed a _.
Questa funzione è identica a mysql_real_escape_string() eccetto che mysql_real_escape_string() accetta un identificativo di connessione ed aggiunge le sequenze di escape alla stringa in base al set di caratteri corrente. mysql_escape_string() non accetta come argomento un identificativo di connessione e non rispetta le impostazioni del corrente set di caratteri.
Esempio 1. Esempio di mysql_escape_string()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_real_escape_string(), addslashes(), e la direttiva magic_quotes_gpc .
(PHP 3, PHP 4, PHP 5)
mysql_fetch_array -- Carica una riga del risultato come un array associativo, un array numerico o entrambi.Restituisce un array che corrisponde alla riga caricata o FALSE se non ci sono più righe.
mysql_fetch_array() è una versione estesa di mysql_fetch_row(). Oltre a memorizzare i dati del risultato in array con indice numerico, questa li memorizza anche con indici associativi usando i nomi dei campi come chiavi.
Se due o più colonne del risultato hanno gli stessi nomi di campo, l'ultima colonna avrà la precedenza. Per accedere alle altre colonne con lo stesso nome, si deve usare l'indice numerico della colonna o farne un alias. Per le colonne-alias, non si può accedere al contenuto con il nome della colonna originale (in questo esempio si usa 'campo').
Una cosa importante da notare è che l'uso di mysql_fetch_array() non è significativamente più lento dell'uso di mysql_fetch_row(); questo fornisce un significativo valore aggiunto.
Il secondo argomento opzionale tipo_risultato in mysql_fetch_array() è una costante e può assumere i seguenti valori: MYSQL_ASSOC, MYSQL_NUM e MYSQL_BOTH. Questa caratteristica è stata aggiunta nel PHP 3.0.7. MYSQL_BOTH è il valore predefinito per questo argomento.
Usando MYSQL_BOTH, si ottiene un array con entrambe gli indici (associativo e numerico). Usando MYSQL_ASSOC, si ottengono solo gli indici associativi (stesso funzionamento di mysql_fetch_assoc()), usando MYSQL_NUM, si ottengono solo gli indici numerici (stesso funzionamento di mysql_fetch_row()).
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Esempio 2. mysql_fetch_array() con MYSQL_NUM
|
Esempio 3. mysql_fetch_array() con MYSQL_ASSOC
|
Esempio 4. mysql_fetch_array() con MYSQL_BOTH
|
Per maggiori dettagli, vedere anche mysql_fetch_row() e mysql_fetch_assoc().
Restituisce un array associativo che corrisponde alla riga caricata o FALSE se non ci sono più righe.
mysql_fetch_assoc() è equivalente alla chiamata di mysql_fetch_array() con MYSQL_ASSOC come secondo parametro opzionale. Questa restituisce solo un array associativo. Questo è il modo incui mysql_fetch_array() funzionava originalmente. Se è necessario l'indice numerico al posto di quello associativo, usare mysql_fetch_array().
Se due o più colonne del risultato hanno gli stessi nomi di campo, l'ultima colonna avrà la precedenza. Per accedere alle altre colonne con lo stesso nome, si deve accedere al risultato con l'indice numerico usando mysql_fetch_row() oppure aggiunger degli alias. Vedere l'esempio nella descrizione di mysql_fetch_array() per quanto concerne gli alias.
Una cosa importante da notare è che l'uso di mysql_fetch_assoc() non è significativamente più lento dell'uso di mysql_fetch_row(); questo fornisce un significativo valore aggiunto.
Esempio 1. Un esteso esempio di mysql_fetch_assoc()
|
Vedere anche mysql_fetch_row(), mysql_fetch_array(), mysql_query() e mysql_error().
(PHP 3, PHP 4, PHP 5)
mysql_fetch_field -- Ottiene informazioni sulla colonna da un risultato e le restituisce come oggettoRestituisce un oggetto contenente le informazioni di un campo.
mysql_fetch_field() può essere usata al fine di ottenere informazioni circa i campi di un determinato risultato di una query. Se l'indice del campo non è specificato, il successivo campo non ancora recuperato da mysql_fetch_field() viene considerato.
Le proprietà dell'oggetto sono:
name - nome della colonna
table - nome della tabella a cui appartiene la colonna
max_length - massima lunghezza della colonna
not_null - 1 se la colonna non può essere NULL
primary_key - 1 se la colonna è una chiave primaria
unique_key - 1 se la colonna è una chiave unica
multiple_key - 1 se la colonna è una chiave non-unica
numeric - 1 se la colonna è numerica
blob - 1 se la colonna è un BLOB
type - il tipo della colonna
unsigned - 1 se la colonna è senza segno
zerofill - 1 se la colonna è completata da zeri
Esempio 1. mysql_fetch_field()
|
Vedere anche mysql_field_seek().
Restituisce un array che corrisponde alle lunghezze di ogni campo nell'ultima riga caricata da mysql_fetch_row() oppure FALSE in caso di errore.
mysql_fetch_lengths() memorizza le lunghezze di ogni colonna dell'ultima riga restituita da mysql_fetch_row(), mysql_fetch_array() e mysql_fetch_object() in un array, iniziando con un indice pari a 0.
Vedere anche: mysql_fetch_row().
Restituisce un oggetto con proprietà che corrispondono alla riga caricata oppure FALSE se non ci sono più righe.
mysql_fetch_object() è simile a mysql_fetch_array(), con una differenza - viene restituito un oggetto invece che un array. Indirettamente, questo significa che si ha solo accesso ai dati attraverso i nomi dei campi e non attraverso il loro indice (i mumeri sono nomi di proprietà illeciti).
<?php /* questo è valido */ echo $riga->campo; /* questo non è valido */ echo $riga->0; ?> |
In termini di velocità, la funzione è identica a mysql_fetch_array() e quasi veloce come mysql_fetch_row() (la differenza è insignificante).
Esempio 1. Esempio di mysql_fetch_object()
|
Vedere anche: mysql_fetch_array() e mysql_fetch_row().
Restituisce un array che corrisponde ad una riga caricata oppure FALSE se non ci sono più righe.
mysql_fetch_row() carica una riga di dati dal risultato associato all'identificativo specificato. La riga è restituita com un array. Ogni colonna del risultato è memorizzata in un indice dell'array, partendo dall'indice 0.
La susseguente chiamata a mysql_fetch_row() restituisce la successiva riga nell'intervallo del risultato oppure FALSE se non ci sono più righe.
Vedere anche: mysql_fetch_array(), mysql_fetch_object(), mysql_data_seek(), mysql_fetch_lengths() e mysql_result().
(PHP 3, PHP 4, PHP 5)
mysql_field_flags -- Ottine i flag associati al campo specificato di un risultatomysql_field_flags() restituisce i flag del campo specificato. I flag sono restituiti come singole parole per flag separate da un singolo spazio, in modo che sia possibile suddividere il valore restituito usando explode().
I seguenti flag sono restituiti, se la versione di MySQL è abbastanza aggiornata da supportarli: "not_null", "primary_key", "unique_key", "multiple_key", "blob", "unsigned", "zerofill", "binary", "enum", "auto_increment", "timestamp".
Per motivi di compatibilità con il passato, anche mysql_fieldflags() può essere usata. Questo comunque è sconsigliato.
mysql_field_len() restituisce la lunghezza del campo specificato.
Per motivi di compatibilità con il passato, anche mysql_fieldlen() può essere usata. Questo comunque è sconsigliato.
mysql_field_name() restituisce il nome del campo specificato dall'indice. risultato deve essere un identificativo di risultato valido e indice_campo è lo spiazzamento numerico del campo.
Nota: indice_campo inizia da 0.
Es. L'indice del terzo campo è in realtà 2, l'indice del quarto campo è 3 e così via.
Esempio 1. Esempio di mysql_field_name()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Per motivi di compatibilità con il passato, anche mysql_fieldname() può essere usata. Questo comunque è sconsigliato.
(PHP 3, PHP 4, PHP 5)
mysql_field_seek -- Imposta il puntatore al risultato ad un determinato indice di campoEsegue il seek ad uno specifico indice di campo. Se la successiva chiamata a mysql_fetch_field() non include un indice di campo, quello specificato in mysql_field_seek() viene restituito.
Vedere anche: mysql_fetch_field().
(PHP 3, PHP 4, PHP 5)
mysql_field_table -- Ottiene il nome della tabella in cui si trova il campo specificatoOttiene il nome della tabella in cui si trova il campo specificato.
Per motivi di compatibilità con il passato, anche mysql_fieldtable() può essere usata. Questo comunque è sconsigliato.
mysql_field_type() è simile alla funzione mysql_field_name(). Gli argomenti sono identici, ma viene restituito il tipo del campo. Il tipo del campo sarà uno dei seguenti: "int", "real", "string", "blob" ed altri come dettagliati nella Documentazione di MySQL.
Esempio 1. Tipi di campo MySQL
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Per motivi di compatibilità con il passato, anche mysql_fieldtype() può essere usata. Questo comunque è sconsigliato.
mysql_free_result() libera utuuta la memoria associata all'identificativo del risultato risultato.
mysql_free_result() deve essere richiamata solo se si è preoccupati sulla quantità di memoria usata dalle query che restituiscono dei grandi risultati. Tutta la memoria associata al risultato è automaticamente liberata al termine dell'esecuzione dello script.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Per motivi di compatibilità con il passato, anche mysql_freeresult() può essere usata. Questo comunque è sconsigliato.
mysql_get_client_info() restituisce una stringa che rappresenta la versione della libraria client.
Vedere anche: mysql_get_host_info(), mysql_get_proto_info() e mysql_get_server_info().
mysql_get_host_info() restituisce una stringa che descrive il tipo di connessione in uso per identificativo_connessione, includendo il nome dell'host del server. Se identificativo_connessione è omesso, sarà usata l'ultima connessione aperta.
Esempio 1. Esempio di mysql_get_host_info
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_get_client_info(), mysql_get_proto_info() e mysql_get_server_info().
mysql_get_proto_info() restituisce la versione del protocollo usata dalla connessione identificativo_connessione. Se identificativo_connessione è omesso, sarà usata l'ultima connessione aperta.
Esempio 1. Esempio di mysql_get_proto_info
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_get_client_info(), mysql_get_host_info() e mysql_get_server_info().
mysql_get_server_info() restituisce la versione del server usato dalla connessione identificativo_connessione. Se identificativo_connessione è omesso, sarà usata l'ultima connessione aperta.
Esempio 1. Esempio di mysql_get_server_info
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_get_client_info(), mysql_get_host_info() e mysql_get_proto_info().
mysql_info() restituisce informazioni dettagliate relative all'ultima query usando lo specifico identificativo_connessione. Se identificativo_connessione non è specificato, viene considerata l'ultima connessione aperta.
mysql_info() restituisce una stringa per tutte le istruzioni elencate di seguito. Per tutte le altre restituisce FALSE. Il formato della stringa dipende dall'istruzione data.
Esempio 1. Istruzioni MySQL significative
|
Nota: mysql_info() restituisce un valore non FALSE per le istruzioni INSERT ... VALUES solo se nell'istruzione sono specificate liste di valori multipli.
Vedere anche: mysql_affected_rows()
(PHP 3, PHP 4, PHP 5)
mysql_insert_id -- Ottiene l'identificativo generato dalla precedente operazione INSERTmysql_insert_id() restituisce l'identificativo generato per una colonna AUTO_INCREMENT dal precedente query INSERT usando lo specifico identificativo_connessione. Se identificativo_connessione non è specificato, viene considerata l'ultima connessione aperta.
mysql_insert_id() restituisce 0 se la precedente query non ha generato un valore AUTO_INCREMENT. Se è necessario salvare il valore per usarlo in seguito, assicurarsi di richiamare mysql_insert_id() immediatamente dopo la query che ha generato il valore.
Nota: Il valore della funzione SQL LAST_INSERT_ID() di MySQL contiene sempre il più recente valore AUTO_INCREMENT generato e non è azzerato dalle query.
Avvertimento |
mysql_insert_id() converte il tipo restituito dalla funzione nativa dell'API C di MySQL mysql_insert_id() al tipo long (chiamata int nel PHP). Se la colonna AUTO_INCREMENT è del tipo BIGINT, il valore restituito da mysql_insert_id() sarà inesatto. In questo caso si usi la funzione SQL di MySQL LAST_INSERT_ID() in una query SQL. |
Esempio 1. Esempio di mysql_insert_id
|
Vedere anche: mysql_query().
mysql_list_dbs() restituirà un risultato puntatore contenete i database resi disponibili dal demone mysql. Usare la funzione mysql_tablename() per esplorare questo risultato puntatore o qualsiasi funzione per i risultati delle tabelle, come mysql_fetch_array().
Esempio 1. Esempio di mysql_list_dbs()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Nota: Il codice riportato sopra dovrebbe funzionare facilmente con mysql_fetch_row() o altre funzioni simili.
Per motivi di compatibilità con il passato, anche mysql_listdbs() può essere usata. Questo comunque è sconsigliato.
Vedere anche mysql_db_name().
mysql_list_fields() recupera le informazioni relative ad una data tabella. Gli argomenti sono il nome del database ed il nome della tabella. Viene restituito un risultato puntatore che può essere usato con mysql_field_flags(), mysql_field_len(), mysql_field_name() e mysql_field_type().
Esempio 1. Esempio di mysql_list_fields()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Per motivi di compatibilità con il passato, anche mysql_listfields() può essere usata. Questo comunque è sconsigliato.
mysql_list_processes() restituisce un risultato puntatore che descrive i thread attuali del server.
Esempio 1. Esempio di mysql_list_processes()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_thread_id()
mysql_list_tables() accetta un nome di database e restituisce un risultato puntatore in modo molto simile alla funzione mysql_query(). Usare la funzione mysql_tablename() per esplorare questo risultato puntatore o qualsiasi funzione per i risultati delle tabelle, come mysql_fetch_array().
Il parametro database è il nome del database da cui recuperare la lista di tabelle. in caso di errore, mysql_list_tables() restituisce FALSE.
Per motivi di compatibilità con il passato, anche mysql_listtables() può essere usata. Questo comunque è sconsigliato.
Esempio 1. mysql_list_tables() example
|
Vedere anche: mysql_list_dbs() e mysql_tablename().
mysql_num_fields() restituisce il numero di campi in un risultato.
Vedere anche: mysql_select_db(), mysql_query(), mysql_fetch_field() e mysql_num_rows().
Per motivi di compatibilità con il passato, anche mysql_numfields() può essere usata. Questo comunque è sconsigliato.
mysql_num_rows() restituisce il numero di righe in un risultato. Questo comando è valido solo per le istruzioni SELECT. Per recuperare il numero di righe coinvolte dalle query INSERT, UPDATE o DELETE, usare mysql_affected_rows().
Esempio 1. Esempio di mysql_num_rows()
|
Nota: Se si usa mysql_unbuffered_query(), mysql_num_rows() non restituirà il valore corretto finché non sono recuperate tutte le righe del risultato.
Vedere anche: mysql_affected_rows(), mysql_connect(), mysql_data_seek(), mysql_select_db() e mysql_query().
Per motivi di compatibilità con il passato, anche mysql_numrows() può essere usata. Questo comunque è sconsigliato.
Restituisce un identificativo di connessione MySQL valido in caso di successo oppure FALSE in caso di errore.
mysql_pconnect() stabilisce una connessione ad un server MySQL. I seguenti valori predefiniti sono usati per i parametri opzionali mancanti: server = 'localhost:3306', nome_utente = nome dell'utente prprietario del processo server e password = password vuota. Il parametro flag_client può essere una combinatione delle costanti MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE o MYSQL_CLIENT_INTERACTIVE.
Il parametro server può includere una numero di porta. Es. "hostname:porta" o un percorso ad un socket es. ":/percorso/a/socket" per il localhost.
Nota: Il supporto per ":porta" è stato aggiunto nel PHP 3.0B4.
Il supportp per ":/percorso/a/socket" è stato aggiunto nel PHP 3.0.10.
mysql_pconnect() agisce in modo molto simile a mysql_connect() con due differenze principali.
Primo, quando si connette, la funzione tenta innanzitutto di trovare una connessione (persistente) già aperta avente gli stessi host, username e password. Se viene trovata una connessione, viene restituito un identificativo a questa anziché aprirne una nuova.
Secondo, la connessione al server SQL non sarà chiusa quando l'esecuzione dello script termina. La connessione rimane invece aperta per usi futuri (mysql_close() non chiuderà le connessioni stabilite da mysql_pconnect()).
Il parametro opzionale flag_client è diventato disponibile nel PHP 4.3.0.
Questo tipo di link è perciò chiamato 'persistente'.
Nota: Notare che questo tipo di connessione funziona solo se si usa PHP come modulo. Vedere la sezione Persistent Database Connections per maggiori informazioni.
Avvertimento |
L'uso di connessioni persistenti può richiedere un po' di messa a punto delle configurazioni di Apache e MySQL per assicurarsi di non eccedere il numero di connessioni consentite da MySQL. |
(PHP 4 >= 4.3.0, PHP 5)
mysql_ping -- Esegue un ping su una connessione al server o riconnette se non non esiste la connessionemysql_ping() controlla se una connessione al server funziona o meno. Se questa è caduta, viene tentata una riconnessione automatica. Questa funzione può essere usata dagli script che rimangono inattivi per un lungo periodo per controllare se il server ha chiuso la connessione o meno e riconnettersi se necessario. mysql_ping() restituisce TRUE se la connessione al server è funzionante, altrimenti FALSE.
Vedere anche: mysql_thread_id() e mysql_list_processes().
mysql_query() invia una query al database attualmente attivo sul server associato all'identificativo di conmnessione specificato. Se identificativo_connessione non è specificato, viene considerata l'ultima connessione aperta. Se nessuna connessione è aperta, la funzione prova a stabilire una connessione come se mysql_connect() fosse richiamata senza argomenti ed usa questa.
Il paramentro opzionale modo_risultato può essere MYSQL_USE_RESULT e MYSQL_STORE_RESULT. Il valore predefinito MYSQL_STORE_RESULT, così il risultato è bufferato. Vedere anche mysql_unbuffered_query() per la controparte di questo comportamento.
Nota: La stringa della query non dovrebbe terminare con un punto e virgola.
Solo per le istruzioni SELECT, SHOW, EXPLAIN o DESCRIBE mysql_query() restituisce un identificativo di risorsa o FALSE se la query non è stata eseguita correttamente. Per altri tipi di istruzioni SQL, mysql_query() restituisce TRUE in caso di successo e FALSE in caso di errore. Un valore restituito diverso da FALSE indica che la query era lecita ed è stata eseguita dal server. Questo non indica niente riguardo il numero di righe coinvolte o restituite. è assolutamente possibile che una query abbia successo ma che non coinvolga o restituisca nessuna riga.
La seguente query non è valida sintatticamente, quindi mysql_query() fallisce e restituisce FALSE:
La seguente query non è semanticamente valida se mia_colonna non è una colonna della tabella mia_tabella, quindi mysql_query() fallisce e retituisce FALSE:
mysql_query() fallisce e restituisce FALSE anche se non si hanno i permessi per accedere alle tabelle cui la query fa riferimento.
Assumendo che la query abbia succeesso, si può richiamare mysql_num_rows() per scoprire quante righe sono state restituite da un'istruzione SELECT o mysql_affected_rows() per scoprire quante righe sono state coinvolte da un'istruzione DELETE, INSERT, REPLACE o UPDATE.
Solo per le istruzioni SELECT, SHOW, DESCRIBE o EXPLAIN, mysql_query() restituisce un nuovo identificativo di risultato che si può passare a mysql_fetch_array() e ad altre funzioni che si occupano dei risultati delle tabelle. Quando si conclude il trattamento del risultato, si possono liberare le risorse associate ad esso richiamando mysql_free_result(). Comunqe la memoria sarà liberata automaticamente Al termnine dell'esecuzione dello script.
Vedere anche: mysql_num_rows(), mysql_affected_rows(), mysql_unbuffered_query(), mysql_free_result(), mysql_fetch_array(), mysql_fetch_row(), mysql_fetch_assoc(), mysql_result(), mysql_select_db() e mysql_connect().
(PHP 4 >= 4.3.0, PHP 5)
mysql_real_escape_string -- Aggiunge le sequenze di escape ai caratteri speciali in una stringa per l'uso in una istruzione SQL, tenendo conto dell'attuale set di caratteri della connessione.Questa funzione aggiunge le sequenza di escape ai caratteri speciali in stringa_senza_escape, tenendo conto dell'attuale set di caratteri della connessione in modo che sia sicuro usarla in mysql_query().
Nota: mysql_real_escape_string() non aggiunge le sequenze di escape a % ed a _.
Esempio 1. Esempio di mysql_real_escape_string()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche : mysql_escape_string() e mysql_character_set_name().
mysql_result() restituisce i contenuti di una cella da un risultato MySQL. L'argomento campo può essere l'indice o il nome del campo oppure il nome della tabella ed il nome del campo separati da un punto (nome_tabella.nome_campo). Se il nome della colonna ha un alias ('select foo as bar from...'), usare l'alias al posto del nome della colonna.
Quando si lavora con un risultato di grandi dimensioni, si dovrebbero considerare l'uso delle funzioni che caricano l'intera riga (specificate di seguito). Poiché queste funzioni restituiscono i contenuti di celle multiple in una chiamata a funzione, sono MOLTO più veloci di mysql_result(). Notare anche che specificare un indice numerico per l'argomento campo è molto più veloce che specificare un argomento del tipo nome_di_campo o nome_tabella.nome_campo.
Le chiamate a mysql_result() non dovrebbero esserse mescolate con chiamate ad altre funzioni che hanno a che fare con i risultati.
Alternative raccomandate per alte prestazioni: mysql_fetch_row(), mysql_fetch_array() e mysql_fetch_object().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
mysql_select_db() imposta il database attualmente attivo sul server associato all'identificativo di connessione specificato. Se nessin identificativo di connesione è specificato, viene considerata l'ultima connessione aperta. Se nessuna connessione è aperta, la funzione proverà a stabilire una connessione come se mysql_connect() fosse richiamata senza argomenti ed userà questa.
Ogni chiamata successiva a mysql_query() sarà fatta sul database attivo.
Vedere anche: mysql_connect(), mysql_pconnect() e mysql_query().
Per motivi di compatibilità con il passato, anche mysql_selectdb() può essere usata. Questo comunque è sconsigliato.
mysql_stat() restituisce l'attuale stato del server.
Nota: mysql_stat() attualmente restituisce solo le seguenti informazioni: uptime, thread, query, tabelle aperte, tabelle svuotate e query al secondo. Per una lista completa delle altre variabili di stato si usi il comando SQL SHOW STATUS.
Esempio 1. mysql_stat() example
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
mysql_tablename() prende il puntatore risultato dalla funzione mysql_list_tables() come un indice intero e restituisce il nome di una tabella. La funzione mysql_num_rows() può essere usata per determinare il numero di tabelle nel risultato puntatore. Usare la funzione mysql_tablename() per esplorare questo risultato puntatore o qualsiasi funzione per i risultati delle tabelle, come mysql_fetch_array().
Vedere anche: mysql_list_tables().
mysql_thread_id() restituisce l'attuale thread ID. Se La connessione è persa a ci si riconnette con mysql_ping(), il thread ID cambia. Questo significa che non si dovrebbe ottenere il thread ID e memorizzarlo per impieghi successivi. Si dovrebbe rilevare il thread ID quando è necessario.
Esempio 1. Esempio di mysql_thread_id()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_ping() e mysql_list_processes().
(PHP 4 >= 4.0.6, PHP 5)
mysql_unbuffered_query -- Invia una query SQL a MySQL senza caricare e bufferare le righe risultantimysql_unbuffered_query() invia una query SQL query a MySQL senza caricare e bufferare le righe risultanti automaticamente come fa mysql_query(). Da una parte, questo risparmia un considerevole quantità di memoria con le query SQL che producono risulati di grandi dimensioni. Dall'altra parte, si può iniziare l'elaborazione dei risultati immediatamente dopo che la prima riga è stata recuperata: non si deve attendere finché la query SQL sia completamente eseguita. Quando si usano diverse connessioni a database, si deve specificare il paramentro opzionale identificativo_connessione.
Il parametro opzionale modo_risultato può essere MYSQL_USE_RESULT e MYSQL_STORE_RESULT. Il valore predefinito è MYSQL_USE_RESULT, quindi il risultato non è bufferato. Vedere anche mysql_query() per la controparte di questo comportamento.
Nota: I benefici di mysql_unbuffered_query() hanno un costo: non si può usare mysql_num_rows() su un risultato restituito da mysql_unbuffered_query(). Inoltre si debbono caricare tutte le righe risultanti da una query SQL non bufferata prima di poter inviare una nuova query SQL a MySQL.
vedere anche: mysql_query().
PDO_MYSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to MySQL 3.x and 4.x databases.
PDO_MYSQL will take advantage of native prepared statement support present in MySQL 4.1 and higher. If you're using an older version of the mysql client libraries, PDO will emulate them for you.
Avvertimento |
Beware: MySQL tables do not support transactions by default. When writing transactional database code, MySQL will pretend that a transaction was initiated successfully, even when no transactional support is present. In addition, any DDL queries issued will implicitly commit any pending transactions. |
The constants below are defined by this driver, and will only be available when the extension has been either compiled into PHP or dynamically loaded at runtime. In addition, these driver-specific constants should only be used if you are using this driver. Using mysql-specific attributes with the postgres driver may result in unexpected behaviour. PDO::getAttribute() may be used to obtain the PDO_ATTR_DRIVER_NAME attribute to check the driver, if your code can run against multiple drivers.
If this attribute is set to TRUE on a PDOStatement, the MySQL driver will use the buffered versions of the MySQL API. If you're writing portable code, you should use PDOStatement::fetchAll() instead.
Esempio 1. Forcing queries to be buffered in mysql
|
The mysqli extension allows you to access the functionality provided by MySQL 4.1 and above. More information about the MySQL Database server can be found at http://www.mysql.com/
Documentation for MySQL can be found at http://dev.mysql.com/doc/.
Parts of this documentation included from MySQL manual with permissions of MySQL AB.
In order to have these functions available, you must compile PHP with support for the mysqli extension.
Nota: The mysqli extension is designed to work with the version 4.1.3 or above of MySQL. For previous versions, please see the MySQL extension documentation.
To install the mysqli extension for PHP, use the --with-mysqli=mysql_config_path/mysql_config configuration option where mysql_config_path represents the location of the mysql_config program that comes with MySQL versions greater than 4.1.
If you would like to install the mysql extension along with the mysqli extension you have to use the same client library to avoid any conflicts.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. MySQLi Configuration Options
Name | Default | Changeable | Changelog |
---|---|---|---|
mysqli.max_links | "-1" | PHP_INI_SYSTEM | Available since PHP 5.0.0. |
mysqli.default_port | "3306" | PHP_INI_ALL | Available since PHP 5.0.0. |
mysqli.default_socket | NULL | PHP_INI_ALL | Available since PHP 5.0.0. |
mysqli.default_host | NULL | PHP_INI_ALL | Available since PHP 5.0.0. |
mysqli.default_user | NULL | PHP_INI_ALL | Available since PHP 5.0.0. |
mysqli.default_pw | NULL | PHP_INI_ALL | Available since PHP 5.0.0. |
For further details and definitions of the above PHP_INI_* constants, see the chapter on configuration changes.
Breve descrizione dei parametri di configurazione.
The maximum number of MySQL connections per process.
The default TCP port number to use when connecting to the database server if no other port is specified. If no default is specified, the port will be obtained from the MYSQL_TCP_PORT environment variable, the mysql-tcp entry in /etc/services or the compile-time MYSQL_PORT constant, in that order. Win32 will only use the MYSQL_PORT constant.
The default socket name to use when connecting to a local database server if no other socket name is specified.
The default server host to use when connecting to the database server if no other host is specified. Doesn't apply in safe mode.
The default user name to use when connecting to the database server if no other name is specified. Doesn't apply in safe mode.
The default password to use when connecting to the database server if no other password is specified. Doesn't apply in safe mode.
Represents a connection between PHP and a MySQL database.
autocommit - turns on or off auto-commiting database modifications
change_user - changes the user of the specified database connection
character_set_name - returns the default character set for the database connection
close - closes a previously opened connection
commit - commits the current transaction
connect - opens a new connection to MySQL database server
debug - performs debugging operations
dump_debug_info - dumps debug information
get_client_info - returns client version
get_host_info - returns type of connection used
get_server_info - returns version of the MySQL server
get_server_version - returns version of the MySQL server
init - initializes mysqli object
info - retrieves information about the most recently executed query
kill - asks the server to kill a mysql thread
multi_query - performs multiple queries
more_results - check if more results exist from currently executed multi-query
next_result - reads next result from currently executed multi-query
options - set options
ping - pings a server connection or reconnects if there is no connection
prepare - prepares a SQL query
query - performs a query
real_connect - attempts to open a connection to MySQL database server
escape_string - escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection
rollback - rolls back the current transaction
select_db - selects the default database
set_charset - sets the default client character set
ssl_set - sets ssl parameters
stat - gets the current system status
stmt_init- initializes a statement for use with mysqli_stmt_prepare
store_result - transfers a resultset from last query
use_result - transfers an unbuffered resultset from last query
thread_safe - returns whether thread safety is given or not
affected_rows - gets the number of affected rows in a previous MySQL operation
client_info - returns the MySQL client version as a string
client_version - returns the MySQL client version as an integer
errno - returns the error code for the most recent function call
error - returns the error string for the most recent function call
field_count - returns the number of columns for the most recent query
host_info - returns a string representing the type of connection used
info - retrieves information about the most recently executed query
insert_id - returns the auto generated id used in the last query
protocol_version - returns the version of the MySQL protocol used
server_info - returns a string that represents the server version number
server_version - returns the version number of the server as an integer
sqlstate - returns a string containing the SQLSTATE error code for the last error
thread_id - returns the thread ID for the current connection
warning_count - returns the number of warnings generated during execution of the previous SQL statement
Represents a prepared statement.
bind_param - binds variables to a prepared statement
bind_result - binds variables to a prepared statement for result storage
close - closes a prepared statement
data_seek - seeks to an arbitrary row in a statement result set
execute - executes a prepared statement
fetch - fetches result from a prepared statement into bound variables
free_result - frees stored result memory for the given statement handle
result_metadata - retrieves a resultset from a prepared statement for metadata information
prepare - prepares a SQL query
send_long_data - sends data in chunks
reset - resets a prepared statement
store_result - buffers complete resultset from a prepared statement
affected_rows - returns affected rows from last statement execution
errno - returns errorcode for last statement function
error - returns errormessage for last statement function
field_count - returns the number of columns in a result set
id - returns the statement identifier
insert_id - returns the value generated for an AUTO_INCREMENT column by the prepared statement
num_rows - returns the number of rows in the result set
param_count - returns number of parameter for a given prepare statement
sqlstate - returns a string containing the SQLSTATE error code for the last statement function
Represents the result set obtained from a query against the database.
close - closes resultset
data_seek - moves internal result pointer
fetch_field - gets column information from a resultset
fetch_fields - gets information for all columns from a resulset
fetch_field_direct - gets column information for specified column
fetch_array - fetches a result row as an associative array, a numeric array, or both.
fetch_assoc - fetches a result row as an associative array
fetch_object - fetches a result row as an object
fetch_row - gets a result row as an enumerated array
close - frees result memory
field_seek - set result pointer to a specified field offset
current_field - returns offset of current fieldpointer
field_count - returns number of fields in resultset
lengths - returns an array of columnlengths
num_rows - returns number of rows in resultset
type - returns MYSQLI_STORE_RESULT or MYSQLI_USE_RESULT
Tabella 2. MySQLi Constants
Name | Description |
---|---|
MYSQLI_READ_DEFAULT_GROUP (integer) | Read options from the named group from `my.cnf' or the file specified with MYSQLI_READ_DEFAULT_FILE |
MYSQLI_READ_DEFAULT_FILE (integer) | Read options from the named option file instead of from my.cnf |
MYSQLI_OPT_CONNECT_TIMEOUT (integer) | Connect timeout in seconds |
MYSQLI_OPT_LOCAL_INFILE (integer) | Enables command LOAD LOCAL INFILE |
MYSQLI_INIT_COMMAND (integer) | Command to execute when connecting to MySQL server. Will automatically be re-executed when reconnecting. |
MYSQLI_CLIENT_SSL (integer) | Use SSL (encrypted protocol). This option should not be set by application programs; it is set internally in the MySQL client library |
MYSQLI_CLIENT_COMPRESS (integer) | Use compression protocol |
MYSQLI_CLIENT_INTERACTIVE (integer) | Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection. The client's session wait_timeout variable will be set to the value of the session interactive_timeout variable. |
MYSQLI_CLIENT_IGNORE_SPACE (integer) | Allow spaces after function names. Makes all functions names reserved words. |
MYSQLI_CLIENT_NO_SCHEMA (integer) | Don't allow the db_name.tbl_name.col_name syntax. |
MYSQLI_CLIENT_MULTI_QUERIES (integer) | |
MYSQLI_STORE_RESULT (integer) | For using buffered resultsets |
MYSQLI_USE_RESULT (integer) | For using unbuffered resultsets |
MYSQLI_ASSOC (integer) | Columns are returned into the array having the fieldname as the array index. |
MYSQLI_NUM (integer) | Columns are returned into the array having an enumerated index. |
MYSQLI_BOTH (integer) | Columns are returned into the array having both a numerical index and the fieldname as the associative index. |
MYSQLI_NOT_NULL_FLAG (integer) | Indicates that a field is defined as NOT NULL |
MYSQLI_PRI_KEY_FLAG (integer) | Field is part of a primary index |
MYSQLI_UNIQUE_KEY_FLAG (integer) | Field is part of a unique index. |
MYSQLI_MULTIPLE_KEY_FLAG (integer) | Field is part of an index. |
MYSQLI_BLOB_FLAG (integer) | Field is defined as BLOB |
MYSQLI_UNSIGNED_FLAG (integer) | Field is defined as UNSIGNED |
MYSQLI_ZEROFILL_FLAG (integer) | Field is defined as ZEROFILL |
MYSQLI_AUTO_INCREMENT_FLAG (integer) | Field is defined as AUTO_INCREMENT |
MYSQLI_TIMESTAMP_FLAG (integer) | Field is defined as TIMESTAMP |
MYSQLI_SET_FLAG (integer) | Field is defined as SET |
MYSQLI_NUM_FLAG (integer) | Field is defined as NUMERIC |
MYSQLI_PART_KEY_FLAG (integer) | Field is part of an multi-index |
MYSQLI_GROUP_FLAG (integer) | Field is part of GROUP BY |
MYSQLI_TYPE_DECIMAL (integer) | Field is defined as DECIMAL |
MYSQLI_TYPE_TINY (integer) | Field is defined as TINYINT |
MYSQLI_TYPE_SHORT (integer) | Field is defined as INT |
MYSQLI_TYPE_LONG (integer) | Field is defined as INT |
MYSQLI_TYPE_FLOAT (integer) | Field is defined as FLOAT |
MYSQLI_TYPE_DOUBLE (integer) | Field is defined as DOUBLE |
MYSQLI_TYPE_NULL (integer) | Field is defined as DEFAULT NULL |
MYSQLI_TYPE_TIMESTAMP (integer) | Field is defined as TIMESTAMP |
MYSQLI_TYPE_LONGLONG (integer) | Field is defined as BIGINT |
MYSQLI_TYPE_INT24 (integer) | Field is defined as MEDIUMINT |
MYSQLI_TYPE_DATE (integer) | Field is defined as DATE |
MYSQLI_TYPE_TIME (integer) | Field is defined as TIME |
MYSQLI_TYPE_DATETIME (integer) | Field is defined as DATETIME |
MYSQLI_TYPE_YEAR (integer) | Field is defined as YEAR |
MYSQLI_TYPE_NEWDATE (integer) | Field is defined as DATE |
MYSQLI_TYPE_ENUM (integer) | Field is defined as ENUM |
MYSQLI_TYPE_SET (integer) | Field is defined as SET |
MYSQLI_TYPE_TINY_BLOB (integer) | Field is defined as TINYBLOB |
MYSQLI_TYPE_MEDIUM_BLOB (integer) | Field is defined as MEDIUMBLOB |
MYSQLI_TYPE_LONG_BLOB (integer) | Field is defined as LONGBLOB |
MYSQLI_TYPE_BLOB (integer) | Field is defined as BLOB |
MYSQLI_TYPE_VAR_STRING (integer) | Field is defined as VARCHAR |
MYSQLI_TYPE_STRING (integer) | Field is defined as CHAR |
MYSQLI_TYPE_GEOMETRY (integer) | Field is defined as GEOMETRY |
MYSQLI_NEED_DATA (integer) | More data available for bind variable |
MYSQLI_NO_DATA (integer) | No more data available for bind variable |
MYSQLI_DATA_TRUNCATED (integer) | Data truncation occurred. Available since PHP 5.1.0 and MySQL 5.0.5. |
All Examples in the MySQLI documentation use the world database from MySQL AB. The world database can be found at http://dev.mysql.com/get/Downloads/Manual/world.sql.gz/from/pick
(PHP 5)
mysqli_affected_rows(no version information, might be only in CVS)
mysqli->affected_rows -- Gets the number of affected rows in a previous MySQL operationProcedural style:
int mysqli_affected_rows ( mysqli link )Object oriented style (property):
class mysqli {mysqli_affected_rows() returns the number of rows affected by the last INSERT, UPDATE, or DELETE query associated with the provided link parameter. If the last query was invalid, this function will return -1.
Nota: For SELECT statements mysqli_affected_rows() works like mysqli_num_rows().
The mysqli_affected_rows() function only works with queries which modify a table. In order to return the number of rows from a SELECT query, use the mysqli_num_rows() function instead.
An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error.
Nota: If the number of affected rows is greater than maximal int value, the number of affected rows will be returned as a string.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Affected rows (INSERT): 984 Affected rows (UPDATE): 168 Affected rows (DELETE): 815 Affected rows (SELECT): 169 |
(PHP 5)
mysqli_autocommit(no version information, might be only in CVS)
mysqli->autocommit -- Turns on or off auto-commiting database modificationsProcedural style:
bool mysqli_autocommit ( mysqli link, bool mode )Object oriented style (method)
class mysqli {mysqli_autocommit() is used to turn on or off auto-commit mode on queries for the database connection represented by the link object.
Nota: mysqli_autocommit() doesn't work with non transactional table types (like MyISAM or ISAM).
To determine the current state of autocommit use the SQL command 'SELECT @@autocommit'.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Autocommit is 1 |
This function is an alias of mysqli_stmt_bind_param(). For a detailled descripton see description of mysqli_stmt_bind_param().
Nota: mysqli_bind_param() is deprecated and will be removed.
This function is an alias of mysqli_stmt_bind_result(). For a detailled descripton see description of mysqli_stmt_bind_result().
Nota: mysqli_bind_result() is deprecated and will be removed.
(PHP 5)
mysqli_change_user(no version information, might be only in CVS)
mysqli->change_user -- Changes the user of the specified database connectionProcedural style:
bool mysqli_change_user ( mysqli link, string user, string password, string database )Object oriented style (method):
class mysqli {mysqli_change_user() is used to change the user of the specified database connection as given by the link parameter and to set the current database to that specified by the database parameter.
If desired, the NULL value may be passed in place of the database parameter resulting in only changing the user and not selecting a database. To select a database in this case use the mysqli_select_db() function.
In order to successfully change users a valid username and password parameters must be provided and that user must have sufficient permissions to access the desired database. If for any reason authorization fails, the current user authentication will remain.
Nota: Using this command will always cause the current database connection to behave as if was a completely new database connection, regardless of if the operation was completed successfully. This reset includes performing a rollback on any active transactions, closing all temporary tables, and unlocking all locked tables.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Default database: world Value of variable a is NULL |
(PHP 5)
mysqli_character_set_name(no version information, might be only in CVS)
mysqli->character_set_name -- Returns the default character set for the database connectionProcedural style:
string mysqli_character_set_name ( mysqli link )Object oriented style (method):
class mysqli {Returns the current character set for the database connection specified by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Current character set is latin1_swedish_ci |
This function is an alias of mysqli_character_set_name(). For a detailled descripton see description of mysqli_character_set_name().
(PHP 5)
mysqli_close(no version information, might be only in CVS)
mysqli->close -- Closes a previously opened database connectionProcedural style:
bool mysqli_close ( mysqli link )Object oriented style (method):
class mysqli {The mysqli_close() function closes a previously opened database connection specified by the link parameter.
(PHP 5)
mysqli_commit(no version information, might be only in CVS)
mysqli->commit -- Commits the current transactionProcedural style:
bool mysqli_commit ( mysqli link )Object oriented style (method)
class mysqli {Commits the current transaction for the database connection specified by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The mysqli_connect_errno() function will return the last error code number for last call to mysqli_connect(). If no errors have occured, this function will return zero.
Nota: Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.
An error code value for the last call to mysqli_connect(), if it failed. zero means no error occurred.
mysqli_connect(), mysqli_connect_error(), mysqli_errno(), mysqli_error() e mysqli_sqlstate().
The mysqli_connect_error() function is identical to the corresponding mysqli_connect_errno() function in every way, except instead of returning an integer error code the mysqli_connect_error() function will return a string representation of the last error to occur for the last mysqli_connect() call. If no error has occured, this function will return an empty string.
mysqli_connect(), mysqli_connect_errno(), mysqli_errno(), mysqli_error() e mysqli_sqlstate().
(PHP 5)
mysqli_connect(no version information, might be only in CVS)
mysqli() -- Open a new connection to the MySQL serverProcedural style
mysqli mysqli_connect ( [string host [, string username [, string passwd [, string dbname [, int port [, string socket]]]]]] )Object oriented style (constructor):
class mysqli {The mysqli_connect() function attempts to open a connection to the MySQL Server running on host which can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol. If successful, the mysqli_connect() will return an object representing the connection to the database, or FALSE on failure.
The username and password parameters specify the username and password under which to connect to the MySQL server. If the password is not provided (the NULL value is passed), the MySQL server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password as provided or not).
The dbname parameter if provided will specify the default database to be used when performing queries.
The port and socket parameters are used in conjunction with the host parameter to further control how to connect to the database server. The port parameter specifies the port number to attempt to connect to the MySQL server on, while the socket parameter specifies the socket or named pipe that should be used.
Nota: Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by the host parameter.
Returns a object which represents the connection to a MySQL Server or FALSE if the connection failed.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Host information: Localhost via UNIX socket |
(PHP 5)
mysqli_data_seek(no version information, might be only in CVS)
result->data_seek -- Adjusts the result pointer to an arbitary row in the resultProcedural style:
bool mysqli_data_seek ( mysqli_result result, int offset )Object oriented style (method):
class mysqli_result {The mysqli_data_seek() function seeks to an arbitrary result pointer specified by the offset in the result set represented by result. The offset parameter must be between zero and the total number of rows minus one (0..mysqli_num_rows() - 1).
Nota: This function can only be used with buffered results attained from the use of the mysqli_store_result() or mysqli_query() functions.
mysqli_store_result(), mysqli_fetch_row(), mysqli_fetch_array(), mysqli_fetch_assoc(), mysqli_fetch_object(), mysqli_query() e mysqli_num_rows().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
City: Benin City Countrycode: NGA |
The mysqli_debug() function is used to perform debugging operations using the Fred Fish debugging library. The debug parameter is a string representing the debugging operation to perform.
Nota: To use the mysqli_debug() function you must complile the MySQL client library to support debugging.
(PHP 5)
mysqli_disable_reads_from_master(no version information, might be only in CVS)
mysqli->disable_reads_from_master -- Disable reads from masterProcedural style:
bool mysqli_disable_reads_from_master ( mysqli link )Object oriented style (method):
class mysqli {Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 5)
mysqli_dump_debug_info(no version information, might be only in CVS)
mysqli->dump_debug_info -- Dump debugging information into the logThis function is designed to be executed by an user with the SUPER privilege and is used to dump debugging information into the log for the MySQL Server relating to the connection specified by the link parameter.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 5)
mysqli_errno(no version information, might be only in CVS)
mysqli->errno -- Returns the error code for the most recent function callProcedural style:
int mysqli_errno ( mysqli link )Object oriented style (property):
class mysqli {The mysqli_errno() function will return the last error code for the most recent MySQLi function call that can succeed or fail with respect to the database link defined by the link parameter. If no errors have occured, this function will return zero.
Nota: Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.
An error code value for the last call, if it failed. zero means no error occurred.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Errorcode: 1193 |
Procedural style:
string mysqli_error ( mysqli link )Object oriented style (property)
class mysqli {The mysqli_error() function is identical to the corresponding mysqli_errno() function in every way, except instead of returning an integer error code the mysqli_error() function will return a string representation of the last error to occur for the database connection represented by the link parameter. If no error has occured, this function will return an empty string.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Errormessage: Unknown system variable 'a' |
This function is an alias of mysqli_stmt_execute(). For a detailled descripton see description of mysqli_stmt_execute().
Nota: mysqli_execute() is deprecated and will be removed.
(PHP 5)
mysqli_fetch_array(no version information, might be only in CVS)
result->fetch_array -- Fetch a result row as an associative, a numeric array, or bothProcedural style:
mixed mysqli_fetch_array ( mysqli_result result [, int resulttype] )Object oriented style (method):
class mysqli_result {Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.
mysqli_fetch_array() is an extended version of the mysqli_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Nota: This function sets NULL fields to PHP NULL value.
If two or more columns of the result have the same field names, the last column will take precedence and overwrite the earlier data. In order to access multiple columns with the same name, the numerically indexed version of the row must be used.
The optional second argument resulttype is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH. By default the mysqli_fetch_array() function will assume MYSQLI_BOTH for this parameter.
By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave identically to the mysqli_fetch_row() function. The final option MYSQLI_BOTH will create a single array with the attributes of both.
Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.
mysqli_fetch_assoc(), mysqli_fetch_row(), mysqli_fetch_object(), mysqli_query() e mysqli_data_seek().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Kabul (AFG) Qandahar (AFG) Herat (AFG) |
(PHP 5)
mysqli_fetch_assoc(no version information, might be only in CVS)
mysqli->fetch_assoc -- Fetch a result row as an associative arrayProcedural style:
array mysqli_fetch_assoc ( mysqli_result result )Object oriented style (method):
class mysqli_result {Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.
The mysqli_fetch_assoc() function is used to return an associative array representing the next row in the result set for the result represented by the result parameter, where each key in the array represents the name of one of the result set's columns.
If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using mysqli_fetch_row() or add alias names.
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Nota: This function sets NULL fields to PHP NULL value.
Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.
mysqli_fetch_array(), mysqli_fetch_row(), mysqli_fetch_object(), mysqli_query() e mysqli_data_seek().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA) |
(PHP 5)
mysqli_fetch_field_direct(no version information, might be only in CVS)
result->fetch_field_direct -- Fetch meta-data for a single fieldProcedural style:
object mysqli_fetch_field_direct ( mysqli_result result, int fieldnr )Object oriented style (method):
class mysqli_result {mysqli_fetch_field_direct() returns an object which contains field definition informations from specified resultset. The value of fieldnr must be in the range from 0 to number of fields - 1.
Returns an object which contains field definition information or FALSE if no field information for specified fieldnr is available.
Tabella 1. Object attributes
Attribute | Description |
---|---|
name | The name of the column |
orgname | Original column name if an alias was specified |
table | The name of the table this field belongs to (if not calculated) |
orgtable | Original table name if an alias was specified |
def | The default value for this field, represented as a string |
max_length | The maximum width of the field for the result set. |
flags | An integer representing the bit-flags for the field. |
type | The data type used for this field |
decimals | The number of decimals used (for integer fields) |
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Name: SurfaceArea Table: Country max. Len: 10 Flags: 32769 Type: 4 |
(PHP 5)
mysqli_fetch_field(no version information, might be only in CVS)
result->fetch_field -- Returns the next field in the result setProcedural style:
object mysqli_fetch_field ( mysqli_result result )Object oriented style (method):
class mysqli_result {The mysqli_fetch_field() returns the definition of one column of a result set as an object. Call this function repeatedly to retrieve information about all columns in the result set. mysqli_fetch_field() returns FALSE when no more fields are left.
Returns an object which contains field definition information or FALSE if no field information is available.
Tabella 1. Object properties
Property | Description |
---|---|
name | The name of the column |
orgname | Original column name if an alias was specified |
table | The name of the table this field belongs to (if not calculated) |
orgtable | Original table name if an alias was specified |
def | The default value for this field, represented as a string |
max_length | The maximum width of the field for the result set. |
flags | An integer representing the bit-flags for the field. |
type | The data type used for this field |
decimals | The number of decimals used (for integer fields) |
mysqli_num_fields(), mysqli_fetch_field_direct(), mysqli_fetch_fields() e mysqli_field_seek().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Name: Name Table: Country max. Len: 11 Flags: 1 Type: 254 Name: SurfaceArea Table: Country max. Len: 10 Flags: 32769 Type: 4 |
(PHP 5)
mysqli_fetch_fields(no version information, might be only in CVS)
result->fetch_fields -- Returns an array of objects representing the fields in a result setProcedural Style:
array mysqli_fetch_fields ( mysqli_result result )Object oriented style (method):
class mysqli_result {This function serves an identical purpose to the mysqli_fetch_field() function with the single difference that, instead of returning one object at a time for each field, the columns are returned as an array of objects.
Returns an array of objects which contains field definition information or FALSE if no field information is available.
Tabella 1. Object properties
Property | Description |
---|---|
name | The name of the column |
orgname | Original column name if an alias was specified |
table | The name of the table this field belongs to (if not calculated) |
orgtable | Original table name if an alias was specified |
def | The default value for this field, represented as a string |
max_length | The maximum width of the field for the result set. |
flags | An integer representing the bit-flags for the field. |
type | The data type used for this field |
decimals | The number of decimals used (for integer fields) |
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Name: Name Table: Country max. Len: 11 Flags: 1 Type: 254 Name: SurfaceArea Table: Country max. Len: 10 Flags: 32769 Type: 4 |
(PHP 5)
mysqli_fetch_lengths(no version information, might be only in CVS)
result->lengths -- Returns the lengths of the columns of the current row in the result setProcedural style:
array mysqli_fetch_lengths ( mysqli_result result )Object oriented style (property):
class mysqli_result {The mysqli_fetch_lengths() function returns an array containing the lengths of every column of the current row within the result set represented by the result parameter. If successful, a numerically indexed array representing the lengths of each column is returned or FALSE on failure.
An array of integers representing the size of each column (not including any terminating null characters). FALSE if an error occurred.
mysqli_fetch_lengths() is valid only for the current row of the result set. It returns FALSE if you call it before calling mysqli_fetch_row/array/object or after retrieving all rows in the result.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Field 1 has Length 3 Field 2 has Length 5 Field 3 has Length 13 Field 4 has Length 9 Field 5 has Length 6 Field 6 has Length 1 Field 7 has Length 6 Field 8 has Length 4 Field 9 has Length 6 Field 10 has Length 6 Field 11 has Length 5 Field 12 has Length 44 Field 13 has Length 7 Field 14 has Length 3 Field 15 has Length 2 |
(PHP 5)
mysqli_fetch_object(no version information, might be only in CVS)
result->fetch_object -- Returns the current row of a result set as an objectProcedural style:
mixed mysqli_fetch_object ( mysqli_result result )Object oriented style (method):
class mysqli_result {The mysqli_fetch_object() will return the current row result set as an object where the attributes of the object represent the names of the fields found within the result set. If no more rows exist in the current result set, NULL is returned.
Returns an object that corresponds to the fetched row or NULL if there are no more rows in resultset.
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Nota: This function sets NULL fields to PHP NULL value.
mysqli_fetch_array(), mysqli_fetch_assoc(), mysqli_fetch_row(), mysqli_query() e mysqli_data_seek().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA) |
(PHP 5)
mysqli_fetch_row(no version information, might be only in CVS)
result->fetch_row -- Get a result row as an enumerated arrayProcedural style:
mixed mysqli_fetch_row ( mysqli_result result )Object oriented style (method):
class mysqli_result {Returns an array that corresponds to the fetched row, or NULL if there are no more rows.
mysqli_fetch_row() fetches one row of data from the result set represented by result and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to the mysqli_fetch_row() function will return the next row within the result set, or FALSE if there are no more rows.
mysqli_fetch_row() returns an array that corresponds to the fetched row or NULL if there are no more rows in result set.
Nota: This function sets NULL fields to PHP NULL value.
mysqli_fetch_array(), mysqli_fetch_assoc(), mysqli_fetch_object(), mysqli_query() e mysqli_data_seek().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA) |
This function is an alias of mysqli_stmt_fetch(). For a detailled descripton see description of mysqli_stmt_fetch().
Nota: mysqli_fetch() is deprecated and will be removed.
(PHP 5)
mysqli_field_count(no version information, might be only in CVS)
mysqli->field_count -- Returns the number of columns for the most recent queryProcedural style:
int mysqli_field_count ( mysqli link )Object oriented style (method):
class mysqli_result {Returns the number of columns for the most recent query on the connection represented by the link parameter. This function can be useful when using the mysqli_store_result() function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
(PHP 5)
mysqli_field_seek(no version information, might be only in CVS)
result->field_seek -- Set result pointer to a specified field offsetProcedural style:
bool mysqli_field_seek ( mysqli_result result, int fieldnr )Object oriented style (method):
class mysqli_result {Sets the field cursor to the given offset. The next call to mysqli_fetch_field() will retrieve the field definition of the column associated with that offset.
Nota: To seek to the beginning of a row, pass an offset value of zero.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Name: SurfaceArea Table: Country max. Len: 10 Flags: 32769 Type: 4 |
(PHP 5)
mysqli_field_tell(no version information, might be only in CVS)
result->current_field -- Get current field offset of a result pointerProcedural style:
int mysqli_field_tell ( mysqli_result result )Object oriented style (property):
class mysqli_result {Returns the position of the field cursor used for the last mysqli_fetch_field() call. This value can be used as an argument to mysqli_field_seek().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Column 1: Name: Name Table: Country max. Len: 11 Flags: 1 Type: 254 Column 2: Name: SurfaceArea Table: Country max. Len: 10 Flags: 32769 Type: 4 |
(PHP 5)
mysqli_free_result(no version information, might be only in CVS)
result->free -- Frees the memory associated with a resultProcedural style:
void mysqli_free_result ( mysqli_result result )Object oriented style (method):
class mysqli_result {The mysqli_free_result() function frees the memory associated with the result represented by the result parameter, which was allocated by mysqli_query(), mysqli_store_result() or mysqli_use_result().
Nota: You should always free your result with mysqli_free_result(), when your result object is not needed anymore.
mysqli_query(), mysqli_stmt_store_result(), mysqli_store_result() e mysqli_use_result().
The mysqli_get_client_info() function is used to return a string representing the client version being used in the MySQLi extension.
A number that represents the MySQL client library version in format: main_version*10000 + minor_version *100 + sub_version. For example, 4.1.0 is returned as 40100.
This is useful to quickly determine the version of the client library to know if some capability exits.
(PHP 5)
mysqli_get_host_info(no version information, might be only in CVS)
mysqli->get_host_info -- Returns a string representing the type of connection usedProcdural style:
string mysqli_get_host_info ( mysqli link )Object oriented style (property):
class mysqli {The mysqli_get_host_info() function returns a string describing the connection represented by the link parameter is using (including the server host name).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Host info: Localhost via UNIX socket |
This function is an alias of mysqli_stmt_result_metadata(). For a detailled descripton see description of mysqli_stmt_result_metadata().
Nota: mysqli_get_metadata() is deprecated and will be removed.
(PHP 5)
mysqli_get_proto_info(no version information, might be only in CVS)
mysqli->protocol_version -- Returns the version of the MySQL protocol usedProcedural style:
int mysqli_get_proto_info ( mysqli link )Object oriented style (property):
class mysqli {Returns an integer representing the MySQL protocol version used by the connection represented by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Protocol version: 10 |
(PHP 5)
mysqli_get_server_info(no version information, might be only in CVS)
mysqli->server_info -- Returns the version of the MySQL serverProcedural style:
string mysqli_get_server_info ( mysqli link )Object oriented style (property):
class mysqli {Returns a string representing the version of the MySQL server that the MySQLi extension is connected to (represented by the link parameter).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Server version: 4.1.2-alpha-debug |
Procedural style:
int mysqli_get_server_version ( mysqli link )Object oriented style (property):
class mysqli {The mysqli_get_server_version() function returns the version of the server connected to (represented by the link parameter) as an integer.
The form of this version number is main_version * 10000 + minor_version * 100 + sub_version (i.e. version 4.1.0 is 40100).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Server version: 40102 |
(PHP 5)
mysqli_info(no version information, might be only in CVS)
mysqli->info -- Retrieves information about the most recently executed queryProcedural style:
string mysqli_info ( mysqli link )Object oriented style (property)
class mysqli {The mysqli_info() function returns a string providing information about the last query executed. The nature of this string is provided below:
Tabella 1. Possible mysqli_info return values
Query type | Example result string |
---|---|
INSERT INTO...SELECT... | Records: 100 Duplicates: 0 Warnings: 0 |
INSERT INTO...VALUES (...),(...),(...) | Records: 3 Duplicates: 0 Warnings: 0 |
LOAD DATA INFILE ... | Records: 1 Deleted: 0 Skipped: 0 Warnings: 0 |
ALTER TABLE ... | Records: 3 Duplicates: 0 Warnings: 0 |
UPDATE ... | Rows matched: 40 Changed: 40 Warnings: 0 |
Nota: Queries which do not fall into one of the above formats are not supported. In these situations, mysqli_info() will return an empty string.
A character string representing additional information about the most recently executed query.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Records: 150 Duplicates: 0 Warnings: 0 |
Allocates or initializes a MYSQL object suitable for mysqli_options() and mysqli_real_connect().
Nota: Any subsequent calls to any mysqli function (except mysqli_options()) will fail until mysqli_real_connect() was called.
(PHP 5)
mysqli_insert_id(no version information, might be only in CVS)
mysqli->insert_id -- Returns the auto generated id used in the last queryProcedural style:
int mysqli_insert_id ( mysqli link )Object oriented style (property):
class mysqli {The mysqli_insert_id() function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.
Nota: Performing an INSERT or UPDATE statement using the LAST_INSERT_ID() function will also modify the value returned by the mysqli_insert_id() function.
The value of the AUTO_INCREMENT field that was updated by the previous query. Returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value.
Nota: If the number is greater than maximal int value, mysqli_insert_id() will return a string.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
New Record has id 1. |
(PHP 5)
mysqli_kill(no version information, might be only in CVS)
mysqli->kill -- Asks the server to kill a MySQL threadProcedural style:
bool mysqli_kill ( mysqli link, int processid )Object oriented style (method)
class mysqli {This function is used to ask the server to kill a MySQL thread specified by the processid parameter. This value must be retrieved by calling the mysqli_thread_id() function.
Nota: To stop a running query you should use the SQL command KILL QUERY processid.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Error: MySQL server has gone away |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 5)
mysqli_more_results(no version information, might be only in CVS)
mysqli->more_results -- Check if there any more query results from a multi querymysqli_more_results() indicates if one or more result sets are available from a previous call to mysqli_multi_query().
mysqli_multi_query(), mysqli_next_result(), mysqli_store_result() e mysqli_use_result().
(PHP 5)
mysqli_multi_query(no version information, might be only in CVS)
mysqli->multi_query -- Performs a query on the databaseProcedural style:
bool mysqli_multi_query ( mysqli link, string query )Object oriented style (method):
class mysqli {The mysqli_multi_query() executes one or multiple queries which are concatenated by a semicolon.
To retrieve the resultset from the first query you can use mysqli_use_result() or mysqli_store_result(). All subsequent query results can be processed using mysqli_more_results() and mysqli_next_result().
mysqli_multi_query() only returns FALSE if the first statement failed. To retrieve subsequent errors from other statements you have to call mysqli_next_result() first.
mysqli_use_result(), mysqli_store_result(), mysqli_next_result() e mysqli_more_results().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
my_user@localhost ----------------- Amersfoort Maastricht Dordrecht Leiden Haarlemmermeer |
(PHP 5)
mysqli_next_result(no version information, might be only in CVS)
mysqli->next_result -- Prepare next result from multi_querymysqli_next_result() prepares next result set from a previous call to mysqli_multi_query() which can be retrieved by mysqli_store_result() or mysqli_use_result().
mysqli_multi_query(), mysqli_more_results(), mysqli_store_result() e mysqli_use_result().
(PHP 5)
mysqli_num_fields(no version information, might be only in CVS)
result->field_count -- Get the number of fields in a resultProcedural style:
int mysqli_num_fields ( mysqli_result result )Object oriented style (property):
class mysqli_result {mysqli_num_fields() returns the number of fields from specified result set.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Result set has 5 fields. |
Procedural style:
int mysqli_num_rows ( mysqli result )Object oriented style (property):
class mysqli {Returns the number of rows in the result set.
The use of mysqli_num_rows() depends on whether you use buffered or unbuffered result sets. In case you use unbuffered resultsets mysqli_num_rows() will not correct the correct number of rows until all the rows in the result have been retrieved.
Returns number of rows in the result set.
Nota: If the number of rows is greater than maximal int value, the number will be returned as a string.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Result set has 239 rows. |
Procedural style:
bool mysqli_options ( mysqli link, int option, mixed value )Object oriented style (method)
class mysqli {mysqli_options() can be used to set extra connect options and affect behavior for a connection.
This function may be called multiple times to set several options.
mysqli_options() should be called after mysqli_init() and before mysqli_real_connect().
The parameter option is the option that you want to set, the value is the value for the option. The parameter option can be one of the following values:
Tabella 1. Valid options
Name | Description |
---|---|
MYSQLI_OPT_CONNECT_TIMEOUT | connection timeout in seconds |
MYSQLI_OPT_LOCAL_INFILE | enable/disable use of LOAD LOCAL INFILE |
MYSQLI_INIT_CMD | command to execute after when connecting to MySQL server |
MYSQLI_READ_DEFAULT_FILE | Read options from named option file instead of my.cnf |
MYSQLI_READ_DEFAULT_GROUP | Read options from the named group from my.cnf or the file specified with MYSQL_READ_DEFAULT_FILE. |
This function is an alias of mysqli_stmt_param_count(). For a detailled descripton see description of mysqli_stmt_param_count().
Nota: mysqli_param_count() is deprecated and will be removed.
(PHP 5)
mysqli_ping(no version information, might be only in CVS)
mysqli->ping -- Pings a server connection, or tries to reconnect if the connection has gone downProcedural style:
bool mysqli_ping ( mysqli link )Object oriented style (method):
class mysqli {Checks whether the connection to the server is working. If it has gone down, and global option mysqli.reconnect is enabled an automatic reconnection is attempted.
This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Our connection is ok! |
(PHP 5)
mysqli_prepare(no version information, might be only in CVS)
mysqli->prepare -- Prepare a SQL statement for executionProcedure style:
mysqli_stmt mysqli_prepare ( mysqli link, string query )Object oriented style (method)
class mysqli {mysqli_prepare() prepares the SQL query pointed to by the null-terminated string query, and returns a statement handle to be used for further operations on the statement. The query must consist of a single SQL statement.
Nota: You should not add a terminating semicolon or \g to the statement.
The parameter query can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.
Nota: The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.
However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement, or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. It's not allowed to compare marker with NULL by ? IS NULL too. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.
The parameter markers must be bound to application variables using mysqli_stmt_bind_param() and/or mysqli_stmt_bind_result() before executing the statement or fetching rows.
mysqli_stmt_execute(), mysqli_stmt_fetch(), mysqli_stmt_bind_param(), mysqli_stmt_bind_result() e mysqli_stmt_close().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Amersfoort is in district Utrecht |
(PHP 5)
mysqli_query(no version information, might be only in CVS)
mysqli->query -- Performs a query on the databaseProcedural style:
mixed mysqli_query ( mysqli link, string query [, int resultmode] )Object oriented style (method):
class mysqli {The mysqli_query() function is used to simplify the act of performing a query against the database represented by the link parameter.
Functionally, using this function is identical to calling mysqli_real_query() followed either by mysqli_use_result() or mysqli_store_result() where query is the query string itself and resultmode is either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, if the resultmode is not provided MYSQLI_STORE_RESULT is used.
If you execute mysqli_query() with resultmode MYSQLI_USE_RESULT all subsequent calls will return error Commands out of sync unless you call mysqli_free_result().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Table myCity successfully created. Select returned 10 rows. Error: Commands out of sync; You can't run this command now |
(PHP 5)
mysqli_real_connect(no version information, might be only in CVS)
mysqli->real_connect -- Opens a connection to a mysql serverProcedural style
bool mysqli_real_connect ( mysqli link [, string hostname [, string username [, string passwd [, string dbname [, int port [, string socket [, int flags]]]]]]] )Object oriented style (method)
class mysqli {mysqli_real_connect() attempts to establish a connection to a MySQL database engine running on hostname.
This function differs from mysqli_connect():
mysqli_real_connect() needs a valid object which has to be created by function mysqli_init()
With function mysqli_options() you can set various options for connection.
With the parameter flags you can set different connection options:
Tabella 1. Supported flags
Name | Description |
---|---|
MYSQLI_CLIENT_COMPRESS | Use compression protocol |
MYSQLI_CLIENT_FOUND_ROWS | return number of matched rows, not the number of affected rows |
MYSQLI_CLIENT_IGNORE_SPACE | Allow spaces after function names. Makes all function names reserved words. |
MYSQLI_CLIENT_INTERACTIVE | Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection |
MYSQLI_CLIENT_SSL | Use SSL (encryption) |
Nota: For security reasons the MULTI_STATEMENT flag is not supported in PHP. If you want to execute multiple queries use the mysqli_multi_query() function.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Connection: Localhost via UNIX socket |
(PHP 5)
mysqli_real_escape_string(no version information, might be only in CVS)
mysqli->real_escape_string -- Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connectionProcedural style:
string mysqli_real_escape_string ( mysqli link, string escapestr )Object oriented style (method):
class mysqli {This function is used to create a legal SQL string that you can use in a SQL statement. The string escapestr is encoded to an escaped SQL string, taking into account the current character set of the connection.
Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Error: 42000 1 Row inserted. |
(PHP 5)
mysqli_real_query(no version information, might be only in CVS)
mysqli->real_query -- Execute an SQL queryProcedural style
bool mysqli_real_query ( mysqli link, string query )Object oriented style (method):
class mysqli {The mysqli_real_query() function is used to execute only a query against the database represented by the link whose result can then be retrieved or stored using the mysqli_store_result() or mysqli_use_result() functions.
Nota: In order to determine if a given query should return a result set or not, see mysqli_field_count().
mysqli_report() is a powerful function to improve your queries and code during development and testing phase. Depending on the flags it reports errors from mysqli function calls or queries which don't use an index (or use a bad index).
Esempio 1. Object oriented style
|
(PHP 5)
mysqli_rollback(no version information, might be only in CVS)
mysqli->rollback -- Rolls back current transactionRollbacks the current transaction for the database specified by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
0 rows in table myCity. 50 rows in table myCity (after rollback). |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 5)
mysqli_rpl_query_type(no version information, might be only in CVS)
mysqli->rpl_query_type -- Returns RPL query typeProcedural style:
int mysqli_rpl_query_type ( mysqli link, string query )Object oriented style (method)
class mysqli {Returns MYSQLI_RPL_MASTER, MYSQLI_RPL_SLAVE or MYSQLI_RPL_ADMIN depending on a query type. INSERT, UPDATE and similar are master queries, SELECT is slave, and FLUSH, REPAIR and similar are admin.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 5)
mysqli_select_db(no version information, might be only in CVS)
mysqli->select_db -- Selects the default database for database queriesThe mysqli_select_db() function selects the default database (specified by the dbname parameter) to be used when performing queries against the database connection represented by the link parameter.
Nota: This function should only be used to change the default database for the connection. You can select the default database with 4th parameter in mysqli_connect().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Default database is test. Default database is world. |
This function is an alias of mysqli_stmt_send_long_data(). For a detailled descripton see description of mysqli_stmt_send_long_data().
Nota: mysqli_send_long_data() is deprecated and will be removed.
(PHP 5)
mysqli_send_query(no version information, might be only in CVS)
mysqli->send_query -- Send the query and returnProcedural style:
bool mysqli_send_query ( mysqli link, string query )Object oriented style (method)
class mysqli {Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 5 >= 5.1.0RC1)
mysqli_set_charset(no version information, might be only in CVS)
mysqli->set_charset -- Sets the default client character setThe mysqli_set_charset() function sets the default character set (specified by the charset parameter) to be used when sending data from and to the database server represented by the link parameter.
Nota: To use this function on a Windows platform you need MySQL client library version 4.1.11 or above (for MySQL 5.0 you need 5.0.6 or above)
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Current character set: utf8 |
(PHP 5)
mysqli_sqlstate(no version information, might be only in CVS)
mysqli->sqlstate -- Returns the SQLSTATE error from previous MySQL operationProcedural style:
string mysqli_sqlstate ( mysqli link )Object oriented style (property):
class mysqli {Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see http://dev.mysql.com/doc/mysql/en/error-handling.html.
Nota: Note that not all MySQL errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.
Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Error - SQLSTATE 42S01. |
(PHP 5)
mysqli_ssl_set(no version information, might be only in CVS)
mysqli->ssl_set -- Used for establishing secure connections using SSLProcedural style:
bool mysqli_ssl_set ( mysqli link, string key, string cert, string ca, string capath, string cipher )Object oriented style (method):
class mysqli {The function mysqli_ssl_set() is used for establishing secure connections using SSL. It must be called before mysqli_real_connect(). This function does nothing unless OpenSSL support is enabled.
key is the pathname to the key file. cert is the pathname to the certificate file. ca is the pathname to the certificate authority file. capath is the pathname to a directory that contains trusted SSL CA certificates in pem format. cipher is a list of allowable ciphers to use for SSL encryption. Any unused SSL parameters may be given as NULL
This function always returns TRUE value. If SSL setup is incorrect mysqli_real_connect() will return an error when you attempt to connect.
(PHP 5)
mysqli_stat(no version information, might be only in CVS)
mysqli->stat -- Gets the current system statusProcedural style:
string mysqli_stat ( mysqli link )Object oriented style (method):
class mysqli {mysqli_stat() returns a string containing information similar to that provided by the 'mysqladmin status' command. This includes uptime in seconds and the number of running threads, questions, reloads, and open tables.
Il precedente esempio visualizzerà:
System status: Uptime: 272 Threads: 1 Questions: 5340 Slow queries: 0 Opens: 13 Flush tables: 1 Open tables: 0 Queries per second avg: 19.632 Memory in use: 8496K Max memory used: 8560K |
(PHP 5)
mysqli_stmt_affected_rows(no version information, might be only in CVS)
mysqli_stmt->affected_rows -- Returns the total number of rows changed, deleted, or inserted by the last executed statementProcedural style :
int mysqli_stmt_affected_rows ( mysqli_stmt stmt )Object oriented style (property):
class mysqli_stmt {mysqli_stmt_affected_rows() returns the number of rows affected by INSERT, UPDATE, or DELETE query. If the last query was invalid, this function will return -1.
The mysqli_stmt_affected_rows() function only works with queries which update a table. In order to return the number of rows from a SELECT query, use the mysqli_stmt_num_rows() function instead.
An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE/DELETE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query has returned an error.
Nota: If the number of affected rows is greater than maximal PHP int value, the number of affected rows will be returned as a string value.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
rows inserted: 17 |
(PHP 5)
mysqli_stmt_bind_param(no version information, might be only in CVS)
stmt->bind_param -- Binds variables to a prepared statement as parametersProcedural style:
bool mysqli_stmt_bind_param ( mysqli_stmt stmt, string types, mixed &var1 [, mixed &...] )Object oriented style (method):
class mysqli_stmt {mysqli_stmt_bind_param() is used to bind variables for the parameter markers in the SQL statement that was passed to mysqli_prepare(). The string types contains one or more characters which specify the types for the corresponding bind variables
Tabella 1. Type specification chars
Character | Description |
---|---|
i | corresponding variable has type integer |
d | corresponding variable has type double |
s | corresponding variable has type string |
b | corresponding variable is a blob and will be send in packages |
Nota: If data size of a variable exceeds max. allowed package size (max_allowed_package), you have to specify b in types and use mysqli_stmt_send_long_data() to send the data in packages.
The number of variables and length of string types must match the parameters in the statement.
mysqli_stmt_bind_result(), mysqli_stmt_execute(), mysqli_stmt_fetch(), mysqli_prepare(), mysqli_stmt_send_long_data(), mysqli_stmt_errno() e mysqli_stmt_error().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
1 Row inserted. 1 Row deleted. |
(PHP 5)
mysqli_stmt_bind_result(no version information, might be only in CVS)
stmt->bind_result -- Binds variables to a prepared statement for result storageProcedural style:
bool mysqli_stmt_bind_result ( mysqli_stmt stmt, mixed &var1 [, mixed &...] )Object oriented style (method):
class mysqli_stmt {mysqli_stmt_bind_result() is used to associate (bind) columns in the result set to variables. When mysqli_stmt_fetch() is called to fetch data, the MySQL client/server protocol places the data for the bound columns into the specified variables var1, ....
Nota: Note that all columns must be bound prior to calling mysqli_stmt_fetch(). Depending on column types bound variables can silently change to the corresponding PHP type.
A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time mysqli_stmt_fetch() is called.
mysqli_stmt_bind_param(), mysqli_stmt_execute(), mysqli_stmt_fetch(), mysqli_prepare(), mysqli_stmt_prepare(), mysqli_stmt_init(), mysqli_stmt_errno() e mysqli_stmt_error().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
AFG Afghanistan ALB Albania DZA Algeria ASM American Samoa AND Andorra |
(PHP 5)
mysqli_stmt_close(no version information, might be only in CVS)
mysqli_stmt->close -- Closes a prepared statementProcedural style:
bool mysqli_stmt_close ( mysqli_stmt stmt )Object oriented style (method):
class mysqli_stmt {Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle pointed to by stmt. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.
(PHP 5)
mysqli_stmt_data_seek(no version information, might be only in CVS)
stmt->data_seek -- Seeks to an arbitray row in statement result setProcedural style:
void mysqli_stmt_data_seek ( mysqli_stmt statement, int offset )Object oriented style (method):
class mysqli_stmt {The mysqli_stmt_data_seek() function seeks to an arbitrary result pointer specified by the offset in the statement result set represented by statement. The offset parameter must be between zero and the total number of rows minus one (0..mysqli_stmt_num_rows() - 1).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
City: Benin City Countrycode: NGA |
(PHP 5)
mysqli_stmt_errno(no version information, might be only in CVS)
mysqli_stmt->errno -- Returns the error code for the most recent statement callProcedural style :
int mysqli_stmt_errno ( mysqli_stmt stmt )Object oriented style (property):
class mysqli_stmt {For the statement specified by stmt, mysqli_stmt_errno() returns the error code for the most recently invoked statement function that can succeed or fail.
Nota: Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Error: 1146. |
(PHP 5)
mysqli_stmt_error(no version information, might be only in CVS)
mysqli_stmt->error -- Returns a string description for last statement errorProcedural style:
string mysqli_stmt_error ( mysqli_stmt stmt )Object oriented style (property):
class mysqli_stmt {For the statement specified by stmt, mysqli_stmt_error() returns a containing the error message for the most recently invoked statement function that can succeed or fail.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Error: Table 'world.myCountry' doesn't exist. |
(PHP 5)
mysqli_stmt_execute(no version information, might be only in CVS)
stmt->execute -- Executes a prepared QueryProcedural style:
bool mysqli_stmt_execute ( mysqli_stmt stmt )Object oriented style (method):
class mysqli_stmt {The mysqli_stmt_execute() function executes a query that has been previously prepared using the mysqli_prepare() function represented by the stmt object. When executed any parameter markers which exist will automatically be replaced with the appropiate data.
If the statement is UPDATE, DELETE, or INSERT, the total number of affected rows can be determined by using the mysqli_stmt_affected_rows() function. Likewise, if the query yields a result set the mysqli_stmt_fetch() function is used.
Nota: When using mysqli_stmt_execute(), the mysqli_stmt_fetch() function must be used to fetch the data prior to performing any additional queries.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Stuttgart (DEU,Baden-Wuerttemberg) Bordeaux (FRA,Aquitaine) |
(PHP 5)
mysqli_stmt_fetch(no version information, might be only in CVS)
stmt->fetch -- Fetch results from a prepared statement into the bound variablesProcedural style:
bool mysqli_stmt_fetch ( mysqli_stmt stmt )Object oriented style (method):
class mysqli_stmt {mysqli_stmt_fetch() fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result().
Nota: Note that all columns must be bound by the application before calling mysqli_stmt_fetch().
mysqli_prepare(), mysqli_stmt_errno(), mysqli_stmt_error() e mysqli_stmt_bind_result().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Rockford (USA) Tallahassee (USA) Salinas (USA) Santa Clarita (USA) Springfield (USA) |
(PHP 5)
mysqli_stmt_free_result(no version information, might be only in CVS)
stmt->free_result -- Frees stored result memory for the given statement handleProcedural style:
void mysqli_stmt_free_result ( mysqli_stmt stmt )Object oriented style (method):
class mysqli_stmt {The mysqli_stmt_free_result() function frees the result memory associated with the statement represented by the stmt parameter, which was allocated by mysqli_stmt_store_result().
(PHP 5)
mysqli_stmt_init(no version information, might be only in CVS)
mysqli->stmt_init -- Initializes a statement and returns an object for use with mysqli_stmt_prepareProcedural style :
mysqli_stmt mysqli_stmt_init ( mysqli link )Object oriented style (property):
class mysqli {Allocates and initializes a statement object suitable for mysqli_stmt_prepare().
Nota: Any subsequent calls to any mysqli_stmt function will fail until mysqli_stmt_prepare() was called.
(PHP 5)
mysqli_stmt_num_rows(no version information, might be only in CVS)
stmt->num_rows -- Return the number of rows in statements result setProcedural style :
int mysqli_stmt_num_rows ( mysqli_stmt stmt )Object oriented style (property):
class mysqli_stmt {Returns the number of rows in the result set. The use of mysqli_stmt_num_rows() depends on whether or not you used mysqli_stmt_store_result() to buffer the entire result set in the statement handle.
If you use mysqli_stmt_store_result(), mysqli_stmt_num_rows() may be called immediately.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Number of rows: 20. |
(PHP 5)
mysqli_stmt_param_count(no version information, might be only in CVS)
stmt->param_count -- Returns the number of parameter for the given statementProcedural style:
int mysqli_stmt_param_count ( mysqli_stmt stmt )Object oriented style (property):
class mysqli_stmt {mysqli_stmt_param_count() returns the number of parameter markers present in the prepared statement.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Statement has 2 markers. |
(PHP 5)
mysqli_stmt_prepare(no version information, might be only in CVS)
stmt->prepare -- Prepare a SQL statement for executionProcedure style:
bool mysqli_stmt_prepare ( mysqli_stmt stmt, string query )Object oriented style (method)
class mysqli_stmt {mysqli_stmt_prepare() prepares the SQL query pointed to by the null-terminated string query. The statement object has to be allocated by mysqli_stmt_init(). The query must consist of a single SQL statement.
Nota: You should not add a terminating semicolon or \g to the statement.
The parameter query can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.
Nota: The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.
However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.
The parameter markers must be bound to application variables using mysqli_stmt_bind_param() and/or mysqli_stmt_bind_result() before executing the statement or fetching rows.
mysqli_stmt_init(), mysqli_stmt_execute(), mysqli_stmt_fetch(), mysqli_stmt_bind_param(), mysqli_stmt_bind_result() e mysqli_stmt_close().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Amersfoort is in district Utrecht |
(PHP 5)
mysqli_stmt_reset(no version information, might be only in CVS)
stmt->reset -- Resets a prepared statementProcedural style:
bool mysqli_stmt_reset ( mysqli_stmt stmt )Object oriented style (method):
class mysqli_stmt {The mysqli_stmt_reset() resets a prepared statement on client and server to state after prepare. For now this is mainly used to reset data sent with mysqli_stmt_send_long_data().
Nota: To prepare a statement with another query use function mysqli_stmt_prepare().
Procedural style:
mysqli_result mysqli_stmt_result_metadata ( mysqli_stmt stmt )Object oriented style (method):
class mysqli_stmt {If a statement passed to mysqli_prepare() is one that produces a result set, mysqli_stmt_result_metadata() returns the result object that can be used to process the meta information such as total number of fields and individual field information.
Nota: This result set pointer can be passed as an argument to any of the field-based functions that process result set metadata, such as:
The result set structure should be freed when you are done with it, which you can do by passing it to mysqli_free_result()
Nota: The result set returned by mysqli_stmt_result_metadata() contains only metadata. It does not contain any row results. The rows are obtained by using the statement handle with mysqli_stmt_fetch().
mysqli_stmt_result_metadata() returns a result object or FALSE if an error occured.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
(PHP 5)
mysqli_stmt_send_long_data(no version information, might be only in CVS)
stmt->send_long_data -- Send data in blocksProcedural style:
bool mysqli_stmt_send_long_data ( mysqli_stmt stmt, int param_nr, string data )Object oriented style (method)
class mysqli_stmt {Allows to send parameter data to the server in pieces (or chunks), e.g. if the size of a blob exceeds the size of max_allowed_packet. This function can be called multiple times to send the parts of a character or binary data value for a column, which must be one of the TEXT or BLOB datatypes.
param_nr indicates which parameter to associate the data with. Parameters are numbered beginning with 0. data is a string containing data to be sent.
Returns a string containing the SQLSTATE error code for the most recently invoked prepared statement function that can succeed or fail. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see http://dev.mysql.com/doc/mysql/en/error-handling.html.
Nota: Note that not all MySQL errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.
Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Error: 42S02. |
(PHP 5)
mysqli_stmt_store_result(no version information, might be only in CVS)
mysqli_stmt->store_result -- Transfers a result set from a prepared statementProcedural style:
bool mysqli_stmt_store_result ( mysqli_stmt stmt )Object oriented style (method):
class mysqli_stmt {You must call mysqli_stmt_store_result() for every query that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN), and only if you want to buffer the complete result set by the client, so that the subsequent mysqli_stmt_fetch() call returns buffered data.
Nota: It is unnecessary to call mysqli_stmt_store_result() for other queries, but if you do, it will not harm or cause any notable performance in all cases. You can detect whether the query produced a result set by checking if mysqli_stmt_result_metadata() returns NULL.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Number of rows: 20. |
(PHP 5)
mysqli_store_result(no version information, might be only in CVS)
mysqli->store_result -- Transfers a result set from the last queryProcedural style:
mysqli_result mysqli_store_result ( mysqli link )Object oriented style (method):
class mysqli {Transfers the result set from the last query on the database connection represented by the link parameter to be used with the mysqli_data_seek() function.
Nota: Although it is always good practice to free the memory used by the result of a query using the mysqli_free_result() function, when transfering large result sets using the mysqli_store_result() this becomes particularly important.
Nota: mysqli_store_result() returns FALSE in case the query didn't return a result set (if the query was, for example an INSERT statement). This function also returns FALSE if the reading of the result set failed. You can check if you have got an error by checking if mysqli_error() doesn't return an empty string, if mysqli_errno() returns a non zero value, or if mysqli_field_count() returns a non zero value. Also possible reason for this function returning FALSE after successfull call to mysqli_query() can be too large result set (memory for it cannot be allocated). If mysqli_field_count() returns a non-zero value, the statement should have produced a non-empty result set.
(PHP 5)
mysqli_thread_id(no version information, might be only in CVS)
mysqli->thread_id -- Returns the thread ID for the current connectionProcedural style:
int mysqli_thread_id ( mysqli link )Object oriented style (property):
class mysqli {The mysqli_thread_id() function returns the thread ID for the current connection which can then be killed using the mysqli_kill() function. If the connection is lost and you reconnect with mysqli_ping(), the thread ID will be other. Therefore you should get the thread ID only when you need it.
Nota: The thread ID is assigned on a connection-by-connection basis. Hence, if the connection is broken and then re-established a new thread ID will be assigned.
To kill a running query you can use the SQL command KILL QUERY processid.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Error: MySQL server has gone away |
Procedural style:
bool mysqli_thread_safe ( void )mysqli_thread_safe() indicates whether the client library is compiled as thread-safe.
(PHP 5)
mysqli_use_result(no version information, might be only in CVS)
mysqli->use_result -- Initiate a result set retrievalProcedural style:
mysqli_result mysqli_use_result ( mysqli link )Object oriented style (method):
class mysqli {mysqli_use_result() is used to initiate the retrieval of a result set from the last query executed using the mysqli_real_query() function on the database connection specified by the link parameter. Either this or the mysqli_store_result() function must be called before the results of a query can be retrieved, and one or the other must be called to prevent the next query on that database connection from failing.
Nota: The mysqli_use_result() function does not transfer the entire result set from the database and hence cannot be used functions such as mysqli_data_seek() to move to a particular row within the set. To use this functionality, the result set must be stored using mysqli_store_result(). One should not use mysqli_use_result() if a lot of processing on the client side is performed, since this will tie up the server and prevent other threads from updating any tables from which the data is being fetched.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
my_user@localhost ----------------- Amersfoort Maastricht Dordrecht Leiden Haarlemmermeer |
(PHP 5)
mysqli_warning_count(no version information, might be only in CVS)
mysqli->warning_count -- Returns the number of warnings from the last query for the given linkProcedural style:
int mysqli_warning_count ( mysqli link )Object oriented style (property):
class mysqli {mysqli_warning_count() returns the number of warnings from the last query in the connection represented by the link parameter.
Nota: For retrieving warning messages you can use the SQL command SHOW WARNINGS [limit row_count].
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Warning (1264): Data truncated for column 'Name' at row 1 |
ncurses (new curses) is a free software emulation of curses in System V Rel 4.0 (and above). It uses terminfo format, supports pads, colors, multiple highlights, form characters and function key mapping. Because of the interactive nature of this library, it will be of little use for writing Web applications, but may be useful when writing scripts meant using PHP from the command line.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
Ncurses is available for the following platforms:
AIX
BeOS
Cygwin
Digital Unix (aka OSF1)
FreeBSD
GNU/Linux
HPUX
IRIX
OS/2
SCO OpenServer
Solaris
SunOS
You need the ncurses libraries and headerfiles. Download the latest version from the ftp://ftp.gnu.org/pub/gnu/ncurses/ or from an other GNU-Mirror.
To get these functions to work, you have to compile the CGI or CLI version of PHP with --with-ncurses[=DIR].
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Ncurses configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
ncurses.value | "42" | PHP_INI_ALL | |
ncurses.string | "foobar" | PHP_INI_ALL |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 2. ncurses color constants
constant | meaning |
---|---|
NCURSES_COLOR_BLACK | no color (black) |
NCURSES_COLOR_WHITE | white |
NCURSES_COLOR_RED | red - supported when terminal is in color mode |
NCURSES_COLOR_GREEN | green - supported when terminal is in color mode |
NCURSES_COLOR_YELLOW | yellow - supported when terminal is in color mode |
NCURSES_COLOR_BLUE | blue - supported when terminal is in color mode |
NCURSES_COLOR_CYAN | cyan - supported when terminal is in color mode |
NCURSES_COLOR_MAGENTA | magenta - supported when terminal is in color mode |
Tabella 3. ncurses key constants
constant | meaning |
---|---|
NCURSES_KEY_F0 - NCURSES_KEY_F64 | function keys F1 - F64 |
NCURSES_KEY_DOWN | down arrow |
NCURSES_KEY_UP | up arrow |
NCURSES_KEY_LEFT | left arrow |
NCURSES_KEY_RIGHT | right arrow |
NCURSES_KEY_HOME | home key (upward+left arrow) |
NCURSES_KEY_BACKSPACE | backspace |
NCURSES_KEY_DL | delete line |
NCURSES_KEY_IL | insert line |
NCURSES_KEY_DC | delete character |
NCURSES_KEY_IC | insert char or enter insert mode |
NCURSES_KEY_EIC | exit insert char mode |
NCURSES_KEY_CLEAR | clear screen |
NCURSES_KEY_EOS | clear to end of screen |
NCURSES_KEY_EOL | clear to end of line |
NCURSES_KEY_SF | scroll one line forward |
NCURSES_KEY_SR | scroll one line backward |
NCURSES_KEY_NPAGE | next page |
NCURSES_KEY_PPAGE | previous page |
NCURSES_KEY_STAB | set tab |
NCURSES_KEY_CTAB | clear tab |
NCURSES_KEY_CATAB | clear all tabs |
NCURSES_KEY_SRESET | soft (partial) reset |
NCURSES_KEY_RESET | reset or hard reset |
NCURSES_KEY_PRINT | |
NCURSES_KEY_LL | lower left |
NCURSES_KEY_A1 | upper left of keypad |
NCURSES_KEY_A3 | upper right of keypad |
NCURSES_KEY_B2 | center of keypad |
NCURSES_KEY_C1 | lower left of keypad |
NCURSES_KEY_C3 | lower right of keypad |
NCURSES_KEY_BTAB | back tab |
NCURSES_KEY_BEG | beginning |
NCURSES_KEY_CANCEL | cancel |
NCURSES_KEY_CLOSE | close |
NCURSES_KEY_COMMAND | cmd (command) |
NCURSES_KEY_COPY | copy |
NCURSES_KEY_CREATE | create |
NCURSES_KEY_END | end |
NCURSES_KEY_EXIT | exit |
NCURSES_KEY_FIND | find |
NCURSES_KEY_HELP | help |
NCURSES_KEY_MARK | mark |
NCURSES_KEY_MESSAGE | message |
NCURSES_KEY_MOVE | move |
NCURSES_KEY_NEXT | next |
NCURSES_KEY_OPEN | open |
NCURSES_KEY_OPTIONS | options |
NCURSES_KEY_PREVIOUS | previous |
NCURSES_KEY_REDO | redo |
NCURSES_KEY_REFERENCE | ref (reference) |
NCURSES_KEY_REFRESH | refresh |
NCURSES_KEY_REPLACE | replace |
NCURSES_KEY_RESTART | restart |
NCURSES_KEY_RESUME | resume |
NCURSES_KEY_SAVE | save |
NCURSES_KEY_SBEG | shiftet beg (beginning) |
NCURSES_KEY_SCANCEL | shifted cancel |
NCURSES_KEY_SCOMMAND | shifted command |
NCURSES_KEY_SCOPY | shifted copy |
NCURSES_KEY_SCREATE | shifted create |
NCURSES_KEY_SDC | shifted delete char |
NCURSES_KEY_SDL | shifted delete line |
NCURSES_KEY_SELECT | select |
NCURSES_KEY_SEND | shifted end |
NCURSES_KEY_SEOL | shifted end of line |
NCURSES_KEY_SEXIT | shifted exit |
NCURSES_KEY_SFIND | shifted find |
NCURSES_KEY_SHELP | shifted help |
NCURSES_KEY_SHOME | shifted home |
NCURSES_KEY_SIC | shifted input |
NCURSES_KEY_SLEFT | shifted left arrow |
NCURSES_KEY_SMESSAGE | shifted message |
NCURSES_KEY_SMOVE | shifted move |
NCURSES_KEY_SNEXT | shifted next |
NCURSES_KEY_SOPTIONS | shifted options |
NCURSES_KEY_SPREVIOUS | shifted previous |
NCURSES_KEY_SPRINT | shifted print |
NCURSES_KEY_SREDO | shifted redo |
NCURSES_KEY_SREPLACE | shifted replace |
NCURSES_KEY_SRIGHT | shifted right arrow |
NCURSES_KEY_SRSUME | shifted resume |
NCURSES_KEY_SSAVE | shifted save |
NCURSES_KEY_SSUSPEND | shifted suspend |
NCURSES_KEY_UNDO | undo |
NCURSES_KEY_MOUSE | mouse event has occurred |
NCURSES_KEY_MAX | maximum key value |
Tabella 4. mouse constants
Constant | meaning |
---|---|
NCURSES_BUTTON1_RELEASED - NCURSES_BUTTON4_RELEASED | button (1-4) released |
NCURSES_BUTTON1_PRESSED - NCURSES_BUTTON4_PRESSED | button (1-4) pressed |
NCURSES_BUTTON1_CLICKED - NCURSES_BUTTON4_CLICKED | button (1-4) clicked |
NCURSES_BUTTON1_DOUBLE_CLICKED - NCURSES_BUTTON4_DOUBLE_CLICKED | button (1-4) double clicked |
NCURSES_BUTTON1_TRIPLE_CLICKED - NCURSES_BUTTON4_TRIPLE_CLICKED | button (1-4) triple clicked |
NCURSES_BUTTON_CTRL | ctrl pressed during click |
NCURSES_BUTTON_SHIFT | shift pressed during click |
NCURSES_BUTTON_ALT | alt pressed during click |
NCURSES_ALL_MOUSE_EVENTS | report all mouse events |
NCURSES_REPORT_MOUSE_POSITION | report mouse position |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_addchnstr -- Add attributed string with specified length at current positionAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_beep() sends an audible alert (bell) and if its not possible flashes the screen. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also ncurses_flash()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_border -- Draw a border around the screen using attributed charactersAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_border() draws the specified lines and corners around the main window. Each parameter expects 0 to draw a line and 1 to skip it. The corners are top left, top right, bottom left and bottom right.
Use ncurses_wborder() for borders around subwindows!
See also ncurses_wborder().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The function ncurses_can_change_color() returns TRUE or FALSE, depending on whether the terminal has color capabilities and whether the programmer can change the colors.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_cbreak() disables line buffering and character processing (interrupt and flow control characters are unaffected), making characters typed by the user immediately available to the program.
ncurses_cbreak() returns TRUE or NCURSES_ERR if any error occurred.
See also: ncurses_nocbreak()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_clear() clears the screen completely without setting blanks. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Note: ncurses_clear() clears the screen without setting blanks, which have the current background rendition. To clear screen with blanks, use ncurses_erase().
See also ncurses_erase().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_clrtobot() erases all lines from cursor to end of screen and creates blanks. Blanks created by ncurses_clrtobot() have the current background rendition. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also ncurses_clear(), and ncurses_clrtoeol()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_clrtoeol() erases the current line from cursor position to the end. Blanks created by ncurses_clrtoeol() have the current background rendition. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also ncurses_clear(), and ncurses_clrtobot()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_def_prog_mode() saves the current terminal modes for program (in curses) for use by ncurses_reset_prog_mode(). Returns FALSE on success, otherwise TRUE.
See also: ncurses_reset_prog_mode()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_def_shell_mode() saves the current terminal modes for shell (not in curses) for use by ncurses_reset_shell_mode(). Returns FALSE on success, otherwise TRUE.
See also: ncurses_reset_shell_mode()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
ncurses_del_panel -- Remove panel from the stack and delete it (but not the associated window)
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_delch -- Delete character at current position, move rest of line leftAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_delch() deletes the character under the cursor. All characters to the right of the cursor on the same line are moved to the left one position and the last character on the line is filled with a blank. The cursor position does not change. Returns FALSE on success, otherwise TRUE.
See also: ncurses_deleteln()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_deleteln() deletes the current line under cursorposition. All lines below the current line are moved up one line. The bottom line of window is cleared. Cursor position does not change. Returns FALSE on success, otherwise TRUE.
See also: ncurses_delch()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_doupdate() compares the virtual screen to the physical screen and updates the physical screen. This way is more effective than using multiple refresh calls. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_echo() enables echo mode. All characters typed by user are echoed by ncurses_getch(). Returns FALSE on success, TRUE if any error occurred.
To disable echo mode use ncurses_noecho().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_erase() fills the terminal screen with blanks. Created blanks have the current background rendition, set by ncurses_bkgd(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also ncurses_bkgd(), and ncurses_clear()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_erasechar() returns the current erase char character.
See also: ncurses_killchar()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_flash() flashes the screen, and if its not possible, sends an audible alert (bell). Returns FALSE on success, otherwise TRUE.
See also: ncurses_beep()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The ncurses_flushinp() throws away any typeahead that has been typed and has not yet been read by your program. Returns FALSE on success, otherwise TRUE.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_getmaxyx() puts the horizontal and vertical size of the window window into the given variables y and x. Variables must be passed as reference, so they are updated when the user changes terminal size.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_getmouse() reads mouse event out of queue. Function ncurses_getmouse() will return ;FALSE if a mouse event is actually visible in the given window, otherwise it will return TRUE. Event options will be delivered in parameter mevent, which has to be an array, passed by reference (see example below). On success an associative array with following keys will be delivered:
"id" : Id to distinguish multiple devices
"x" : screen relative x-position in character cells
"y" : screen relative y-position in character cells
"z" : currently not supported
"mmask" : Mouse action
See also ncurses_ungetmouse()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_has_colors() returns TRUE or FALSE depending on whether the terminal has color capacities.
See also: ncurses_can_change_color()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_has_ic() checks terminals insert- and delete capabilities. It returns TRUE when terminal has insert/delete-capabilities, otherwise FALSE.
See also: ncurses_has_il()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_has_il() checks terminals insert- and delete-line-capabilities. It returns TRUE when terminal has insert/delete-line capabilities, otherwise FALSE
See also: ncurses_has_ic()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_hline -- Draw a horizontal line at current position using an attributed character and max. n characters longAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_inch() returns the character from the current position.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_init() initializes the ncurses interface and must be used before any other ncurses function.
(PHP 4 >= 4.1.0, PHP 5)
ncurses_insch -- Insert character moving rest of line including character at current positionAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_insdelln -- Insert lines before current line scrolling down (negative numbers delete and scroll up)Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_insertln() inserts a new line above the current line. The bottom line will be lost.
(PHP 4 >= 4.2.0, PHP 5)
ncurses_insstr -- Insert string at current position, moving rest of line rightAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_instr() returns the number of characters read from the current character position until end of line. buffer contains the characters. Attributes are stripped from the characters.
(PHP 4 >= 4.1.0, PHP 5)
ncurses_isendwin -- Ncurses is in endwin mode, normal screen output may be performedAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_isendwin() returns TRUE, if ncurses_endwin() has been called without any subsequent calls to ncurses_wrefresh(), otherwise FALSE.
See also ncurses_endwin() and ncurses_wrefresh().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_killchar() returns the current line kill character.
See also: ncurses_erasechar()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_longname() returns a verbose description of the terminal. The description is truncated to 128 characters. On Error ncurses_longname() returns NULL.
See also: ncurses_termname()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Function ncurses_mousemask() will set mouse events to be reported. By default no mouse events will be reported. The function ncurses_mousemask() will return a mask to indicated which of the in parameter newmask specified mouse events can be reported. On complete failure, it returns 0. In parameter oldmask, which is passed by reference ncurses_mousemask() returns the previous value of mouse event mask. Mouse events are represented by NCURSES_KEY_MOUSE in the ncurses_wgetch() input stream. To read the event data and pop the event of queue, call ncurses_getmouse().
As a side effect, setting a zero mousemask in newmask turns off the mouse pointer. Setting a non zero value turns mouse pointer on.
mouse mask options can be set with the following predefined constants:
NCURSES_BUTTON1_PRESSED
NCURSES_BUTTON1_RELEASED
NCURSES_BUTTON1_CLICKED
NCURSES_BUTTON1_DOUBLE_CLICKED
NCURSES_BUTTON1_TRIPLE_CLICKED
NCURSES_BUTTON2_PRESSED
NCURSES_BUTTON2_RELEASED
NCURSES_BUTTON2_CLICKED
NCURSES_BUTTON2_DOUBLE_CLICKED
NCURSES_BUTTON2_TRIPLE_CLICKED
NCURSES_BUTTON3_PRESSED
NCURSES_BUTTON3_RELEASED
NCURSES_BUTTON3_CLICKED
NCURSES_BUTTON3_DOUBLE_CLICKED
NCURSES_BUTTON3_TRIPLE_CLICKED
NCURSES_BUTTON4_PRESSED
NCURSES_BUTTON4_RELEASED
NCURSES_BUTTON4_CLICKED
NCURSES_BUTTON4_DOUBLE_CLICKED
NCURSES_BUTTON4_TRIPLE_CLICKED
NCURSES_BUTTON_SHIFT>
NCURSES_BUTTON_CTRL
NCURSES_BUTTON_ALT
NCURSES_ALL_MOUSE_EVENTS
NCURSES_REPORT_MOUSE_POSITION
See also ncurses_getmouse(), ncurses_ungetmouse() and ncurese_getch().
(PHP 4 >= 4.3.0, PHP 5)
ncurses_move_panel -- Moves a panel so that its upper-left corner is at [startx, starty]
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_mvaddchnstr -- Move position and add attributed string with specified lengthAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_mvdelch -- Move position and delete character, shift rest of line leftAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_mvhline -- Set new position and draw a horizontal line using an attributed character and max. n characters longAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
ncurses_mvvline -- Set new position and draw a vertical line using an attributed character and max. n characters longAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_newwin() creates a new window to draw elements in. Windows can be positioned using x, y, rows and cols. When creating additional windows, remember to use ncurses_getmaxyx() to check for available space, as terminal size is individual and may vary. The return value is a resource ID used to differ between multiple windows.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_nocbreak() routine returns terminal to normal (cooked) mode. Initially the terminal may or may not in cbreak mode as the mode is inherited. Therefore a program should call ncurses_cbreak() and ncurses_nocbreak() explicitly. Returns TRUE if any error occurred, otherwise FALSE.
See also: ncurses_cbreak()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_noecho() prevents echoing of user typed characters. Returns TRUE if any error occurred, otherwise FALSE.
See also: ncurses_echo(), ncurses_getch()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_noraw() switches the terminal out of raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal. Returns TRUE if any error occurred, otherwise FALSE.
See also: ncurses_raw(), ncurses_cbreak(), ncurses_nocbreak()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
If panel is null, returns the bottom panel in the stack.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
If panel is null, returns the top panel in the stack.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_raw() places the terminal in raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal. Returns TRUE if any error occurred, otherwise FALSE.
See also: ncurses_noraw(), ncurses_cbreak(), ncurses_nocbreak()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Function ncurses_resetty() restores the terminal state, which was previously saved by calling ncurses_savetty(). This function always returns FALSE.
See also: ncurses_savetty()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Function ncurses_savetty() saves the current terminal state. The saved terminal state can be restored with function ncurses_resetty(). ncurses_savetty() always returns FALSE.
See also: ncurses_resetty()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_scrl -- Scroll window content up or down without changing current positionAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
ncurses_show_panel -- Places an invisible panel on top of the stack, making it visible
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_slk_attr() returns the current soft label key attribute. On error returns TRUE, otherwise FALSE.
(PHP 4 >= 4.1.0, PHP 5)
ncurses_slk_attroff -- Turn off the given attributes for soft function-key labelsAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_slk_attron -- Turn on the given attributes for soft function-key labelsAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The function ncurses_slk_clear() clears soft label keys from screen. Returns TRUE on error, otherwise FALSE.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Function ncurses_slk_init() must be called before ncurses_initscr() or ncurses_newterm() is called. If ncurses_initscr() eventually uses a line from stdscr to emulate the soft labels, then format determines how the labels are arranged of the screen. Setting format to 0 indicates a 3-2-3 arrangement of the labels, 1 indicates a 4-4 arrangement and 2 indicates the PC like 4-4-4 mode, but in addition an index line will be created.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_slk_refresh() copies soft label keys from virtual screen to physical screen. Returns TRUE on error, otherwise FALSE.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The function ncurses_slk_restore() restores the soft label keys after ncurses_slk_clear() has been performed.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The ncurses_slk_touch() function forces all the soft labels to be output the next time a ncurses_slk_noutrefresh() is performed.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_termattrs -- Returns a logical OR of all attribute flags supported by terminalAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_termname() returns terminals shortname. The shortname is truncated to 14 characters. On error ncurses_termname() returns NULL.
See also: ncurses_longname()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_getmouse() pushes a KEY_MOUSE event onto the unput queue and associates with this event the given state sata and screen-relative character cell coordinates, specified in mevent. Event options will be specified in associative array mevent:
"id" : Id to distinguish multiple devices
"x" : screen relative x-position in character cells
"y" : screen relative y-position in character cells
"z" : currently not supported
"mmask" : Mouse action
ncurses_ungetmouse() returns FALSE on success, otherwise TRUE.
See also: ncurses_getmouse()
(PHP 4 >= 4.3.0, PHP 5)
ncurses_update_panels -- Refreshes the virtual screen to reflect the relations between panels in the stack
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_use_env -- Control use of environment information about terminal sizeAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_use_extended_names -- Control use of extended names in terminfo descriptionsAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_vidattr -- Display the string on the terminal in the video attribute modeAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_vline -- Draw a vertical line at current position using an attributed character and max. n characters longAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
ncurses_waddch -- Adds character at current position in a window and advance cursor
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
ncurses_wborder -- Draws a border around the window using attributed charactersAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_wborder() draws the specified lines and corners around the passed window window. Each parameter expects 0 to draw a line and 1 to skip it. The corners are top left, top right, bottom left and bottom right.
Use ncurses_border() for borders around the main window.
See also ncurses_border().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
ncurses_whline -- Draws a horizontal line in a window at current position using an attributed character and max. n characters long
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Per maggiori dettagli e definizioni delle costanti PHP_INI_* vedere ini_set().
Breve descrizione dei parametri di configurazione.
Inposta se definire o meno le varie varaibili di syslog (quali $LOG_PID, $LOG_CRON, etc.). Disattivarle ha effetti positivi sulle performance. A runtime, queste variabili possono essere definit richiamando define_syslog_variables().
Le costanti qui elencate sono sempre disponibili in quanto parte del core di PHP.
Tabella 2. Opzioni openlog()
Costante | Descrizione |
---|---|
LOG_CONS | Se si verifica un errore nella scrittura nel log di sistema scrive direttamente sulla console. |
LOG_NDELAY | Apre immediatamente la connessione con il log |
LOG_ODELAY | (default) attende ad aprire la connessione fino a quando non vi è un messaggio da registrare. |
LOG_NOWAIT | |
LOG_PERROR | Scrive il messaggio di log anche nello standard error |
LOG_PID | Include anche il PID in ciascun messaggio |
Tabella 3. Tools openlog()
Costante | Descrizione |
---|---|
LOG_AUTH | Messaggio di sicurezza/autorizzazione (utilizzare LOG_AUTHPRIV nei sistemi in cui questa costante è definita) |
LOG_AUTHPRIV | Messaggi di sicurezza/autorizzazione (privati) |
LOG_CRON | Demone dell'ora (cron ed at) |
LOG_DAEMON | Altri demoni di sistema |
LOG_KERN | Messaggi del kernel |
LOG_LOCAL0 ... LOG_LOCAL7 | Riservato per utilizzi locali, questi non sono dipsonibili in Windows |
LOG_LPR | Sottosistema della stampante |
LOG_MAIL | Sottosistema di posta |
LOG_NEWS | Sottosistema USENET news |
LOG_SYSLOG | Messaggi generati internamente da syslogd |
LOG_USER | Messaggi utente generici |
LOG_UUCP | Sottosistema UUCP |
Tabella 4. Priorità (in ordine decrescente) di syslog()
Costante | Descrizione |
---|---|
LOG_EMERG | Sistema inutilizzabile |
LOG_ALERT | Azioni devono essere intraprese immediatamente |
LOG_CRIT | Condizioni critiche |
LOG_ERR | Condizioni di errore |
LOG_WARNING | Condizioni di attenzione |
LOG_NOTICE | Situazione normale, ma significativa |
LOG_INFO | Messaggio informativo |
LOG_DEBUG | Messaggio di debug |
Tabella 5. Parametri dns_get_record()
Costante | Descrizione |
---|---|
DNS_A | Risorsa con indirizzo IPv4 |
DNS_MX | Mail Exchanger Resource |
DNS_CNAME | Alias (Canonical Name) Resource |
DNS_NS | Authoritative Name Server Resource |
DNS_PTR | Pointer Resource |
DNS_HINFO | Host Info Resource (Vedere la pagina IANA Operating System Names per il significato di questi valori) |
DNS_SOA | Start of Authority Resource |
DNS_TXT | Text Resource |
DNS_ANY | Any Resource Record. In molti sistemi questo restituisce tutti i record, tuttavia non si dovrebbe farne affidamento per utilzzi critici. Piuttosto utilizzare DNS_ALL. |
DNS_AAAA | IPv6 Address Resource |
DNS_ALL | Interroga in modo iterativo il DNS alla ricerca di ogni tipo di record disponibile. |
(PHP 3, PHP 4, PHP 5)
checkdnsrr -- Controlla i record DNS relativi ad un host Internet o indirizzo IPCerca i record DNS del tipo type corrispondenti a host. Restituisce vero se dei records sono trovati; falso se nessun record viene trovato o in caso di errore.
type può essere uno dei seguenti: A, MX, NS, SOA, PTR, CNAME, oppure ANY. Il default è MX.
Host può essere sia l'indirizzo IP in notazione decimale o il nome dell'host.
Nota: Questa funzione non è implementata su piattaforme Windows
Vedere anche getmxrr(), gethostbyaddr(), gethostbyname(), gethostbynamel() e la man page named(8).
closelog() chiude il descrittore usato per scrivere al logger di sistema. L'uso di closelog() è facoltativo.
Vedere anche define_syslog_variables(), syslog() e openlog().
Disattiva il debugger interno PHP. Il debugger è ancora in fase di sviluppo.
Attiva il debugger interno PHP, connettendolo ad indirizzo. Il debugger è in fase di sviluppo.
Inizializza tutte le costanti usate nelle funzioni del syslog.
Vedere anche openlog(), syslog() e closelog().
Check DNS records corresponding to a given Internet host name or IP address
Get MX records corresponding to a given Internet host name.
Nota: This function is not implemented on Windows platforms, nor does it (currently) work on *BSD systems. Try the PEAR class Net_DNS.
This function returns an array of associative arrays. Each associative array contains at minimum the following keys:
Tabella 1. Basic DNS attributes
Attribute | Meaning |
---|---|
host | The record in the DNS namespace to which the rest of the associated data refers. |
class | dns_get_record() only returns Internet class records and as such this parameter will always return IN. |
type | String containing the record type. Additional attributes will also be contained in the resulting array dependant on the value of type. See table below. |
ttl | Time To Live remaining for this record. This will not equal the record's original ttl, but will rather equal the original ttl minus whatever length of time has passed since the authoritative name server was queried. |
hostname should be a valid DNS hostname such as "www.example.com". Reverse lookups can be generated using in-addr.arpa notation, but gethostbyaddr() is more suitable for the majority of reverse lookups.
By default, dns_get_record() will search for any resource records associated with hostname. To limit the query, specify the optional type parameter. type may be any one of the following: DNS_A, DNS_CNAME, DNS_HINFO, DNS_MX, DNS_NS, DNS_PTR, DNS_SOA, DNS_TXT, DNS_AAAA, DNS_SRV, DNS_NAPTR, DNS_A6, DNS_ALL or DNS_ANY. The default is DNS_ANY.
Nota: Because of eccentricities in the performance of libresolv between platforms, DNS_ANY will not always return every record, the slower DNS_ALL will collect all records more reliably.
The optional third and fourth arguments to this function, authns and addtl are passed by reference and, if given, will be populated with Resource Records for the Authoritative Name Servers, and any Additional Records respectively. See the example below.
Tabella 2. Other keys in associative arrays dependant on 'type'
Type | Extra Columns |
---|---|
A | ip: An IPv4 addresses in dotted decimal notation. |
MX | pri: Priority of mail exchanger. Lower numbers indicate greater priority. target: FQDN of the mail exchanger. See also dns_get_mx(). |
CNAME | target: FQDN of location in DNS namespace to which the record is aliased. |
NS | target: FQDN of the name server which is authoritative for this hostname. |
PTR | target: Location within the DNS namespace to which this record points. |
TXT | txt: Arbitrary string data associated with this record. |
HINFO | cpu: IANA number designating the CPU of the machine referenced by this record. os: IANA number designating the Operating System on the machine referenced by this record. See IANA's Operating System Names for the meaning of these values. |
SOA | mname: FQDN of the machine from which the resource records originated. rname: Email address of the administrative contain for this domain. serial: Serial # of this revision of the requested domain. refresh: Refresh interval (seconds) secondary name servers should use when updating remote copies of this domain. retry: Length of time (seconds) to wait after a failed refresh before making a second attempt. expire: Maximum length of time (seconds) a secondary DNS server should retain remote copies of the zone data without a successful refresh before discarding. minimum-ttl: Minimum length of time (seconds) a client can continue to use a DNS resolution before it should request a new resolution from the server. Can be overridden by individual resource records. |
AAAA | ipv6: IPv6 address |
A6(PHP >= 5.1.0) | masklen: Length (in bits) to inherit from the target specified by chain. ipv6: Address for this specific record to merge with chain. chain: Parent record to merge with ipv6 data. |
SRV | pri: (Priority) lowest priorities should be used first. weight: Ranking to weight which of commonly prioritized targets should be chosen at random. target and port: hostname and port where the requested service can be found. For additional information see: RFC 2782 |
NAPTR | order and pref: Equivalent to pri and weight above. flags, services, regex, and replacement: Parameters as defined by RFC 2915. |
Nota: Per DNS standards, email addresses are given in user.host format (for example: hostmaster.example.com as opposed to hostmaster@example.com), be sure to check this value and modify if necessary before using it with a functions such as mail().
Esempio 1. Using dns_get_record()
Produces output similar to the following:
|
Since it's very common to want the IP address of a mail server once the MX record has been resolved, dns_get_record() also returns an array in addtl which contains associate records. authns is returned as well containing a list of authoritative name servers.
Esempio 2. Using dns_get_record() and DNS_ANY
Produces output similar to the following:
|
See also dns_get_mx(), and dns_check_record()
(PHP 3, PHP 4, PHP 5)
fsockopen -- Apre una connessione a un socket appartenente a un dominio Internet o UnixInizializza una connessione nel dominio Internet (AF_INET, usando TCP o UDP) o Unix (AF_UNIX). Per il dominio Internet, apre una connessione a un socket TCP verso l' hostname sulla porta port. hostname può essere in questo caso, sia un fully qualified domain name o un indirizzo IP. Per le connessioni UDP, è necessario specificare esplicitamente il protocollo, usando: 'udp://' come prefisso di hostname. Per il dominio Unix, hostname viene utilizzato come percorso verso il socket, in questo caso, porta deve essere impostato a 0. Il parametro opzionale timeout può essere usato per impostare un timeout in secondi per la chiamata di sistema connect.
A partire da PHP 4.3.0, se si è compilato con il supporto OpenSSL, si può prefissare hostname con 'ssl://' oppure 'tls://' per utilizzare una connessione client SSL o TLS su una connessione TCP/IP per connettersi all'host remoto.
fsockopen() restituisce un puntatore a file che può essere usato nelle altre funzioni orientate ai file (come fgets(), fgetss(), fputs(), fclose() e feof()).
Se la chiamata non ha successo, viene restituito FALSE e se gli argomenti opzionali errno e errstr sono presenti, vengono impostati a indicare l'errore a livello di sistema che è avvenuto nella chiamata alla funzione connect() del sistema operativo. Se il valore di errno restituito è 0 e la funzione restituisce FALSE, è un'indicazione che l'errore è avvenuto prima della chiamata di connect(). Questo è molto probabilmente legato ad un problema di inizializzazione del socket. Si noti che gli argomenti errno e errstr verranno sempre passati by reference.
A seconda dell'ambiente operativo, il dominio Unix o l'opzionale timeout della connect potrebbero non essere disponibili.
Il socket viene aperto di default in modo blocking. Si può passare al modo non-blocking usando socket_set_blocking().
Nota: Il parametro timeout è stato introdotto nel PHP 3.0.9 e il supporto UDP è stato aggiunto nel PHP 4.
Restituisce l'hostname dell'host Internet specificato da indirizzo_ip. Se occorre un errore, restituisce indirizzo_ip.
Vedere anche gethostbyname().
(PHP 3, PHP 4, PHP 5)
gethostbyname -- Ottiene l'indirizzo IP corrispondente a un dato hostname InternetRestituisce l'indirizzo IP dell'host Internet specificato da hostname.
Vedere anche gethostbyaddr().
(PHP 3, PHP 4, PHP 5)
gethostbynamel -- Ottiene la lista degli indirizzi IP corrispondenti a un dato hostname InternetRestituisce una lista di indirizzi IP che risolvono nei confronti dell'host Internet specificato da hostname.
Vedere anche gethostbyname(), gethostbyaddr(), checkdnsrr(), getmxrr() e la pagina man named(8).
Cerca nel DNS i record MX corrispondenti a hostname. Restituisce TRUE se ne vengono trovati. Restituisce FALSE se non ne vengono trovati o se avviene un errore.
La lista di record MX trovati viene messa nell'array mxhosts. Se viene indicato l'array weight, esso viene riempito con le informazioni ottenute sui vari pesi.
Vedere anche checkdnsrr(), gethostbyname(), gethostbynamel(), gethostbyaddr()e la pagina man named(8).
getprotobyname() restituisce il numero del protocollo associato al protocollo nome come in /etc/protocols.
Vedere anche: getprotobynumber().
getprotobynumber() restituisce il nome del protocollo associato al protocollo numero come in /etc/protocols.
Vedere anche: getprotobyname().
(PHP 4, PHP 5)
getservbyname -- Ottiene il numero di porta associato ad un servizio Internet e ad un protocollogetservbyname() restituisce la porta Internet corrispondente a servizio per il protocollo specificato come in /etc/services. protocollo può essere sia "tcp" che "udp" (scritti in minuscolo). Restituisce FALSE se service o protocol non sono trovati.
Per avere la lista completa dei numeri di porta vedere: http://www.iana.org/assignments/port-numbers.
Vedere anche: getservbyport().
(PHP 4, PHP 5)
getservbyport -- Ottiene il servizio Internet corrispondente ad una porta e ad un protocollogetservbyport() restituisce il servizio Internet associato a porta relativamente al protocollo specificato come in /etc/services. protocollo può essere sia "tcp" che "udp" (scritti in minuscolo).
Vedere anche: getservbyname().
(PHP 5 >= 5.1.0RC1)
inet_ntop -- Converts a packed internet address to a human readable representationThis function converts a 32bit IPv4, or 128bit IPv6 address (if PHP was built with IPv6 support enabled) into an address family appropriate string representation. Returns FALSE on failure.
Nota: Questa funzione non è implementata su piattaforme Windows
See also long2ip(), inet_pton(), and ip2long().
(PHP 5 >= 5.1.0RC1)
inet_pton -- Converts a human readable IP address to its packed in_addr representationThis function converts a human readable IPv4 or IPv6 address (if PHP was built with IPv6 support enabled) into an address family appropriate 32bit or 128bit binary structure.
Nota: Questa funzione non è implementata su piattaforme Windows
See also ip2long(), inet_ntop(), and long2ip().
(PHP 4, PHP 5)
ip2long -- Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address. Converte una stringa contenente un indirizzo di rete del Protocollo Internet (IPv4) in un indirizzo espresso come tipo di dato int.La funzione ip2long() genera un indirizzo di rete Internet IPv4 a partire dalla rappresentazione in formato standard (stringa separata da punti).
Nota: Poiché il tipo di dato integer in PHP è signed e molti indirizzi IP risulterebbero essere interi negativi, è necessario usare il formattatore "%u" della funzione sprintf() e printf() per ottenere la rappresentazione in stringa dell'indirizzo IP in modo nsigned.
Vedere anche: long2ip()
(PHP 4, PHP 5)
long2ip -- Converte un indirizzo di rete del Protocollo Internet (IPv4) in una stringa contenente un indirizzo espresso secondo la notazione standard di Internet.La funzione long2ip() genera un indirizzo Internet in formato separato da punti (es.: aaa.bbb.ccc.ddd) a partire dalla rappresentazione propria.
Vedere anche: ip2long()
openlog() apre una connessione al logger di sistema per un programma. La stringa ident viene aggiunta a ogni messaggio. Valori per option e facility sono dati di seguito. L'argomento option viene usato per indicare quali opzioni di loggin verranno usate durante la generazione di un messaggio di log. L'argomento facility viene usato per specificare quale tipo di programma sta loggando il messaggio. Questo permette di specificare (nella comfigurazione del syslog della macchina) come trattare i messaggi provenienti dalle diverse facility. L'uso di openlog() è opzionale. Viene chiamato automaticamente da syslog() se necessario, in tal caso ident sarà di default FALSE.
Tabella 1. Opzioni di openlog()
Costante | Descrizione |
---|---|
LOG_CONS | se si verifica un errore durante l'invio dei dati al logger di sistema, scrive direttamente sulla console di sistema |
LOG_NDELAY | apre immediatamente una connessione al logger |
LOG_ODELAY | (default) ritarda l'apertura della connessione fino a quando non viene loggato il primo messaggio |
LOG_PERROR | stampa un messaggio di log anche su standard error |
LOG_PID | include il PID in ciascun messaggio |
Tabella 2. Facility di openlog()
Costante | Descrizione |
---|---|
LOG_AUTH | messaggi di sicurezza/autorizzazione (usa LOG_AUTHPRIV nei sistemi dove è definita quella costante) |
LOG_AUTHPRIV | messaggi di sicurezza/autorizzazione (private) |
LOG_CRON | clock daemon (cron e at) |
LOG_DAEMON | altri demoni di sistema |
LOG_KERN | messaggi del kernel |
LOG_LOCAL0 ... LOG_LOCAL7 | riservato per il locale |
LOG_LPR | sottosistema line printer |
LOG_MAIL | sottosistema mail |
LOG_NEWS | sottosistema news di USENET |
LOG_SYSLOG | messaggi generati internamente da syslogd |
LOG_USER | messaggi generici user-level |
LOG_UUCP | sottosistema UUCP |
Vedere anche define_syslog_variables(), syslog() e closelog().
(PHP 3 >= 3.0.7, PHP 4, PHP 5)
pfsockopen -- Apre una connessione persistente Internet o di tipo domain socket UnixQuesta funzione si comporta esattamente come fsockopen() con la differenza che la connessione non viene chiusa dopo che lo script ha finito la sua esecuzione. È la versione persistente di fsockopen().
syslog() genera un messaggio di log che viene distribuito dal logger di sistema. priorità è la combinazione della facility e del livello, valori utilizzabili sono riportati nella prossima sezione. L'argomento rimanente è il messaggio da inviare, eccetto i due caratteri %m che vengono sostituiti dalla stringa del messaggio di errore (strerror) corrispondente all'attuale valore di errno.
Tabella 1. Priorità syslog() (in ordine discendente)
Costante | Descrizione |
---|---|
LOG_EMERG | sistema non utilizzabile |
LOG_ALERT | azione da intraprendere immediatamente |
LOG_CRIT | condizioni critiche |
LOG_ERR | condizioni di errore |
LOG_WARNING | condizioni di attenzione |
LOG_NOTICE | condizione normale, ma significativa |
LOG_INFO | messaggio di informazione |
LOG_DEBUG | messaggio a livello di debug |
Esempio 1. Uso di syslog()
|
Su Windows NT, il servizio syslog è emulato usando Event Log.
Vedere anche define_syslog_variables(), openlog() e closelog().
This is a PHP language extension for RedHat Newt library, a terminal-based window and widget library for writing applications with user friendly interface. Once this extension is enabled in PHP it will provide the use of Newt widgets, such as windows, buttons, checkboxes, radiobuttons, labels, editboxes, scrolls, textareas, scales, etc. Use of this extension if very similar to the original Newt API of C programming language.
This module uses the functions of the RedHat Newt library. You need libnewt version >= 0.51.0.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/newt.
In PHP 4 this PECL extensions source can be found in the ext/ directory within the PHP source or at the PECL link above. In order to use these functions you must compile CGI or CLI PHP with newt support by using the --with-newt[=DIR] configure option.
Nota: This extension is not available for Windows platform.
You may need also curses and slang libraries, in order to compile this extension. To specify locations of these libraries, use the followin configuration options: --with-curses-dir=/path/to/libcurses --with-slang-dir=/path/to/libslang
This extension uses two resource types: "newt component" and "newt grid". Resource type "newt component" is returned by functions, which create common newt widgets (for example: newt_button()) Resource type "newt grid" is a special link identifier for components, returned by newt grid factory functions (for example: newt_create_grid())
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
This function sends a beep to the terminal.
Nota: Depending on the terminal's settings, this been may or may not be audible.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Open a centered window of the specified size.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
(PECL)
newt_clear_key_buffer -- Discards the contents of the terminal's input buffer without waiting for additional inputDiscards the contents of the terminal's input buffer without waiting for additional input.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Displays the string text at the position indicated.
Column number
Nota: If left is negative, the position is measured from the opposite side of the screen.
Line number
Nota: If top is negative, the position is measured from the opposite side of the screen.
Text to display.
Esempio 1. A newt_draw_root_text() example This code demonstrates drawing of titles in the both corners of the screen.
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Uninitializes newt interface. This function be called, when program is ready to exit.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Fills in the passed references with the current size of the terminal.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
Its description
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Initializes the newt interface. This function must be called before any other newt function.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Open a window of the specified size and position.
Location of the upper left-hand corner of the window (column number)
Location of the upper left-hand corner of the window (row number)
Window width
Window height
Window title
Replaces the current help line with the one from the stack.
Nota: It's important not to call to newt_pop_help_line() more then newt_push_help_line().
Removes the top window from the display, and redraws the display areas which the window overwrote.
Saves the current help line on a stack, and displays the new line.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
To increase performance, newt only updates the display when it needs to, not when the program tells it to write to the terminal. Applications can force newt to immediately update modified portions of the screen by calling this function.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
(PECL)
newt_set_suspend_callback -- Set a callback function which gets invoked when user presses the suspend keySet a callback function which gets invoked when user presses the suspend key (normally ^Z). If no suspend callback is registered, the suspend keystroke is ignored.
A callback function, which accepts one argument: data
This data is been passed to the callback function
Tells newt to return the terminal to its initial state. Once this is done, the application can suspend itself (by sending itself a SIGTSTP, fork a child program, or do whatever else it likes.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
This function doesn't return until a key has been pressed. The keystroke is then ignored. If a key is already in the terminal's buffer, this function discards a keystroke and returns immediately.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
These functions are only available when running PHP as a NSAPI module in Netscape/iPlanet/SunONE webservers.
For PHP installation on Netscape/iPlanet/SunONE webservers see the NSAPI section (UNIX, Windows) in the installation chapter.
The behaviour of the NSAPI PHP module is affected by settings in php.ini. Configuration settings from php.ini may be overridden by additional parameters to the php4_execute call in obj.conf
Tabella 1. NSAPI configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
nsapi.read_timeout | "60" | PHP_INI_ALL | Available since PHP 4.3.3. |
Breve descrizione dei parametri di configurazione.
Sets the time in seconds the plugin is waiting for POST data from the client.
NSAPI implements a subset of the functions from the Apache module for maximum compatibility.
Tabella 2. Apache functions implemented by NSAPI
Apache function (only as alias) | NSAPI function | Description |
---|---|---|
apache_request_headers() | nsapi_request_headers() | Fetch all HTTP request headers |
apache_response_headers() | nsapi_response_headers() | Fetch all HTTP response headers |
getallheaders() | nsapi_request_headers() | Fetch all HTTP request headers |
virtual() | nsapi_virtual() | Make NSAPI sub-request |
nsapi_request_headers() gets all the HTTP headers in the current request. This is only supported when PHP runs as a NSAPI module.
Nota: Prior to PHP 4.3.3, getallheaders() was only available for the Apache servers. After PHP 4.3.3, getallheaders() is an alias for nsapi_request_headers() if you use the NSAPI module.
Nota: You can also get at the value of the common CGI variables by reading them from the $_SERVER superglobal, which works whether or not you are using PHP as a NSAPI module.
nsapi_virtual() is an NSAPI-specific function which is equivalent to <!--#include virtual...--> in SSI (.shtml files). It does an NSAPI sub-request. It is useful for including CGI scripts or .shtml files, or anything else that you'd parse through webserver.
To run the sub-request, all buffers are terminated and flushed to the browser, pending headers are sent too.
You cannot make recursive requests with this function to other PHP scripts. If you want to include PHP scripts, use include() or require().
Nota: This function depends on a undocumented feature of the Netscape/iPlanet/SunONE webservers. Use phpinfo() to determine if it is available. In the Unix environment it should always work, in windows it depends on the name of a ns-httpdXX.dll file.
Read the note about subrequests in the NSAPI section (UNIX, Windows) if you experience this problem.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
In Object Oriented Programming, it is common to see the composition of simple classes (and/or instances) into a more complex one. This is a flexible strategy for building complicated objects and object hierarchies and can function as a dynamic alternative to multiple inheritance. There are two ways to perform class (and/or object) composition depending on the relationship between the composed elements: Association and Aggregation.
An Association is a composition of independently constructed and externally visible parts. When we associate classes or objects, each one keeps a reference to the ones it is associated with. When we associate classes statically, one class will contain a reference to an instance of the other class. For example:
Esempio 1. Class association
|
Esempio 2. Object association
|
Aggregation, on the other hand, implies encapsulation (hidding) of the parts of the composition. We can aggregate classes by using a (static) inner class (PHP does not yet support inner classes), in this case the aggregated class definition is not accessible, except through the class that contains it. The aggregation of instances (object aggregation) involves the dynamic creation of subobjects inside an object, in the process, expanding the properties and methods of that object.
Object aggregation is a natural way of representing a whole-part relationship, (for example, molecules are aggregates of atoms), or can be used to obtain an effect equivalent to multiple inheritance, without having to permanently bind a subclass to two or more parent classes and their interfaces. In fact object aggregation can be more flexible, in which we can select what methods or properties to "inherit" in the aggregated object.
We define 3 classes, each implementing a different storage method:
Esempio 3. storage_classes.inc
|
We then instantiate a couple of objects from the defined classes, and perform some aggregations and deaggregations, printing some object information along the way:
Esempio 4. test_aggregation.php
|
We will now consider the output to understand some of the side-effects and limitation of object aggregation in PHP. First, the newly created $fs and $ws objects give the expected output (according to their respective class declaration). Note that for the purposes of object aggregation, private elements of a class/object begin with an underscore character ("_"), even though there is not real distinction between public and private class/object elements in PHP.
$fs object Class: filestorage property: data (array) 0 => 3.1415926535898 1 => kludge != cruft method: filestorage method: write $ws object Class: wddxstorage property: data (array) 0 => 3.1415926535898 1 => kludge != cruft property: version = 1.0 property: _id = ID::9bb2b640764d4370eb04808af8b076a5 method: wddxstorage method: store method: _genid |
We then aggregate $fs with the WDDXStorage class, and print out the object information. We can see now that even though nominally the $fs object is still of FileStorage, it now has the property $version, and the method store(), both defined in WDDXStorage. One important thing to note is that it has not aggregated the private elements defined in the class, which are present in the $ws object. Also absent is the constructor from WDDXStorage, which will not be logical to aggegate.
Let's aggregate $fs to the WDDXStorage class $fs object Class: filestorage property: data (array) 0 => 3.1415926535898 1 => kludge != cruft property: version = 1.0 method: filestorage method: write method: store |
The process of aggregation is cumulative, so when we aggregate $fs with the class DBStorage, generating an object that can use the storage methods of all the defined classes.
Now let us aggregate it to the DBStorage class $fs object Class: filestorage property: data (array) 0 => 3.1415926535898 1 => kludge != cruft property: version = 1.0 property: dbtype = mysql method: filestorage method: write method: store method: save |
Finally, the same way we aggregated properties and methods dynamically, we can also deaggregate them from the object. So, if we deaggregate the class WDDXStorage from $fs, we will obtain:
And deaggregate the WDDXStorage methods and properties $fs object Class: filestorage property: data (array) 0 => 3.1415926535898 1 => kludge != cruft property: dbtype = mysql method: filestorage method: write method: save |
One point that we have not mentioned above, is that the process of aggregation will not override existing properties or methods in the objects. For example, the class FileStorage defines a $data property, and the class WDDXStorage also defines a similar property which will not override the one in the object acquired during instantiation from the class FileStorage.
(no version information, might be only in CVS)
aggregate_info -- Returns an associative array of the methods and properties from each class that has been aggregated to the objectWill return the aggregation information for a particular object as an associative array of arrays of methods and properties. The key for the main array is the name of the aggregated class.
For example the code below
Esempio 1. Using aggregate_info()
Will produce the output
|
_secret_super_dicing
See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()
(PHP 4 >= 4.2.0)
aggregate_methods_by_list -- Selective dynamic class methods aggregation to an objectAggregates methods from a class to an existing object using a list of method names. The optional parameter exclude is used to decide whether the list contains the names of methods to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).
The class constructor or methods whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.
See also aggregate(), aggregate_info(), aggregate_methods(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()
(PHP 4 >= 4.2.0)
aggregate_methods_by_regexp -- Selective class methods aggregation to an object using a regular expressionAggregates methods from a class to an existing object using a regular expression to match method names. The optional parameter exclude is used to decide whether the regular expression will select the names of methods to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).
The class constructor or methods whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.
See also aggregate(), aggregate_info(), aggregate_methods(), aggregate_methods_by_list(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()
Aggregates all methods defined in a class to an existing object, except for the class constructor, or methods whose names start with an underscore character (_) which are considered private to the aggregated class.
See also aggregate(), aggregate_info(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()
(PHP 4 >= 4.2.0)
aggregate_properties_by_list -- Selective dynamic class properties aggregation to an objectAggregates properties from a class to an existing object using a list of property names. The optional parameter exclude is used to decide whether the list contains the names of class properties to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).
The properties whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.
See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_regexp(), aggregate_info(), deaggregate()
(PHP 4 >= 4.2.0)
aggregate_properties_by_regexp -- Selective class properties aggregation to an object using a regular expressionAggregates properties from a class to an existing object using a regular expression to match their names. The optional parameter exclude is used to decide whether the regular expression will select the names of class properties to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).
The properties whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.
See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_info(), deaggregate()
Aggregates all properties defined in a class to an existing object, except for properties whose names start with an underscore character (_) which are considered private to the aggregated class.
See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), aggregate_info(), deaggregate()
Aggregates methods and properties defined in a class to an existing object. Methods and properties with names starting with an underscore character (_) are considered private to the aggregated class and are not used, constructors are also excluded from the aggregation procedure.
See also aggregate_info(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()
Removes the methods and properties from classes that were aggregated to an object. If the optional class_name parameters is passed, only those methods and properties defined in that class are removed, otherwise all aggregated methods and properties are eliminated.
See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), aggregate_info()
Lo scopo di questa estensione è di permettere l'overloading delle proprietà di accesso agli oggetti e dei metodi di chiamata. Solo una funzione è definita in questa estensione, overload() che prende il nome dalla classe che ha questa funzionalità abilitata. La classe nominata ha da definire metodi appropriati se vuole avere questa funzionalità: __get(), __set() and __call() rispettivamente per ricevere/impostare una proprietà, o chiamare un metodo. Questa strada del sovraccarico può essere selettiva. Dentro queste funzioni handler l'overloading è disabilitato così si può accedere alle proprietà dell'oggetto normalmente.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
Avvertimento |
Questo modulo non è parte di PHP 5. Php 5 gestisce le chiamate __get(), __set() and __call() in modo nativo. Vedere la pagina l'overload in PHP 5 per maggiori dettagli. |
Per potere utilizzare queste funzioni occorre compilare il PHP con --enable-overload. A partire dal PHP 4.3.0 questo modulo è abilitato per default. Si può disabilitare il supporto overload tramite --disable--overload.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Nota: Il supporto per questo modulo è compilato per default a partire dal PHP 4.3.0.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Alcuni semplici esempi sull'uso della funzione overload()
Esempio 1. Overloading di una classe PHP
|
La funzione overload() abiliterà la proprietà e il method call overloading per una classe identificata dal parametro class_name. Guarda un esempio nella sezione di introduzione di questa parte..
Queste funzioni permettono di accedere ai database Oracle9, Oracle8 e Oracle7. Usano la Oracle Call Interface (OCI).
Questa estensione è più flessibile della estensione precedente di Oracle. Supporta il binding di variabili PHP locali e globali ai segnaposto Oracle, ha pieno supporto di LOB, FILE e ROWID e permette di utilizzare variabili di definizione personalizzabili. Si raccomanda di utilizzare questa estensione al posto della vecchia estensione quando possibile;
Occorre avere installate le librerie client di Oracle per utilizzare questa estensione. Gli utenti Windows necessitano almeno della versione 8.1 di Oracle per utilizzare la dll php_oci8.dll.
Prima di usare questa estensione, occorre sincerarsi di aver impostato le variabili d'ambiente per l'utente Oracle, come pure per l'utente del server web. Le variabili che potrebbero necessitare l'impostazione sono le seguenti:
ORACLE_HOME
ORACLE_SID
LD_PRELOAD
LD_LIBRARY_PATH
NLS_LANG
ORA_NLS33
Dopo aver impostato le variabili d'ambiente per l'utente del server web, occorre sicerarsi di aver aggiunto anche l'utente stesso (nobody, www) al gruppo oracle.
Se il server web non parte o va in blocco: Controllare che apache sia linkato con la libreria pthread:
# ldd /www/apache/bin/httpd libpthread.so.0 => /lib/libpthread.so.0 (0x4001c000) libm.so.6 => /lib/libm.so.6 (0x4002f000) libcrypt.so.1 => /lib/libcrypt.so.1 (0x4004c000) libdl.so.2 => /lib/libdl.so.2 (0x4007a000) libc.so.6 => /lib/libc.so.6 (0x4007e000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)Se la libpthread non compare nell'elenco, occorre reinstallare Apache:
Si noti che su alcuni sistemi, come ad esempio UnixWare, la libreria si chiama libthread invece di libpthread. PHP e Apache devono essere configurati con EXTRA_LIBS=-lthread.
Si deve compilare PHP con l'opzione --with-oci8[=DIR], dove DIR è di default il contenuto della variabile di ambiente ORACLE_HOME.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Modalità di esecuzione dello statement. Non viene eseguito il commit automatico utilizzando questa modalità.
Modalità di esecuzione dello statement. Utilizzare questa modalità se non si vuole eseguire la query, ma solamente ricevere la descrizione della select list.
Modalità di esecuzione dello statement. Vene eseguito automaticamente il commit dello statement dopo la chiamata della oci_execute().
Modalità di recupero dati dello statement. Utilizzato quando l'applicazione conosce in anticipo quante righe verranno recuperate. Questa modalità disattiva il prefetching negli Oracle release 8 o successivi. Il cursore viene eliminato dopo che le sono state caricate e ciò può determinare un utilizzo ridotto delle risorse del server.
Utilizzato con oci_bind_by_name() quando si collegano i BFILE.
Utilizzato con oci_bind_by_name() quando si collegano i CFILE.
Utilizzato con oci_bind_by_name() quando si collegano i CLOB.
Utilizzato con oci_bind_by_name() quando si collegano i BLOB.
Utilizzato con oci_bind_by_name() quando si collegano i ROWID.
Utilizzato con oci_bind_by_name() quando si collegano i cursori, precedentemente allocati con oci_new_descriptor().
Utilizzato con oci_bind_by_name() quando si collegano i named data type.
Alias di OCI_B_BFILE.
Alias di OCI_B_CFILEE.
Alias di OCI_B_CLOB.
Alias di OCI_B_BLOB.
Alias di OCI_B_ROWID.
Alias di OCI_B_NTY.
Modalità di default di oci_fetch_all().
Modalità alternativa di oci_fetch_all().
Utilizzato con oci_fetch_all() e oci_fetch_array() per ottenere un array associative come risultato.
Utilizzato con oci_fetch_all() e oci_fetch_array() per ottenere un array enumerativo come risultato.
Utilizzato con oci_fetch_all() e oci_fetch_array() per ottenere un array con indici sia associativi che numerici.
Utilizzato con oci_fetch_array() per ottenere elementi dell'array vuoti se il valore del campo è NULL.
Utilizzato con oci_fetch_array() per ottenere il valore del LOB invece del suo descrittore.
Questo flag ordina a oci_new_descriptor() di inizializzare un nuovo descrittore di FILE.
Questo flag ordina a oci_new_descriptor() di inizializzare un nuovo descrittore di LOB.
Questo flag ordina a oci_new_descriptor() di inizializzare un nuovo descrittore di ROWID.
Alias di OCI_DTYPE_FILE.
Alias di OCI_DTYPE_LOB.
Alias di OCI_DTYPE_ROWID.
Esempio 1. Trucchi OCI
|
You can easily access stored procedures in the same way as you would from the commands line.
Esempio 2. Using Stored Procedures
|
(no version information, might be only in CVS)
OCI-Collection->append -- Appends element to the collectionAppends element to the end of the collection. Parameter value can be a string or a number.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Collection->assign -- Assigns a value to the collection from another existing collectionAssigns a value to the collection from another, previously created collection. Both collections must be created with oci_new_collection() prior to using them.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Collection->assignElem -- Assigns a value to the element of the collectionAssigns a value to the element with index index. Parameter value can be a string or a number.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Collection->free -- Frees the resources associated with the collection objectFrees the resources associated with the collection object.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Collection->getElem -- Returns value of the elementReturns element's value with the index index (1-based).
OCI-Collection->getElem() returns FALSE if such element doesn't exist; NULL if element is NULL; string if element is column of a string datatype or number if element is numeric field.
(no version information, might be only in CVS)
OCI-Collection->max -- Returns the maximum number of elements in the collectionReturns the maximum number of elements in the collection. If the returned value is 0, then the number of elements is not limited. OCI-Collection->max() returns FALSE in case of error.
(no version information, might be only in CVS)
OCI-Collection->size -- Returns size of the collectionReturns the number of elements in the collection or FALSE on error.
(no version information, might be only in CVS)
OCI-Collection->trim -- Trims elements from the end of the collectionTrims num of elements from the end of the collection.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Lob->append -- Appends data from the large object to another large objectAppends data from the large object to the end of another large object.
Writing to the large object with OCI-Lob->append() will fail if buffering was previously enabled. You must disable buffering before appending. You may need to flush buffers with OCI-Lob->flush before disabling buffering.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
OCI-Lob->close() closes descriptor of LOB or FILE. This function should be used only with OCI-Lob->writeTemporary.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Lob->eof -- Tests for end-of-file on a large object's descriptorReturns TRUE if internal pointer of large object is at the end of LOB. Otherwise returns FALSE.
(no version information, might be only in CVS)
OCI-Lob->erase -- Erases a specified portion of the internal LOB dataErases a specified portion of the internal LOB data starting at a specified offset. Parameters length and offset are optional. OCI-Lob->erase() erases all LOB data by default.
For BLOBs, erasing means that the existing LOB value is overwritten with zero-bytes. For CLOBs, the existing LOB value is overwritten with spaces.
OCI-Lob->erase() returns the actual number of characters/bytes erased or FALSE in case of error.
Exports LOB contents to a file. The file name is given in the parameter filename. The optional parameter start indicates from where to start exporting and the parameter length - indicates the length of data to be exported.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Lob->flush -- Flushes/writes buffer of the LOB to the serverOCI-Lob->flush() actually writes data to the server. By default, resources are not freed, but using flag OCI_LOB_BUFFER_FREE you can do it explicitly. Be sure you know what you're doing - next read/write operation to the same part of LOB will involve a round-trip to the server and initialize new buffer resources. It is recommended to use OCI_LOB_BUFFER_FREE flag only when you are not going to work with the LOB anymore.
OCI-Lob->flush() returns FALSE if buffering was not enabled or an error occurred.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Lob->free -- Frees resources associated with the LOB descriptorFrees resources associated with the descriptor, previously allocated with oci_new_descriptor().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Lob->getBuffering -- Returns current state of buffering for the large objectReturns FALSE if buffering for the large object is off and TRUE if buffering is used.
Writes data from the filename in to the current position of large object.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Returns large object's contents. As script execution is terminated when the memory_limit is reached, ensure that the LOB does not exceed this limit. In most cases it's recommended to use OCI-Lob->read instead. In case of error OCI-Lob->load() returns FALSE.
Reads length bytes from the current position of LOB's internal pointer. Reading stops when length bytes have been read or end of the large object is reached. Internal pointer of the large object will be shifted on the amount of bytes read.
Returns FALSE in case of error.
(no version information, might be only in CVS)
OCI-Lob->rewind -- Moves the internal pointer to the beginning of the large objectSets the internal pointer to the beginning of the large object.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Saves data to the large object. Parameter offset can be used to indicate offset from the beginning of the large object.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Lob->seek -- Sets the internal pointer of the large objectSets the internal pointer of the large object. Parameter offset indicates the amount of bytes, on which internal pointer should be moved from the position, pointed by whence:
OCI_SEEK_SET - sets the position equal to offset |
OCI_SEEK_CUR - adds offset bytes to the current position |
OCI_SEEK_END - adds offset bytes to the end of large object (use negative value to move to a position before the end of large object) |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Lob->setBuffering -- Changes current state of buffering for the large objectlob->setBuffering() sets the buffering for the large object, depending on the value of the on_off parameter. Repeated calls to lob->setBuffering() with the same flag will return TRUE. The values for on_off are: TRUE for on and FALSE for off.
Use of this function may provide performance improvements by buffering small reads and writes of LOBs by reducing the number of network round-trips and LOB versions. oci_lob_flush() should be used to flush buffers, when you have finished working with the large object.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Returns length of large object value or FALSE in case of error. Empty objects have zero length.
(no version information, might be only in CVS)
OCI-Lob->tell -- Returns current position of internal pointer of large objectReturns current position of a LOB's internal pointer or FALSE if an error occurred.
If parameter length is given, OCI-Lob->truncate() truncates large object to length bytes. Otherwise, OCI-Lob->truncate() will purge the LOB completely.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Writes data from the parameter data into the current position of LOB's internal pointer. If the parameter length is given, writing will stop after length bytes have been written or the end of data is reached, whichever comes first.
OCI-Lob->write() returns the number of bytes written or FALSE in case of error.
(no version information, might be only in CVS)
OCI-Lob->writeTemporary -- Writes temporary large objectCreates a temporary large object and writes data to it.
Parameter lob_type can be one of the following:
OCI_TEMP_BLOB is used to create temporary BLOBs |
OCI_TEMP_CLOB is used to create temporary CLOBs |
OCI-Lob->writeTemporary() creates a CLOB by default.
You should use OCI-Lob->close when the work with the object is over.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
oci_bind_by_name() collega la variabile PHP variable al segnaposto Oracle ph_name. L'utilizzo in modalità input o output sarà determinato a run-time, e lo spazio di memoria necessario sarà allocato. Il parametro lungmax imposta la lunghezza massima del collegamento. Se si imposta lungmax a -1 oci_bind_by_name() userà l'attuale lunghezza di variabile per impostare la lunghezza massima.
Se si deve collegare un tipo dato astratto (LOB/ROWID/BFILE) occorre innanzitutto allocarlo usando la funzione oci_new_descriptor(). Il parametro lungmax non è usato con i tipi dati astratti e dovrebbe essere impostato a -1. La variabile tipo informa oracle sul tipo di descrittore che si vuole usare. I valori possibili sono:
OCI_B_FILE - per i BFILE;
OCI_B_CFILE - per i CFILE;
OCI_B_CLOB - per i CLOB;
OCI_B_BLOB - per i BLOB;
OCI_B_ROWID - per i ROWID;
OCI_B_NTY - per i named datatype;
OCI_B_CURSOR - per i cursori precedentemente creati con oci_new_cursor().
Esempio 1. esempio di ocibindbyname()
|
Ricordarsi che questa funzione elimina gli spazi alla fine della riga. Vedere il seguente esempio:
Esempio 2. esempio di oci_bind_by_name()
|
Esempio 3. esempio di oci_bind_by_name()
|
Avvertimento |
Non utilizzare le magic_quotes_gpc o addslashes() e oci_bind_by_name() simultaneamente in quanto le virgolette non sono necessarie nelle variabili e qualsiasi virgoletta aggiunta automaticamente verrà scritta nel database dal momento che ocibindbyname() non è in grado di distinguere le virgolette aggiunte automaticamente da quelle intenzionali. |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Nelle versioni di PHP antecedenti la 5.0.0 si deve usare ocibindbyname(). Questo nome può ancora essere utilizzato, è rimasto come alias di oci_bind_by_name() per mantenere la compatibilità. Ciò è comunque deprecato e non raccomandato.
oci_cancel() invalida un cursore, rilasciando tutte le risorse associate e cancella la possibilità di leggere da esso.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nelle versioni di PHP antecedenti la 5.0.0 si deve usare ocicancel(). Questo nome può ancora essere utilizzato, è rimasto come alias di oci_cancel() per mantenere la compatibilità. Ciò è comunque deprecato e non raccomandato.
oci_close() closes the Oracle connection connection.
Nota: Starting from the version 1.1 oci_close() correctly closes the Oracle connection. Use oci8.old_oci_close_semantics option to restore old behaviour of this function.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: In PHP versions before 5.0.0 you must use ocilogoff() instead. This name still can be used, it was left as alias of oci_close() for downwards compatability. This, however, is deprecated and not recommended.
oci_commit() commits all outstanding statements for the active transaction on the Oracle connection connection.
Esempio 1. oci_commit() example
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Transactions are automatically rolled back when you close the connection, or when the script ends, whichever is soonest. You need to explicitly call oci_commit() to commit the transaction, or oci_rollback() to abort it.
Nota: In PHP versions before 5.0.0 you must use ocicommit() instead. This name still can be used, it was left as alias of oci_commit() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_rollback() and oci_execute().
oci_connect() returns a connection identifier needed for most other OCI calls. The optional third parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora to which you want to connect. If the optional third parameter is not specified, PHP uses the environment variables ORACLE_SID (Oracle instance) or TWO_TASK (tnsnames.ora) to determine which database to connect to.
Parameter session_mode is available since version 1.1 and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified, oci_connect() will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to On.
Nota: If you're using PHP with Oracle Instant Client, you can use easy connect naming method described here: http://download-west.oracle.com/docs/cd/B12037_01/network.101/b10775/naming.htm#i498306. Basically this means you can specify "//db_host[:port]/database_name" as database name. But if you want to use the old way of naming you must set either ORACLE_HOME or TNS_ADMIN.
Nota: The second and subsequent calls to oci_connect() with the same parameters will return the connection handle returned from the first call. This means that queries issued against one handle are also applied to the other handles, because they are the same handle. This behaviour is demonstrated in Example 1 below. If you require two handles to be transactionally isolated from each other, you should use oci_new_connect() instead.
Using Oracle server version 9.2 and greater, you can indicate charset parameter, which will be used in the new connection. If you're using Oracle server < 9.2, this parameter will be ignored and NLS_LANG environment variable will be used instead.
Esempio 1. oci_connect() example
|
oci_connect() returns FALSE if an error occured.
Nota: In PHP versions before 5.0.0 you must use ocilogon() instead. This name still can be used, it was left as the alias of oci_connect() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_pconnect(), oci_new_connect() and oci_close().
oci_define_by_name() defines PHP variables for fetches of SQL-Columns. Take into consideration that Oracle uses ALL-UPPERCASE column names, whereby in your select you can also use lowercase. oci_define_by_name() expects the column_name to be in uppercase. If you define a variable that doesn't exists in your select statement, no error will be issued.
If you need to define an abstract datatype (LOB/ROWID/BFILE) you must allocate it first using oci_new_descriptor(). See also the oci_bind_by_name() function.
Esempio 1. oci_define_by_name() example
|
Nota: In PHP versions before 5.0.0 you must use ocidefinebyname() instead. This name still can be used, it was left as alias of oci_define_by_name() for downwards compatability. This, however, is deprecated and not recommended.
For most errors, the parameter is the most appropriate resource handle. For connection errors with oci_connect(), oci_new_connect() or oci_pconnect(), do not pass a parameter. If no error is found, oci_error() returns FALSE. oci_error() returns the error as an associative array. In this array, code consists the oracle error code and message the oracle error string.
As of PHP 4.3: offset and sqltext will also be included in the return array to indicate the location of the error and the original SQL text which caused it.
Esempio 3. Displaying the Oracle error message and problematic statement after an execution error
|
Nota: In PHP versions before 5.0.0 you must use ocierror() instead. This name still can be used, it was left as alias of oci_error() for downwards compatability. This, however, is deprecated and not recommended.
oci_execute() executes a previously parsed statement (see oci_parse()). The optional mode allows you to specify the execution mode (default is OCI_COMMIT_ON_SUCCESS). If you don't want statements to be committed automatically, you should specify OCI_DEFAULT as your mode.
When using OCI_DEFAULT mode, you're creating a transaction. Transactions are automatically rolled back when you close the connection, or when the script ends, whichever is soonest. You need to explicitly call oci_commit() to commit the transaction, or oci_rollback() to abort it.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: In PHP versions before 5.0.0 you must use ociexecute() instead. This name still can be used, it was left as alias of oci_execute() for downwards compatability. This, however, is deprecated and not recommended.
oci_fetch_all() fetches all the rows from a result into a user-defined array. oci_fetch_all() returns the number of rows fetched or FALSE in case of an error. skip is the number of initial rows to ignore when fetching the result (default value of 0, to start at the first line). maxrows is the number of rows to read, starting at the skipth row (default to -1, meaning all the rows).
Nota: This function sets NULL fields to PHP NULL value.
Parameter flags can be any combination of the following:
OCI_FETCHSTATEMENT_BY_ROW |
OCI_FETCHSTATEMENT_BY_COLUMN (default value) |
OCI_NUM |
OCI_ASSOC |
Esempio 1. oci_fetch_all() example
|
For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver
oci_fetch_all() returns FALSE in case of error.
Nota: In PHP versions before 5.0.0 you must use ocifetchstatement() instead. This name still can be used, it was left as alias of oci_fetch_all() for downwards compatability. This, however, is deprecated and not recommended.
(PHP 5)
oci_fetch_array -- Returns the next row from the result data as an associative or numeric array, or bothReturns an array, which corresponds to the next result row or FALSE in case of error or there are no more rows in the result.
oci_fetch_array() returns an array with both associative and numeric indices.
Nota: This function sets NULL fields to PHP NULL value.
An optional second parameter can be any combination of the following constants:
OCI_BOTH - return an array with both associative and numeric indices (the same as OCI_ASSOC + OCI_NUM). This is the default behavior. |
OCI_ASSOC - return an associative array (as oci_fetch_assoc() works). |
OCI_NUM - return a numeric array, (as oci_fetch_row() works). |
OCI_RETURN_NULLS - create empty elements for the NULL fields. |
OCI_RETURN_LOBS - return the value of a LOB of the descriptor. |
It should be mentioned here, that oci_fetch_array() is insignificantly slower, than oci_fetch_row(), but much more handy.
Nota: Oracle returns all field names in uppercase and associative indices in the result array will be uppercased too.
Esempio 1. oci_fetch_array() with OCI_BOTH example
|
Esempio 2. oci_fetch_array() with OCI_NUM example
|
Esempio 3. oci_fetch_array() with OCI_ASSOC example
|
Esempio 4. oci_fetch_array() with OCI_RETURN_LOBS example
|
For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver
See also oci_fetch_assoc(), oci_fetch_object(), oci_fetch_row() and oci_fetch_all().
oci_fetch_assoc() returns the next row from the result data as an associative array (identical to oci_fetch_array() call with OCI_ASSOC flag).
Nota: This function sets NULL fields to PHP NULL value.
A subsequent call to oci_fetch_assoc() will return the next row or FALSE if there are no more rows.
Nota: Oracle returns all field names in uppercase and associative indices in the result array will be uppercased too.
For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver
See also oci_fetch_array(), oci_fetch_object(), oci_fetch_row() and oci_fetch_all().
oci_fetch_object() returns the next row from the result data as an object, which attributes correspond to fields in statement.
Nota: This function sets NULL fields to PHP NULL value.
Subsequent calls to oci_fetch_object() will return the next row from the result or FALSE if there are no more rows.
Nota: Oracle returns all field names in uppercase and attributes' names in the result object will be in uppercase as well.
For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver
See also oci_fetch_array(), oci_fetch_assoc(), oci_fetch_row() and oci_fetch_all().
Calling oci_fetch_row() is identical to oci_fetch_array() with OCI_NUM flag and returns the next row from the result data as a numeric array.
Nota: This function sets NULL fields to PHP NULL value.
Subsequent calls to oci_fetch_row() will return the next row from the result data or FALSE if there are no more rows.
For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver
See also oci_fetch_array(), oci_fetch_object(), oci_fetch_assoc() and oci_fetch_all().
oci_fetch() fetches the next row (for SELECT statements) into the internal result-buffer.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver
Nota: In PHP versions before 5.0.0 you must use ocifetch() instead. This name still can be used, it was left as alias of oci_fetch() for downwards compatability. This, however, is deprecated and not recommended.
oci_field_is_null() returns TRUE if field field from the statement is NULL. Parameter field could be a field's index or a field's name (uppercased).
Nota: In PHP versions before 5.0.0 you must use ocicolumnisnull() instead. This name still can be used, it was left as alias of oci_field_is_null() for downwards compatability. This, however, is deprecated and not recommended.
oci_field_name() returns the name of the field corresponding to the field number (1-based).
Esempio 1. oci_field_name() example
|
Nota: In PHP versions before 5.0.0 you must use ocicolumnname() instead. This name still can be used, it was left as alias of oci_field_name() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_num_fields(), oci_field_type(), and oci_field_size().
Returns precision of the field with field index (1-based).
For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).
Nota: In PHP versions before 5.0.0 you must use ocicolumnprecision() instead. This name still can be used, it was left as alias of oci_field_precision() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_field_scale() and oci_field_type().
Returns scale of the column with field index (1-based) or FALSE if there is no such field.
For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).
Nota: In PHP versions before 5.0.0 you must use ocicolumnscale() instead. This name still can be used, it was left as alias of oci_field_scale() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_field_precision() and oci_field_type().
oci_field_size() returns the size of a field in bytes. Value of field parameter can be the field's index (1-based) or it's name.
Esempio 1. oci_field_size()example
|
Nota: In PHP versions before 5.0.0 you must use ocicolumnsize() instead. This name still can be used, it was left as alias of oci_field_size() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_num_fields() and oci_field_name().
oci_field_type_raw() returns Oracle's raw data type of the field.
Nota: In PHP versions before 5.0.0 you must use ocicolumntyperaw() instead. This name still can be used, it was left as alias of oci_field_type_raw() for downwards compatability. This, however, is deprecated and not recommended.
However, if you want to get field's type, then oci_field_type() will suit you better. See oci_field_type() for additional information.
oci_field_type() returns a field's data type. Parameter field is an index of the field in the statement (1-based).
Esempio 1. oci_field_type() example
|
Nota: In PHP versions before 5.0.0 you must use ocicolumntype() instead. This name still can be used, it was left as alias of oci_field_type() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_num_fields(), oci_field_name(), and oci_field_size().
oci_free_statement() frees resources associated with Oracle's cursor or statement, which was received from as a result of oci_parse() or obtained from Oracle.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
oci_internal_debug() enables or disables internal debug output. Set onoff to 0 to turn debug output off or 1 to turn it on.
Nota: In PHP versions before 5.0.0 you must use ociinternaldebug() instead. This name still can be used, it was left as alias of oci_internal_debug() for downwards compatability. This, however, is deprecated and not recommended.
Copies a large object or a part of a large object to another large object. Parameter length indicates the length of data to be copied. Old LOB-recipient data will be overwritten.
If you need to copy a particular part of a LOB to a particular position of a LOB, use oci_lob_seek() to move LOB internal pointers.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Compares two LOB/FILE locators. Returns TRUE if these objects are equal and FALSE otherwise.
Allocates a new collection object. Parameter tdo should be a valid named type (uppercase). The third, optional parameter schema should point to the scheme, where the named type was created. oci_new_collection() uses the name of the current user as the default value of schema.
oci_new_collection() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocinewcollection() instead. This name still can be used, it was left as alias of oci_new_collection() for downwards compatability. This, however, is deprecated and not recommended.
oci_new_connect() establishes a new connection to an Oracle server and logs on. Unlike oci_connect() and oci_pconnect(), oci_new_connect() does not cache connections and will always return a brand-new freshly opened connection handle. This is useful if your application needs transactional isolation between two sets of queries.
The optional third parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora. If the third parameter is not specified, PHP uses environment variables ORACLE_SID and TWO_TASK to determine the name of local Oracle instance and location of tnsnames.ora accordingly.
Parameter session_mode is available since version 1.1 and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified, oci_new_connect() will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to On.
Nota: If you're using PHP with Oracle Instant Client, you can use easy connect naming method described here: http://download-west.oracle.com/docs/cd/B12037_01/network.101/b10775/naming.htm#i498306. Basically this means you can specify "//db_host[:port]/database_name" as database name. But if you want to use the old way of naming you must set either ORACLE_HOME or TNS_ADMIN.
Using Oracle server version 9.2 and greater, you can indicate charset parameter, which will be used in the new connection. If you're using Oracle server < 9.2, this parameter will be ignored and NLS_LANG environment variable will be used instead.
The following demonstrates how you can separate connections.
Esempio 1. oci_new_connect() example
|
oci_new_connect() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocinlogon() instead. This name still can be used, it was left as alias of oci_new_connect() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_connect() and oci_pconnect().
oci_new_cursor() allocates a new statement handle on the specified connection.
Esempio 1. Using REF CURSOR in an Oracle's stored procedure
|
Esempio 2. Using REF CURSOR in an Oracle's select statement
|
oci_new_cursor() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocinewcursor() instead. This name still can be used, it was left as alias of oci_new_cursor() for downwards compatability. This, however, is deprecated and not recommended.
oci_new_descriptor() allocates resources to hold descriptor or LOB locator. Valid values for type are: OCI_D_FILE, OCI_D_LOB and OCI_D_ROWID.
Esempio 1. oci_new_descriptor() example
|
Esempio 2. oci_new_descriptor() example
|
oci_new_descriptor() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocinewdescriptor() instead. This name still can be used, it was left as alias of oci_new_descriptor() for downwards compatability. This, however, is deprecated and not recommended.
oci_num_fields() returns the number of columns in the statement.
Esempio 1. oci_num_fields() example
|
oci_num_fields() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocinumcols() instead. This name still can be used, it was left as alias of oci_num_fields() for downwards compatability. This, however, is deprecated and not recommended.
oci_num_rows() returns number of rows affected during statement execution.
Nota: This function does not return number of rows selected! For SELECT statements this function will return the number of rows, that were fetched to the buffer with oci_fetch*() functions.
Esempio 1. oci_num_rows() example
|
oci_num_rows() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocirowcount() instead. This name still can be used, it was left as alias of oci_num_rows() for downwards compatability. This, however, is deprecated and not recommended.
oci_parse() prepares the query using connection and returns the statement identifier, which can be used with oci_bind_by_name(), oci_execute() and other functions.
Nota: This function does not validate query. The only way to find out if query is valid SQL or PL/SQL statement - is to execute it.
oci_parse() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ociparse() instead. This name still can be used, it was left as alias of oci_parse() for downwards compatability. This, however, is deprecated and not recommended.
Changes password for user with username. Parameters old_password and new_password should indicate old and new passwords respectively.
Nota: The second oci_password_change() syntax is available since version 1.1.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: In PHP versions before 5.0.0 you must use ocipasswordchange() instead. This name still can be used, it was left as alias of oci_password_change() for downwards compatability. This, however, is deprecated and not recommended.
oci_pconnect() creates a persistent connection to an Oracle server and logs on. Persistent connections are cached and re-used between requests, resulting in reduced overhead on each page load; a typical PHP application will have a single persistent connection open against an Oracle server per Apache child process (or PHP FastCGI/CGI process). See the Persistent Database Connections section for more information.
Nota: Starting with version 1.1 of the oci8 extension, the lifetime and maximum amount of persistent Oracle connections can be tuned by setting the following configuration values: oci8.persistent_timeout, oci8.ping_interval and oci8.max_persistent.
The optional third parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora. If the third parameter is not specified, PHP uses environment variables ORACLE_SID and TWO_TASK to determine the name of local Oracle instance and location of tnsnames.ora accordingly.
Parameter session_mode is available since version 1.1 and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified, oci_connect() will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to On.
Nota: If you're using PHP with Oracle Instant Client, you can use easy connect naming method described here: http://download-west.oracle.com/docs/cd/B12037_01/network.101/b10775/naming.htm#i498306. Basically this means you can specify "//db_host[:port]/database_name" as database name. But if you want to use the old way of naming you must set either ORACLE_HOME or TNS_ADMIN.
Using Oracle server version 9.2 and greater, you can indicate charset parameter, which will be used in the new connection. If you're using Oracle server < 9.2, this parameter will be ignored and NLS_LANG environment variable will be used instead.
oci_pconnect() returns connection identifier or FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ociplogon() instead. This name still can be used, it was left as alias of oci_pconnect() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_connect() and oci_new_connect().
oci_result() returns the data from the field field in the current row, fetched by oci_fetch(). oci_result() returns everything as strings except for abstract types (ROWIDs, LOBs and FILEs). oci_result() returns FALSE on error.
You can either use the column number (1-based) or the column name (in uppercase) for the field() parameter.
Nota: In PHP versions before 5.0.0 you must use ociresult() instead. This name still can be used, it was left as alias of oci_result() for downwards compatability. This, however, is deprecated and not recommended.
For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver
See also oci_fetch_array(), oci_fetch_assoc(), oci_fetch_object(), oci_fetch_row() and oci_fetch_all().
oci_rollback() rolls back all outstanding statements for Oracle connection connection.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Transactions are automatically rolled back when you close the connection, or when the script ends, whichever is soonest. You need to explicitly call oci_commit() to commit the transaction, or oci_rollback() to abort it.
Nota: In PHP versions before 5.0.0 you must use ocirollback() instead. This name still can be used, it was left as alias of oci_rollback() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_commit().
Returns a string with version information of the Oracle server, which uses connection connection or returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ociserverversion() instead. This name still can be used, it was left as alias of oci_server_version() for downwards compatability. This, however, is deprecated and not recommended.
Sets the number of rows to be prefetched after successful call to oci_execute(). The default value for rows is 1.
Nota: In PHP versions before 5.0.0 you must use ocisetprefetch() instead. This name still can be used, it was left as alias of oci_set_prefetch() for downwards compatability. This, however, is deprecated and not recommended.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also oci8_.default_prefetch ini option.
oci_statement_type() returns the query type of statement statement as one of the following values:
SELECT
UPDATE
DELETE
INSERT
CREATE
DROP
ALTER
BEGIN
DECLARE
UNKNOWN
Parameter statement is a valid OCI statement identifier, returned from oci_parse().
oci_statement_type() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocistatementtype() instead. This name still can be used, it was left as alias of oci_statement_type() for downwards compatability. This, however, is deprecated and not recommended.
Se non si vogliono leggere altri dati da un cursore, chiamare ocicancel().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.0.6, PHP 5)
ocicollassignelem -- Assegna un elemento alla collezione in una specifica posizione
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ocicolumnisnull() restituisce TRUE se il campo col nel risultato dell'istruzione stmt è NULL. Si può usare il numero del campo (primo campo=1) o il nome del campo per il parametro col.
ocicolumnname() restituisce il nome del campo corrispondente alla posizione (1 = primo campo) specificata.
Esempio 1. esempio di ocicolumnname()
|
Vedere anche ocinumcols(), ocicolumntype(), e ocicolumnsize().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ocicolumnsize() restituisce la dimensione del campo come riportata da Oracle. Si può usare il numero del campo (primo campo=1) o il nome del campo per il parametro col.
Esempio 1. esempio di ocicolumnsize()
|
Vedere anche ocinumcols(), ocicolumnname() e ocicolumnsize().
ocicolumntype() restituisce il tipo del campo corrispondente alla posizione (1 = primo campo) specificata.
Esempio 1. OCIColumnType
|
Vedere anche ocinumcols(), ocicolumnname(), e ocicolumnsize().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ocicommit() esegue tutte le transazioni in sospeso sulla connessione Oracle connection. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Questo esempio dimostra l'utilizzo di OCICommit.
Esempio 1. OCICommit
|
Vedere anche ocirollback().
(PHP 3 >= 3.0.7, PHP 4, PHP 5)
OCIDefineByName -- Utilizza una variabile PHP per la fase di definizione in un comando SELECTocidefinebyname() aggancia le variabili PHP ai campi SQL. Attenzione: Oracle usa nomi di colonna MAIUSCOLI, mentre nella SELECT si possono anche scrivere minuscoli. ocidefinebyname() vuole il parametro Column-Name in caratteri maiuscoli. Se si definisce una variabile che non esiste nel comando SELECT, non viene dato alcun errore!
Se occorre definire un tipo di dati astratto (LOB/ROWID/BFILE) lo si deve prima allocare usando la funzione OCINewDescriptor(). Vedere anche la funzione OCIBindByName().
Esempio 1. OCIDefineByName
|
ocierror() restituisce l'ultimo errore. Se il parametro opzionale stmt|conn|global non è specificato, viene restituito l'ultimo errore generato. Se non ci sono errori, ocierror() restituisce FALSE. ocierror() restituisce l'errore in un array associativo. In questo array, code dà il codice d'errora oracle e message dà la stringa d'errore.
ociexecute() esegue un comando precedentemente analizzato. (vedere ociparse()). Il parametro opzionale mode permette di specificare la modalità di esecuzione (il default è OCI_COMMIT_ON_SUCCESS). Se non si desidera che i comandi eseguano un commit automatico, usare OCI_DEFAULT nella variabile mode.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
ocifetch -- Estrae la prossima tupla opnendola nel buffer di risultato.ocifetch() estrae la prossima tupla (nelle istruzioni SELECT) ponendola nel buffer interno di risultato.
ocifetchinto() estrae la prossima tupla (nelle istruzioni SELECT) ponendola nell'array result. ocifetchinto() sovrascriverà il precedente contenuto di result. Di default result conterrà un array (primo indice = 1) di tutti i campi che non sono NULL.
Il parametro mode permette di cambiare il comportamento predefinito. E' possibile specificare più di un'opzione sommandole (es. OCI_ASSOC+OCI_RETURN_NULLS). Le opzioni valide sono:
OCI_ASSOC Restituisce un array associativo. |
OCI_NUM Restituisce un array indicizzato (primo indice = 0). (DEFAULT) |
OCI_RETURN_NULLS Restituisce anche i campi NULL. |
OCI_RETURN_LOBS Restituisce il valore di un LOB invece del descrittore. |
Vedere anche ocifetch() e ociexecute().
ocifetchstatement() estrae tutte le tuple da un risultato ponendole in un array definito dall'utente. ocifetchstatement() restituisce il numero di tuple estratte.
Esempio 1. Esempio di ocifetchstatement()
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ocifreecursor() libera tutte le risorse associate al cursore stmt. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
ocifreedesc() cancella il descrittore di oggetto binario lob. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 3 >= 3.0.5, PHP 4, PHP 5)
ocifreestatement -- Libera tutte le risorse associate ad un'istruzioneocifreestatement() libera tutte le risorse associate all'istruzione stmt.Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
ociinternaldebug -- Abilita o disabilita la visualizzazione del debug interno.ociinternaldebug() abilita la visualizzazione del debug interno. Impostare onoff a 0 per spegnere il debug, 1 per accenderlo.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ocilogoff() chiude la connessione Oracle.
L'uso di ocilogoff() normalmente non è necessario, dal momento che i collegamenti non persistenti sono automaticamente chiusi alla fine dell'esecuzione dello script. Vedere anche liberare le risorse
ocilogon() restituisce un identificatore di connessione necessario per la maggior parte delle altre chiamate OCI. Il terzo parametro opzionale può contenere il nome della istanza Oracle locale o il nome della voce in tnsnames.ora a cui ci si vuole connettere. Se il terzo parametro opzionale non è specificato, PHP usa la variabile d'ambiente ORACLE_SID (istanza di Oracle) o TWO_TASK (in tnsnames.ora) per determinare a quale database collegarsi.
Le connessioni sono condivise a livello di pagina quando si usa OCILogon(). Questo significa che i commit e i rollback avvengono su tutte le transazioni aperte nella pagina, anche se sono state create connessioni multiple.
Questo esempio dimostra come le connessioni sono condivise.
Esempio 1. esempio di ocilogon()
|
Vedere anche ociplogon() e ocinlogon().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ocinewcursor() alloca un nuovo identificatore di istruzione sulla connessione specificata.
Esempio 1. Using a REF CURSOR from a stored procedure
|
Esempio 2. Using a REF CURSOR in a select statement
|
ocinewdescriptor() alloca memoria per accogliere descrittori o locatori LOB. I valori validi per il parametro type sono OCI_D_FILE, OCI_D_LOB e OCI_D_ROWID. Per i descrittori LOB, i metodi load, save, e savefile sono associati al descrittore, per i BFILE esiste solo il metodo load. Vedere i suggerimenti nel secondo esempio.
Esempio 1. esempio di ocinewdescriptor()
|
Esempio 2. OCINewDescriptor
|
ocinlogon() crea una nuova connessione a un database Oracle 8 e si autentica. Il terzo parametro opzionale può contenere il nome della istanza Oracle locale o il nome della voce in tnsnames.ora a cui ci si vuole connettere. Se il terzo parametro opzionale non è specificato, PHP usa la variabile d'ambiente ORACLE_SID (istanza di Oracle) o TWO_TASK (in tnsnames.ora) per determinare a quale database collegarsi.
ocinlogon() forza una nuova connessione. Si deve usare quando si ha necessità di isolare un insieme di transazioni. Di default, le connessioni sono condivise a livello di pagina se si usa ocilogon() o a livello di processo del web server se si usa ociplogon(). Se ci sono connessioni multiple aperte con ocinlogon(), tutti i commit e rollback avverranno solo sulla connessione specificata.
Questo esempio dimostra come le connessioni sono isolate.
Esempio 1. esempio di ocinlogon()
|
Vedere anche ocilogon() e ociplogon().
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
ocinumcols -- Restituisce il numero di campi che risultano da un comando SQLocinumcols() restituisce il numero di campi contenuti in un'istruzione SQL.
Esempio 1. ocinumcols()
|
ociparse() analizza la query rispetto alla connessione conn. Restituisce un identificatore di istruzione se la query è valida, FALSE altrimenti. La query può essere qualsiasi comando SQL o blocco di codice PL/SQL.
ociplogon() crea una connessione persistente a un database Oracle 8 e si autentica. Il terzo parametro opzionale può contenere il nome della istanza Oracle locale o il nome della voce in tnsnames.ora a cui ci si vuole connettere. Se il terzo parametro opzionale non è specificato, PHP usa la variabile d'ambiente ORACLE_SID (istanza di Oracle) o TWO_TASK (in tnsnames.ora) per determinare a quale database collegarsi.
Vedere anche ocilogon() e ocinlogon().
ociresult() restituisce i dati del campo column nella tupla corrente (vedere ocifetch()).ociresult() restituirà tutto come stringa, eccetto i tipi astratti (ROWIDs, LOBs e FILEs).
ocirollback() annulla tutte le transazioni in sospeso sulla connessione Oracle connection. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche ocicommit()
ocirowcount() restituisce il numero di tuple modificate, ad esempio, da un comando update. Questa funzione non riporta il numero di tuple restituite da una select!
Esempio 1. esempio di ocirowcount()
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
ociserverversion -- Restituisce una stringa contenente informazioni sulla versione del serverImposta a rows il numero di tuple da precaricare. Il valore di default è 1.
ocistatementtype() restituisce uno dei seguenti valori:
SELECT
UPDATE
DELETE
INSERT
CREATE
DROP
ALTER
BEGIN
DECLARE
UNKNOWN
Esempio 1. Esempi di ocistatementtype()
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
ociwritetemporarylob -- Alias di OCI-Lob->writeTemporaryIn aggiunta al normale supporto ODBC, le funzioni ODBC unificate del PHP consentono l'accesso a diversi database che hanno preso in prestito la semantica dell'API ODBC per implementare le loro API. Invece di mantenere più driver per database che sono tutti pressoché identici, questi driver sono stati riuniti in un singolo insieme di funzioni ODBC.
Le funzioni ODBC unificate supportano i seguenti database: Adabas D, IBM DB2, iODBC, Solid ed Sybase SQL Anywhere.
Nota: Nella connessione ai database sopra elencati non vengono coinvolte funzioni ODBC. Le funzioni che vengono utilizzate per collegarsi nativamente con essi condividono solamente lo stesso nome e sintassi delle funzioni ODBC. L'eccezione a questo è iODBC. Compilando il PHP con il supporto di iODBC, si può utilizzare qualsiasi driver compatibile ODBC nelle applicazioni PHP. iODBC è gestito da OpenLink Software. Maggiori informazioni su iODBC, ed un HOWTO sono diponibili nel sito www.iodbc.org.
Per potere accedere ai database supportati occorre avere installato le librerie necessarie.
Include il supporto per Adabas D. DIR indica la directory di installazione di Adabas, il default è /usr/local.
Include il supporto per SAP DB. DIR indica la directory di installazione di SAP DB, il default è /usr/local.
Include il supporto per Solid. DIR indica la directory di installazione di Solid, il default è /usr/local/solid.
Include il supporto per IBM DB2. DIR indica la directory di installazione di DB2, il default è /home/db2inst1/sqllib.
Include il supporto per Empress. DIR indica la directory di installazione di Empress, il default è $EMPRESSPATH. A partire da PHP 4, questa opzione supporta solo Empress Versione 8.60 e successive.
Include il supporto per Empress Local Access. DIR indica la directory di installazione di Empress, il default è $EMPRESSPATH. A partire da PHP 4, questa opzione supporta solo Empress Versione 8.60 e successive.
Include il supporto per Birdstep. DIR indica la directory di installazione di Birdstep, il default è /usr/local/birdstep.
Include il supporto definito dall'utente per ODBC. DIR indica la directory di installazione di ODBC, il default è /usr/local. Accertarsi di definire CUSTOM_ODBC_LIBS e di avere odbc.h nelle directory di include. Ad esempio, si devorebbe definire i seguenti parametri per Sybase SQL Anywhere 5.5.00 su QNX, prima di eseguire lo script di configurazione: CPPFLAGS="-DODBC_QNX -DSQLANY_BUG" LDFLAGS=-lunix CUSTOM_ODBC_LIBS="-ldblib -lodbc".
Include il supporto per iODBC. DIR indica la directory di installazione di iODBC, il default è /usr/local.
Include il supporto per Easysoft OOB. DIR indica la directory di installazione di OOB, il default è /usr/local/easysoft/oob/client.
Include il supporto per unixODBC. DIR indica la directory di installazione di unixODBC, il default è /usr/local.
Include il supporto per OpenLink ODBC. DIR indica la directory di installazione di OpenLink, il default è /usr/local. This is the same as iODBC.
Include il supporto per DBMaker. DIR indica la directory di installazione di DBMaker, per default si ha la directory in cui è installata l'ultima versione di DBMaker (tipo /home/dbmaker/3.6).
Per disabilitare il supporto alle funzioni ODBC unificate in PHP 3 aggiungere il parametro --disable-unified-odbc nella linea di configurazione. Ciò è applicabile soltanto se è abilitata una delle seguenti interfaccie: iODBC, Adabas, Solid, Velocis oppure una versione personalizzata di ODBC.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Parametrizzazione per il modulo Funzioni ODBC Unificate
Nome | Default | Modificabile | Log delle modifiche |
---|---|---|---|
odbc.default_db * | NULL | PHP_INI_ALL | |
odbc.default_user * | NULL | PHP_INI_ALL | |
odbc.default_pw * | NULL | PHP_INI_ALL | |
odbc.allow_persistent | "1" | PHP_INI_SYSTEM | |
odbc.check_persistent | "1" | PHP_INI_SYSTEM | |
odbc.max_persistent | "-1" | PHP_INI_SYSTEM | |
odbc.max_links | "-1" | PHP_INI_SYSTEM | |
odbc.defaultlrl | "4096" | PHP_INI_ALL | |
odbc.defaultbinmode | "1" | PHP_INI_ALL |
Nota: I parametri segnati con * non sono ancora implementati.
Breve descrizione dei parametri di configurazione.
Sorgenti di dati ODBC da utilizzare se non viene fornita in odbc_connect() o odbc_pconnect().
Nome utente da usare se non viene passato nelle funzioni odbc_connect() o odbc_pconnect().
Password da usare se non viene passato nelle funzioni odbc_connect() o odbc_pconnect().
Indica se permettere le connessioni ODBC persistenti.
Verifica se una connessione è ancora valida prima di ri-utilizzarla.
Imposta il numero massimo di connessioni persistenti permesse per processo.
Imposta il numero massimo di connessioni permesse per processo, comprese le connessioni persistenti.
Gestisce i campi di tipo LONG. Specifica il numero di byte da ritornare alla variabile.
When an integer is used, the value is measured in bytes. You may also use shorthand notation as described in this FAQ.
Gestione dei dati binari.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Se non viene fornito il parametro OnOff, la funzione restituisce lo stato dell'auto-commit per id_connessione. Il valore reso è vero se l'autocommit è attivo, altrimenti falso se non è attivato oppure si verifica un errore.
Se il campo OnOff è posto a vero, l' auto-commit è abilitato, se è valorizzato a falso l'auto-commit è disabilitato. La funzione restituisce TRUE se l'operazione riesce, FALSE se si verifica un errore.
Per default, l'auto-commit è abilitato. La disabilitazione dell'auto-commit equivale ad iniziare una transazione.
Vedere inoltre odbc_commit() e odbc_rollback().
(Tipi di campi ODBC SQL coinvolti: BINARY, VARBINARY, LONGVARBINARY)
ODBC_BINMODE_PASSTHRU: Restituzione del dato binario direttamente al client
ODBC_BINMODE_RETURN: restituisce il dato inalterato
ODBC_BINMODE_CONVERT: Conversione in char
Quando si esegue la conversione da dati binari SQL a dati di tipo char del C, ciascun byte ( 8 bits) dei dati sorgenti vengono rappresentati da 2 caratteri ASCII. Questi caratteri sono la rappresentazione ASCII dei numeri nella loro forma esadecimale. Ad esempio, il valore binario 00000001 è convertito in "01" e il valore binario 11111111 è convertito come "FF".
Tabella 1. Gestione del tipo LONGVARBINARY
Modalità | Impostazione di longreadlen | Comportamento |
---|---|---|
ODBC_BINMODE_PASSTHRU | 0 | direttamente al client |
ODBC_BINMODE_RETURN | 0 | direttamente al client |
ODBC_BINMODE_CONVERT | 0 | direttamente al client |
ODBC_BINMODE_PASSTHRU | 0 | passthru |
ODBC_BINMODE_PASSTHRU | >0 | direttamente al client |
ODBC_BINMODE_RETURN | >0 | restituito inalterato |
ODBC_BINMODE_CONVERT | >0 | restituito come char |
Se viene utilizzata odbc_fetch_into(), nei casi in cui il dato viene inviato direttamente al client, quest'ultima restituisce una stringa vuota per le colonne binarie.
Se l'argomento id_risultato è valorizzato a 0, il settaggio viene applicato come default per i nuovi risultati.
Nota: I valori di default per longreadlen è 4096, mentre la modalità di default è ODBC_BINMODE_RETURN. La gestione delle colonne di campi long binary, è anche gestita dalla funzione odbc_longreadlen()
La funzione odbc_close_all() chiude tutte le connessioni aperte con il database server
Nota: Se ci sono delle transazioni aperte sulla connessione richiesta, la funzione fallisce. In questo caso la connessione resta aperta.
odbc_close() chiude la connessione con il database server associata all'identificativo di connessione indicato.
Nota: Se ci sono delle transazioni aperte sulla connessione richiesta, la funzione fallisce. In questo caso la connessione resta aperta.
(PHP 4, PHP 5)
odbc_columnprivileges -- Restituisce un identificatore di risultato che permette di ricavare l'elenco delle colonne e dei privilegi ad esse associati.Elenca le colonne e i privilegi associati ad esse per la tabella data. La funzione ritorna un identificatore di risultato ODBC oppure FALSE se si verifica un errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
GRANTOR
GRANTEE
PRIVILEGE
IS_GRANTABLE
I campi di ordinamento delle righe risultanti sono TABLE_QUALIFIER, TABLE_OWNER e TABLE_NAME.
L'argomento nome_colonna accetta dei criteri di ricerca ('%' per indicare zero o più caratteri e '_' per indicare un singolo carattere).
Elenca i nomi di tutte le colonne presenti nel range richiesto. La funzione restituisce un identificatore di risultato ODBC oppure FALSE se si verifica un errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
TABLE_QUALIFIER
TABLE_SCHKM
TABLE_NAME
COLUMN_NAME
DATA_TYPE
TYPE_NAME
PRECISION
LENGTH
SCALE
RADIX
NULLABLE
REMARKS
I campi di ordinamento delle righe risultanti sono TABLE_QUALIFIER, TABLE_SCHKM e TABLE_NAME.
Gli argomenti schema, nome_tabella e nome_colonna accettano dei criteri di ricerca ('%' per indicare zero o più caratteri e '_' per indicare un singolo carattere).
Vedere anche odbc_columnprivileges() per ottenere i privilegi associati alle colonne.
La funzione odbc_commit() esegue tutte le transazioni pendenti sulla connessione indicata dall'argomento id_connessione. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Restituisce un identificatore di connessione ODBC oppure 0 (falso) se si verifica un errore.
L'identificatore di connessione ritornato da questa funzione è utilizzato dalle altre funzioni ODBC. Si possono avere più connessioni aperte contemporaneamente se queste utlizzano differenti database o differenti credenziali utente. Il quarto parametro (opzionale), setta il tipo di cursore da utilizzare per questa connessione. Normalmente questo parametro non è necessario, ma può essere utilizzato per aggirare dei problemi che si manifestano con alcuni driver ODBC.
Con alcuni driver ODBC, l'esecuzione di complesse procedure può generare un errore tipo: "Non si riesce ad aprire un cursore sulla procedura che richieda qualsiasi cosa oltre ad un singola istruzione select". L'uso di SQL_CUR_USE_ODBC, può evitare questo errore. Inoltre alcuni driver non supportano il parametro row_number della funzione odbc_fetch_row(). In questo caso SQL_CUR_USE_ODBC può essere d'aiuto.
Il campo tipo_cursore può assumere le seguenti costanti:
SQL_CUR_USE_IF_NEEDED
SQL_CUR_USE_ODBC
SQL_CUR_USE_DRIVER
SQL_CUR_DEFAULT
Per le connessioni persistenti vedere odbc_pconnect().
odbc_cursor restituisce il nome del cursore per l'argomento id_risultato.
La funzione restituisce FALSE se si verifica un errore, oppure un array se ha successo.
Questa funzione restituisce la listya dei DNS disponibili ( dopo essere stata richiamata diverse volte). E' obbligatorio che il parametro connection_id sia una connessione ODBC valida. Il parametro fetch_type può essere impostato ad una delle seguenti costanti: SQL_FETCH_FIRST oppure SQL_FETCH_NEXT. Utilizzare SQL_FETCH_FIRST la prima volta che si richiama la funzione, SQL_FETCH_NEXT le volte successive.
odbc_do() esegue una query sulla connessione data.
La funzione restituisce un codice di 6 cifre indicante lo stato di ODBC. Se non vi sono errori viene restituita una stringa vuota. Se viene passato il parametro id_connessione, viene restituito l'ultimo stato di questa connessione, altrimenti si ha l'ultimo stato dell'ultima operazione su una qualsiasi connessione.
Questa funzione restituisce valori sensati se l'ultima query ODBC è fallita (ad esempio odbc_exec() restituisce FALSE).
Vedere anche: odbc_errormsg() e odbc_exec().
la funzione restituisce una stringa contenente l'ultimo messaggio di errore generato da ODBC, oppure una stringa vuota se non ci sono errori. Se viene passato il parametro id_connessione, viene restituito l'ultimo stato di questa connessione, altrimenti si ha l'ultimo stato dell'ultima operazione su una qualsiasi connessione.
Questa funzione restituisce valori sensati se l'ultima query ODBC è fallita (ad esempio odbc_exec() restituisce FALSE).
Vedere anche: odbc_error() and odbc_exec().
Restituisce FALSE se si verifica un errore. Restituisce un identificatore del risultato ODBC se l'espressione SQL viene eseguita correttamente.
odbc_exec() invia una espressione SQL al server tramite la connessione specificata da id_connessione. Questo parametro deve essere un identificativo valido restituito da odbc_connect() oppure odbc_pconnect().
Vedere anche: odbc_prepare() e odbc_execute() per l'esecuzione di molteplici espressioni SQL.
Esegue una espressione SQL memorizzata tramite la funzione odbc_prepare(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento. L'array array_parametri occorre soltanto se è necessario fornire parametri all'espressione.
I parametri in array_parametri saranno sostituiti dai segnaposto nell'ordine dell'espressione predisposta.
Qualsiasi parametro in array_parametri che inizia e finisce con gli apici singoli sarà considerato come il nome di un file da leggere e inviare al database server come dati per gli appropriati segnaposto.
Nota: Dalla versione 4.1.1 la funzionalità di lettura del file ha le seguenti restrizioni:
La lettura del file non è soggetta alle restrizioni di modalità sicura o open-basedir. Questo sarà risolto nella versione 4.2.0 di PHP.
File remoti non sono supportati.
Se si desidera archiviare una stringa che inizia e termina con l'apice singolo, occorre farla precedere dal carattere di escape, oppure da un'altro carattere all'inizio o alla fine del parametro, per prevenire che il parametro sia considerato come nome di un file. Se questo non è possibile occorre utilizzare altri meccanismi per archiviare la stringa, quali, ad esempio, eseguire direttamente la query con odbc_exec().
Scarica, in una matrice associativa, da una query ODBC. Vedere nel successivo log delle modifiche per sapere quando questa funzione è disponibile.
Risorsa risultato da odbc_exec().
Opzionale, indica quale nnumero di riga recuperare.
Restituisce una matrice corrispondente alla riga scaricata, oppure FALSE se non vi sono righe successive.
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
odbc_fetch_into -- Scarica una riga del risultato della query in un arrayLa funzione restituisce il numero di colonne presenti nel risultato; FALSE se si verifica un errore. Il parametro array_dati deve essere passato per referenza, ma può essere di qualsiasi tipo dato che verrà convertito in array. Nell'array saranno posti i valori delle colonne di una riga tratta dalla tabella risultante dalla query a partire dall'indice 0.
A partire dalla versione 4.0.5 di PHP non occorre passare il parametro array_dati per riferimento.
A partire dall versione 4.0.6 di PHP il parametro numero_riga non può essere passato come costante, ma come variabile.
A partire dalla versione 4.2.0 di PHP i parametri array_dati e numero_riga sono stati invertiti. Questo permette al parametro numero_riga di essere ancora una costante. Questa è l'ultima variazione alla funzione.
Scarica un oggetto da una query ODBC. Vedere nel successivo log delle modifiche per sapere quando questa funzione è disponibile.
Risorsa risultato da odbc_exec().
Opzionale, indica quale nnumero di riga recuperare.
Restituisce un oggetto corrispondente alla riga scaricata, oppure FALSE se non vi sono righe successive.
Se odbc_fetch_row() ha successo (c'è almeno una riga), la funzione restituisce TRUE. Altrimenti, se non vi sono più righe, la funzione restituisce FALSE.
odbc_fetch_row() estrae un record dai dati restituiti dalle funzioni odbc_do() / odbc_exec(). Dopo l'esecuzione di odbc_fetch_row(), i campi della riga sono accessibili tramite la funzione odbc_result().
Se non viene specificato il parametro numero_riga, odbc_fetch_row() restituisce la riga successiva dal set delle righe risultanti dalla query. Si può intercalare esecuzioni successive di odbc_fetch_row() con e senza il parametro numero_riga.
Per spostarsi attraverso le righe risultanti, si può eseguire odbc_fetch_row() con il parametro numero_riga impostato a 1, e quindi continuare ad utilizzare odbc_fetch_row() senza numero_riga. Se il driver non supporta l'estrazione di una riga per numero, il campo numero_riga sarà ignorato.
All'interno di un set di righe, referenziate dall'identificativo di risultato ODBC fornito, la funzione odbc_field_len() restituisce la dimensione (precisione) del campo indicato dall'argomento. La numerazione dei campi parte da 1.
Vedere anche: odbc_field_scale() per ottenere la scala di un numero in virgola mobile.
La funzione odbc_field_name() restituisce il nome del campo presente nella colonna richiesta all'interno di un risultato ODBC identificato dal'argomento id_risultato. La numerazione delle colonne parte da 1. La funzione restituisce falso se si verifica un errore.
odbc_field_num() restituisce il numero della colonna in cui si trova il campo richiesto all'interno di un risultato ODBC indicato dall'argomento id_risultato. La numerazione delle colonne parte da 1. Si ottiene FALSE se si verifica un errore.
All'interno di un set di righe, referenziate dall'identificativo di risultato ODBC fornito, la funzione odbc_field_precision() restituisce la precisione del campo indicato dal numero di campo indicato.
Vedere anche: odbc_field_scale() per ottenere la scala di un numero in virgola mobile.
All'interno di un set di righe, referenziate dall'identificativo di risultato ODBC fornito, la funzione odbc_field_scale() restituisce la scala del campo indicato dal numero di campo indicato.
La funzione odbc_field_type() restituisce il tipo di dato SQL del campo indicato dal numero all'interno di un set di righe referenziate dall'identificativo di risultato ODBC passato. La numerazione delle colonne parte da 1.
(PHP 4, PHP 5)
odbc_foreignkeys -- Restituisce l'elenco delle chiavi esterne per la tabella indicata, oppure la lista delle chiavi esterne in altre tabelle che fanno riferimento alla chiave primaria della tabella indicata.La funzione odbc_foreignkeys() ritorna informazioni sulle chiavi esterne. Restituisce un identificatore di risultato oppure FALSE se si verifica un errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
PKTABLE_QUALIFIER
PKTABLE_OWNER
PKTABLE_NAME
PKCOLUMN_NAME
FKTABLE_QUALIFIER
FKTABLE_OWNER
FKTABLE_NAME
FKCOLUMN_NAME
KEY_SEQ
UPDATE_RULE
DELETE_RULE
FK_NAME
PK_NAME
Se l'argomento pk_tabella contiene il nome di una tabella, la funzione odbc_foreignkeys() ritorna una serie di righe contenenti i dati della chiave primaria della tabella e di tutte le chiavi esterne che hanno riferimenti a questa.
Se l'argomento fk_tabella contiene il nome di una tabella, la funzione odbc_foreignkeys() ritorna una serie di righe contenenti i dati delle chiavi esterne della tabella e delle chiavi primarie ( di altre tabelle ) a cui queste hanno riferimenti.
Se entrambi gli argomenti pk_tabella e fk_tabella contengono nomi di tabelle, odbc_foreignkeys() restituisce le chiavi esterne della tabella specificata in fk_tabella che hanno riferimenti alla chiave primaria della tabella indicata in pk_tabella. La funzione dovrebbe trovare almeno una chiave.
Restituisce sempre TRUE.
La funzione odbc_free_result() permette di non utilizzare molta memoria durante l'esecuzione di uno script. Infatti, se si è sicuri di non avere più bisogno dei dati del risultato, si può eseguire odbc_free_result(), e la memoria associata a id_risultato sarà liberata. Se la funzione non viene utilizzata, le aree di memoria resteranno disponibili per tutta la durata dello script. Al termine verranno liberate in modo automatico.
Nota: Se si ha l'auto-commit disabilitato (vedere odbc_autocommit()) e si esegue odbc_free_result() prima di eseguire il commit, tutte le transazioni pendenti saranno annullate,
(PHP 4, PHP 5)
odbc_gettypeinfo -- Restituisce un identificatore di risultato contenente informazioni sui tipi di dati supportati dalla sorgente di datiRecupera informazioni sui tipi di dati supportati dalla sorgente di dati. La funzione restituisce un identificatore di risultato ODBC oppure FALSE su errore. L'argomento opzionale tipo_dato può essere utilizzato per restringere l'informazione su un singolo tipo.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
TYPE_NAME
DATA_TYPE
PRECISION
LITERAL_PREFIX
LITERAL_SUFFIX
CREATE_PARAMS
NULLABLE
CASE_SENSITIVE
SEARCHABLE
UNSIGNED_ATTRIBUTE
MONEY
AUTO_INCREMENT
LOCAL_TYPE_NAME
MINIMUM_SCALE
MAXIMUM_SCALE
I campi di ordinamento delle righe risultanti sono DATA_TYPE e TYPE_NAME.
(tipi di campi ODBC ed SQL coinvolti: LONG, LONGVARBINARY) Tramite l'argomento lunghezza si controlla il numero di byte da ritornare a PHP. Se il campo viene posto a 0, i dati della colonna saranno passati direttamente al client.
Nota: Per la gestione delle colonne di tipo LONGVARBINARY si utilizza anche odbc_binmode().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
All'interno di un set di righe, referenziate dall'identificativo di risultato ODBC fornito, la funzione odbc_num_fields() restituisce il numero di campi (colonne) presenti. La funzione restituisce -1 se si verifica un errore. L'argomento fornito è un identificatore di esito restituito dalla funzione odbc_exec().
odbc_num_rows() ritorna il numero di record presenti in un risultato ODBC. La funzione ritorna -1 se si verifica un errore. Per le clausole INSERT, UPDATE e DELETE, odbc_num_rows() ritorna il numero di righe coinvolte. Nella clausola SELECT questo può essere il numero di righe disponibili.
Nota: Con diversi driver, la funzione odbc_num_rows(), utilizzata con lo scopo di determinare il numero di righe dopo una SELECT, restituisce -1.
Restituisce un identificatore di connessione ODBC oppure 0 (FALSE) su errore. Questa funzione è molto simile a odbc_connect(), eccetto che la connessione non viene realmente chiusa quando lo script finisce. Successive richieste di connessione che utilizzino la stessa combinazione di dsn, utente, password (eseguite sia utilizzando odbc_connect(), sia utilizzando odbc_pconnect()) possono riutilizzare la connessione.
Nota: Le connessioni persistenti non hanno effetti se PHP viene utilizzato come programma CGI.
Per informazioni sul campo opzionale tipo_cursore, vedere la funzione odbc_connect(). Per maggiori dettagli sulle connessioni persistenti, fare riferimento alla FAQ di PHP.
La funzione restituisce FALSE su errore.
Restituisce un identificativo di risultato ODBC se l'espressione SQL viene predisposta correttamente. L'identificativo restituito può essere utilizzato successivamente per eseguire l'espressione utilizzando la funzione odbc_execute().
Alcuni database (tipo IBM DB2, MS SQL server e Oracle) gestiscono le le stored procedure che accettano parametri di tipo IN, INOUT e OUT come definito nelle specifiche ODBC. Tuttavia il driver Unified ODBC supporta soltanto i parametri di tipo IN.
Nel seguente codice, $res sarà valido soltanto se tutti i tre parametri per myproc sono di tipo IN:
<?php $a = 1; $b = 2; $c = 3; $stmt = odbc_prepare($conn, 'CALL myproc(?,?,?)'); $res = odbc_execute($stmt, array($a, $b, $c)); ?> |
(PHP 4, PHP 5)
odbc_primarykeys -- Restituisce un identificatore di risultato che può essere utilizzato per ricavare il nome della colonna che contiene la chiave primaria della tabella.Restituisce il nome della colonna che contiene la chiave primaria per la tabella. La funzione ritorna un identificatore di risultato ODBC oppure FALSE se si verifica un errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
COLUMN_NAME
KEY_SEQ
PK_NAME
La funzione ritorna la lista dei parametri di input e di output e anche delle colonne che concorrono al determinazione del risultato per le procedure indicate. Viene restituito un identificatore di risultato oppure FALSE se si è un errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
PROCEDURE_QUALIFIER
PROCEDURE_OWNER
PROCEDURE_NAME
COLUMN_NAME
COLUMN_TYPE
DATA_TYPE
TYPE_NAME
PRECISION
LENGTH
SCALE
RADIX
NULLABLE
REMARKS
I campi di ordinamento delle righe risultanti sono PROCEDURE_QUALIFIER, PROCEDURE_OWNER, PROCEDURE_NAME e COLUMN_TYPE.
Gli argomenti proprietario, procedura e colonna accettano dei criteri di ricerca ('%' per indicare zero o più caratteri e '_' per indicare un singolo carattere).
(PHP 4, PHP 5)
odbc_procedures -- Restituisce l'elenco delle procedure memorizzate in una specifica sorgente di dati.Si ottiene l'elenco di tutte le procedure presenti nei limiti richiesti. La funzione restituisce un identificatore di risultato, oppure FALSE su errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
PROCEDURE_QUALIFIER
PROCEDURE_OWNER
PROCEDURE_NAME
NUM_INPUT_PARAMS
NUM_OUTPUT_PARAMS
NUM_RESULT_SETS
REMARKS
PROCEDURE_TYPE
Gli argomenti proprietario e nome accettano dei criteri di ricerca ('%' per indicare zero o più caratteri e '_' per indicare un singolo carattere).
Restituisce il numero di righe elaborate, oppure FALSE se si verifica un errore.
Dato un identificatore di risultato restituito da odbc_exec(), la funzione odbc_result_all() visualizza tutti i record ottenuti in una di tabella in formato HTML. Utilizzando il parametro opzionale formato, è possibile fornire informazioni addizionali sulla formattazione della tabella.
Restituisce il contenuto dei campi.
Il parametro campo può essere sia un intero indicante il numero di colonna del campo desiderato; sia una stringa contenente il nome del campo. Ad esempio:
Nel primo caso l'esecuzione di odbc_result() restituisce il valore del terzo campo del record corrente della query. Nel secondo, la funzione odbc_result() restituisce il valore del campo il cui nome è "val", sempre utilizzando i dati dal record corrente. Si ha un errore qualora il numero di colonna fornito sia minore di 1 oppure sia superiore al numero delle colonne (o campi) presenti nel record corrente. Analogamente, si ottiene un errore se il nome del campo richiesto non sia presente nella tabella/e oggetto della ricerca.
L'indice dei campi parte da 1. Per quanto riguarda la gestione dei campi di tipo binario o long fare riferimento a odbc_binmode() e a odbc_longreadlen().
Annulla tutte le operazioni pendenti sulla connessione indicata da id_connessione. Se ha successo restituisce TRUE, altrimenti FALSE.
Questa funzione permette di manipolare i parametri ODBC per la connessione o il risultato di una query indicati. La funzione è stata sviluppata per permettere di aggirare dei problemi emersi in alcuni driver ODBC. Pertanto si dovrebbe utilizzare questa funzione soltanto se si è dei programmatori e si conoscono gli effetti generati dalle varie opzioni. Dato che ogni singola versione di driver ODBC supporta differenti parametri, occorre avere a disposizione un buon manuale del driver per avere esposti tutti i differenti settaggi che possono essere utilizzati.
Poiché i parametri possono variare in base al driver ODBC, è fortemente sconsigliato l'uso di questa funzione in script resi pubblici. Inoltre, alcune opzioni di ODBC non sono gestibili da questa funzione, dato che devono essere specificate prima di stabilire la connessione o prima della preparazione della query. Tuttavia, se per un particolare lavoro permette al PHP di funzionare, può evitare il ricorso a prodotti commerciali.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il campo identificativo indica la connessione o l'esito su cui si varia il settaggio. Per la funzione SQLSetConnectOption(), questo indica l'identificativo di connessione, per SQLSetStmtOption(), indica l'identificativo del risultato.
Il campo funzione indica quale funzione ODBC utilizzare. Dovrebbe essere valorizzato a 1 per SQLSetConnectOption() e a 2 per SQLSetStmtOption().
Il parametro opzione indica l'opzione da settare.
Il campo parametro indica il valore per l'opzione richiesta.
Esempio 1. Esempi di utilizzo
|
(PHP 4, PHP 5)
odbc_specialcolumns -- Restituisce sia il set di colonne che identificano in modo univoco una riga nella tabella, sia colonne che sono automaticamente aggiornate quando un qualsiasi campo della riga viene aggiornato da una transazione.Quando l'argomento tipo è impostato a SQL_BEST_ROWID, odbc_specialcolumns() restituisce la colonna o le colonne che identificano in modo univoco ciascuna riga nella tabella.
Quando l'argomento tipo è impostato a SQL_ROWVER, odbc_specialcolumns() restituisce la colonna o le colonne della tabella indicata, se ve ne sono, che sono state aggiornate automaticamente dalla sorgente dati quando un qualsiasi campo della riga è stato aggiornato da una transazione.
La funzione restituisce un identificatore di risultato ODBC, oppure FALSE su errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
SCOPE
COLUMN_NAME
DATA_TYPE
TYPE_NAME
PRECISION
LENGTH
SCALE
PSEUDO_COLUMN
Le righe del risultato sono ordinate in base alla colonna SCOPE.
Si ottengono informazioni statistiche sulla tabella e i propri indici. La funzione restituisce un identificatore di risultato ODBC, oppure FALSE su errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
NON_UNIQUE
INDEX_QUALIFIER
INDEX_NAME
TYPE
SEQ_IN_INDEX
COLUMN_NAME
COLLATION
CARDINALITY
PAGES
FILTER_CONDITION
I campi di ordinamento delle righe risultanti sono NON_UNIQUE, TYPE, INDEX_QUALIFIER, INDEX_NAME e SEQ_IN_INDEX.
Elenca le tabelle presenti nei limiti richiesti e, per ciascuna di queste, ne fornisce i privilegi. La funzione ritorna un identificatore di risultato ODBC, oppure FALSE su errore.
Le righe risultanti dall'elaborazione hanno i seguenti campi:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
GRANTOR
GRANTEE
PRIVILEGE
IS_GRANTABLE
I campi di ordinamento delle righe risultanti sono TABLE_QUALIFIER, TABLE_OWNER e TABLE_NAME.
Gli argomenti proprietario e nome accettano dei criteri di ricerca ('%' per indicare zero o più caratteri e '_' per indicare un singolo carattere).
(PHP 3 >= 3.0.17, PHP 4, PHP 5)
odbc_tables -- Restituisce l'elenco delle tabelle presenti in una specifica sorgente di datiLa funzione elenca tutte le tabelle presenti nei limiti richiesti. Restituisce un identificatore di risultato in cui vi sono i dati oppure FALSE se si verifica un errore.
Le righe risultanti hanno i seguenti campi:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
TABLE_TYPE
REMARKS
I campi di ordinamento delle righe risultanti sono TABLE_TYPE, TABLE_QUALIFIER, TABLE_OWNER e TABLE_NAME.
Gli argomenti proprietario e nome accettano dei criteri di ricerca ('%' per indicare zero o più caratteri e '_' per indicare un singolo carattere).
Per supportare l'enumerazione delle qualifiche, dei proprietari e dei tipi tabelle, è stata predisposta la seguente semantica per i campi qualifica, proprietario, nome, e tipo:
Se l'argomento qualifica è valorizzato con il carattere percento (%) e i parametri proprietario e nome sono delle stringhe vuote, il risultato sarà un set di righe contenente la lista delle qualifiche previste per la sorgente di dati. (Tutte le colonne tranne TABLE_QUALIFIER conterranno NULL.)
Se l'argomento proprietario è valorizzato con il carattere percento (%) e i parametri qualifica e nome sono delle stringhe vuote, il risultato sarà un set di righe contenente la lista dei proprietari previsti per la sorgente di dati. (Tutte le colonne tranne TABLE_OWNER conterranno NULL.)
Se l'argomento tipo è valorizzato con il carattere percento (%) e i parametri qualifica, proprietario e nome sono delle stringhe vuote, il risultato sarà un set di righe contenente la lista dei tipi di tabella previsti per la sorgente di dati. (Tutte le colonne tranne TABLE_TYPE conterranno NULL.)
Se l'argomento tipo non è una stinga vuota, deve contenere l'elenco dei tipi interessati separati dalla virgola; ogni singolo valore può essere, o meno, racchiuso tra apici singoli ('). Ad esempio: "'TABLE','VIEW'" o "TABLE, VIEW" sono valori validi. Se la sorgente di dati non supporta alcuni dei tipi di tabelle specificati, per questi, la funzione odbc_tables() non riporta alcuna informazione.
Vedere inoltre odbc_tableprivileges() per ottenere i privilegi associati alla tabella.
PDO_ODBC is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to databases through ODBC drivers or through the IBM DB2 Call Level Interface (DB2 CLI) library. PDO_ODBC currently supports three different "flavours" of database drivers:
Supports access to IBM DB2 Universal Database, Cloudscape, and Apache Derby servers through the free DB2 client.
Supports access to database servers through the unixODBC driver manager and the database's own ODBC drivers.
Offers a compile option for ODBC driver managers that are not explicitly supported by PDO_ODBC.
On Windows, PDO_ODBC is built into the PHP core by default. It is linked against the Windows ODBC Driver Manager so that PHP can connect to any database cataloged as a System DSN, and is the recommended driver for connecting to Microsoft SQL Server databases.
As of PHP 5.1, PDO_ODBC is included in the PHP source. You can compile the PDO_ODBC extension as either a static or shared module using the following configure commands.
./configure --enable-pdo_odbc=ibm-db2,/opt/IBM/db2/V8.1/ |
If you do not supply a location for the DB2 libraries and headers to the configure command, PDO_ODBC defaults to /home/db2inst1/sqllib.
./configure --enable-pdo_odbc=unixODBC,/usr/local |
./configure --enable-pdo_odbc=generic,/usr/local,libname,ldflags,cflags |
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. PDO_ODBC Configuration Options
Name | Default | Changeable | Changelog |
---|---|---|---|
pdo_odbc.connection_pooling | "strict" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
Whether to pool ODBC connections. Can be one of "strict", "relaxed" or "off" (equals to ""). The parameter describes how strict the connection manager should be when matching connection parameters to existing pooled connections. strict is the recommend default, and will result in the use of cached connections only when all the connection parameters match exactly. relaxed will result in the use of cached connections when similar connection parameters are used. This can result in increased use of the cache, at the risk of bleeding connection information between (for example) virtual hosts.
This setting can only be changed from the php.ini file, and affects the entire process; any other modules loaded into the process that use the same ODBC libraries will be affected too, including the Unified ODBC extension.
Avvertimento |
relaxed matching should not be used on a shared server, for security reasons. |
Suggerimento: Leave this setting at the default strict setting unless you have good reason to change it.
The PDO_ODBC Data Source Name (DSN) is composed of the following elements:
The DSN prefix is odbc:. If you are connecting to a database cataloged in the ODBC driver manager or the DB2 catalog, you can append the cataloged name of the database to the DSN.
The name of the database as cataloged in the ODBC driver manager or the DB2 catalog. Alternately, you can provide a complete ODBC connection string to connect to a database as described at http://connectionstrings.com/.
The name of the user for the connection. If you specify the user name in the DSN, PDO ignores the value of the user name argument in the PDO constructor.
The password of the user for the connection. If you specify the password in the DSN, PDO ignores the value of the password argument in the PDO constructor.
The OGG/Vorbis file format, as defined by http://www.vorbis.com/ and http://www.vorbis.com/, is a scheme for compressing audio streams by multiple factors with a minimum of quality loss. This extension adds Ogg Vorbis support to PHP's URL Wrappers. When used in read mode, compressed OGG/Vorbis data is expanded to raw PCM audio in one of six PCM encoding formats listed below.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
oggvorbis is installed through the usual PECL package installation process.
$ pear install oggvorbis |
Copy the resulting oggvorbis.so to an appropriate location and add extension=oggvorbis.so to your php.ini file or load it dynamically in your PHP script using dl('oggvorbis.so');
Tabella 1. OGG/Vorbis tuning options
Option | Definition | Relevance | Default |
---|---|---|---|
pcm_mode | PCM byte encoding used. See constants below. | Read / Write | OGGVORBIS_PCM_S16_LE |
rate | PCM Sampling rate. Measured in Hz. | Write only | 44100 |
bitrate | Vorbis Average Bitrate Encoding / Variable Bitrate Encoding. Measured in bps (ABR) or Quality level (VBR: 0.0 to 1.0). 128000 ABR is rough equal to 0.4 VBR. | Write only | 128000 |
channels | Number of PCM channels. 1 == Mono, 2 == Stereo. | Write only | 2 |
serialno | Serial Number of stream within file. Must be unique within file. Because of the potential to select a duplicate serial number within a chained file, make efforts to manually assign unique numbers when encoding. | Write only | Random |
comments | Associative array of file comments. Will be translated to strtoupper($name) . "=$value". Note: This context option is not available in oggvorbis-0.1 | Write only | array('ENCODER' => 'PHP/OggVorbis, http://pear.php.net/oggvorbis') |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 2. OGG/Vorbis supports PCM encodings in the following formats
Constant | Definition |
---|---|
OGGVORBIS_PCM_U8 | Unsigned 8-bit PCM. |
OGGVORBIS_PCM_S8 | Signed 8-bit PCM. |
OGGVORBIS_PCM_U16_LE | Unsigned 16-bit PCM. Little Endian byte order. |
OGGVORBIS_PCM_U16_BE | Unsigned 16-bit PCM. Big Endian byte order. |
OGGVORBIS_PCM_S16_LE | Signed 16-bit PCM. Little Endian byte order. |
OGGVORBIS_PCM_S16_BE | Signed 16-bit PCM. Big Endian byte order. |
Esempio 1. Reading an OGG/Vorbis file
|
Esempio 2. Encode an audio file to OGG/Vorbis
|
Platform independent audio bindings. Requires the OpenAL library.
This PECL extension is not bundled with PHP.
Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/openal.
You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
This extension defines four resource types: Open AL(Device) - Returned by openal_device_open(), Open AL(Context) - Returned by openal_context_create(), Open AL(Buffer) - Returned by openal_buffer_create(), and Open AL(Source) - Returned by openal_source_create().
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Context Attribute
Context Attribute
Context Attribute
Buffer Setting
Buffer Setting
Buffer Setting
Buffer Setting
Source/Listener Setting (Integer)
Source/Listener Setting (Integer)
Source/Listener Setting (Integer)
Source/Listener Setting (Float)
Source/Listener Setting (Float)
Source/Listener Setting (Float)
Source/Listener Setting (Float)
Source/Listener Setting (Float)
Source/Listener Setting (Float)
Source/Listener Setting (Float)
Source/Listener Setting (Float)
Source/Listener Setting (Float)
Source/Listener Setting (Float)
Source/Listener Setting (Float Vector)
Source/Listener Setting (Float Vector)
Source/Listener Setting (Float Vector)
Source/Listener Setting (Float Vector)
PCM Format
PCM Format
PCM Format
PCM Format
Source State
Source State
Source State
Source State
Source State
Boolean value recognized by OpenAL
Boolean value recognized by OpenAL
An Open AL(Buffer) resource (previously created by openal_buffer_create()).
Format of data, one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 e AL_FORMAT_STEREO16
Block of binary audio data in the format and freq specified.
Frequency of data given in Hz.
An Open AL(Buffer) resource (previously created by openal_buffer_create()).
An Open AL(Buffer) resource (previously created by openal_buffer_create()).
Specific property, one of: AL_FREQUENCY, AL_BITS, AL_CHANNELS e AL_SIZE.
Returns an integer value appropriate to the property requested or FALSE on failure.
An Open AL(Buffer) resource (previously created by openal_buffer_create()).
Path to .WAV file on local file system.
An Open AL(Device) resource (previously created by openal_device_open()).
An Open AL(Context) resource (previously created by openal_context_create()).
An Open AL(Context) resource (previously created by openal_context_create()).
An Open AL(Context) resource (previously created by openal_context_create()).
An Open AL(Context) resource (previously created by openal_context_create()).
An Open AL(Device) resource (previously created by openal_device_open()) to be closed.
Open an audio device optionally specified by device_desc. If device_desc is not specified the first available audio device will be used.
Property to retrieve, one of: AL_GAIN (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)) e AL_ORIENTATION (array(float,float,float)).
Property to set, one of: AL_GAIN (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)) e AL_ORIENTATION (array(float,float,float)).
Value to set, either float, or an array of floats as appropriate.
An Open AL(Source) resource (previously created by openal_source_create()).
An Open AL(Source) resource (previously created by openal_source_create()).
Property to get, one of: AL_SOURCE_RELATIVE (int), AL_SOURCE_STATE (int), AL_PITCH (float), AL_GAIN (float), AL_MIN_GAIN (float), AL_MAX_GAIN (float), AL_MAX_DISTANCE (float), AL_ROLLOFF_FACTOR (float), AL_CONE_OUTER_GAIN (float), AL_CONE_INNER_ANGLE (float), AL_CONE_OUTER_ANGLE (float), AL_REFERENCE_DISTANCE (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)), AL_DIRECTION (array(float,float,float)).
Returns the type associated with the property being retrieved or FALSE on failure.
An Open AL(Source) resource (previously created by openal_source_create()).
An Open AL(Source) resource (previously created by openal_source_create()).
An Open AL(Source) resource (previously created by openal_source_create()).
An Open AL(Source) resource (previously created by openal_source_create()).
Property to set, one of: AL_BUFFER (OpenAL(Source)), AL_LOOPING (bool), AL_SOURCE_RELATIVE (int), AL_SOURCE_STATE (int), AL_PITCH (float), AL_GAIN (float), AL_MIN_GAIN (float), AL_MAX_GAIN (float), AL_MAX_DISTANCE (float), AL_ROLLOFF_FACTOR (float), AL_CONE_OUTER_GAIN (float), AL_CONE_INNER_ANGLE (float), AL_CONE_OUTER_ANGLE (float), AL_REFERENCE_DISTANCE (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)), AL_DIRECTION (array(float,float,float)).
Value to assign to specified property. Refer to the description of property for a description of the value(s) expected.
An Open AL(Source) resource (previously created by openal_source_create()).
An Open AL(Source) resource (previously created by openal_source_create()).
Format of data, one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 e AL_FORMAT_STEREO16
Frequency of data to stream given in Hz.
This module uses the functions of OpenSSL for generation and verification of signatures and for sealing (encrypting) and opening (decrypting) data. OpenSSL offers many features that this module currently doesn't support. Some of these may be added in the future.
In order to use the OpenSSL functions you need to install the OpenSSL package. PHP between versions 4.0.5 and 4.3.1 will work with OpenSSL >= 0.9.5. Other versions (PHP <=4.0.4pl1 and >= 4.3.2) require OpenSSL >= 0.9.6.
Avvertimento |
You are strongly encouraged to use the most recent OpenSSL version, otherwise your web server could be vulnerable to attack. |
To use PHP's OpenSSL support you must also compile PHP --with-openssl[=DIR].
Note to Win32 Users: In order to enable this module on a Windows environment, you must copy libeay32.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)
Additionally, if you are planning to use the key generation and certificate signing functions, you will need to install a valid openssl.cnf on your system. As of PHP 4.3.0, we include a sample configuration file in the openssl folder of our win32 binary distribution. If you are using PHP 4.2.0 or later and are missing the file, you can obtain it from the OpenSSL home page or by downloading the PHP 4.3.0 release and using the configuration file from there.
Note to Win32 Users: PHP will search for the openssl.cnf using the following logic:
the OPENSSL_CONF environmental variable, if set, will be used as the path (including filename) of the configuration file.
the SSLEAY_CONF environmental variable, if set, will be used as the path (including filename) of the configuration file.
The file openssl.cnf will be assumed to be found in the default certificate area, as configured at the time that the openssl DLL was compiled. This is usually means that the default filename is c:\usr\local\ssl\openssl.cnf.
In your installation, you need to decide whether to install the configuration file at c:\usr\local\ssl\openssl.cnf or whether to install it someplace else and use environmental variables (possibly on a per-virtual-host basis) to locate the configuration file. Note that it is possible to override the default path from the script using the configargs of the functions that require a configuration file.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Quite a few of the openssl functions require a key or a certificate parameter. PHP 4.0.5 and earlier have to use a key or certificate resource returned by one of the openssl_get_xxx functions. Later versions may use one of the following methods:
Certificates
An X.509 resource returned from openssl_x509_read()
A string having the format file://path/to/cert.pem; the named file must contain a PEM encoded certificate
A string containing the content of a certificate, PEM encoded
Public/Private Keys
A key resource returned from openssl_get_publickey() or openssl_get_privatekey()
For public keys only: an X.509 resource
A string having the format file://path/to/file.pem - the named file must contain a PEM encoded certificate/private key (it may contain both)
A string containing the content of a certificate/key, PEM encoded
For private keys, you may also use the syntax array($key, $passphrase) where $key represents a key specified using the file:// or textual content notation above, and $passphrase represents a string containing the passphrase for that private key
When calling a function that will verify a signature/certificate, the cainfo parameter is an array containing file and directory names that specify the locations of trusted CA files. If a directory is specified, then it must be a correctly formed hashed directory as the openssl command would use.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
The S/MIME functions make use of flags which are specified using a bitfield which can include one or more of the following values:
Tabella 1. PKCS7 CONSTANTS
Constant | Description |
---|---|
PKCS7_TEXT | Adds text/plain content type headers to encrypted/signed message. If decrypting or verifying, it strips those headers from the output - if the decrypted or verified message is not of MIME type text/plain then an error will occur. |
PKCS7_BINARY | Normally the input message is converted to "canonical" format which is effectively using CR and LF as end of line: as required by the S/MIME specification. When this options is present, no translation occurs. This is useful when handling binary data which may not be in MIME format. |
PKCS7_NOINTERN | When verifying a message, certificates (if any) included in the message are normally searched for the signing certificate. With this option only the certificates specified in the extracerts parameter of openssl_pkcs7_verify() are used. The supplied certificates can still be used as untrusted CAs however. |
PKCS7_NOVERIFY | Do not verify the signers certificate of a signed message. |
PKCS7_NOCHAIN | Do not chain verification of signers certificates: that is don't use the certificates in the signed message as untrusted CAs. |
PKCS7_NOCERTS | When signing a message the signer's certificate is normally included - with this option it is excluded. This will reduce the size of the signed message but the verifier must have a copy of the signers certificate available locally (passed using the extracerts to openssl_pkcs7_verify() for example). |
PKCS7_NOATTR | Normally when a message is signed, a set of attributes are included which include the signing time and the supported symmetric algorithms. With this option they are not included. |
PKCS7_DETACHED | When signing a message, use cleartext signing with the MIME type multipart/signed. This is the default if you do not specify any flags to openssl_pkcs7_sign(). If you turn this option off, the message will be signed using opaque signing, which is more resistant to translation by mail relays but cannot be read by mail agents that do not support S/MIME. |
PKCS7_NOSIGS | Don't try and verify the signatures on a message |
Nota: These constants were added in 4.0.6.
openssl_csr_export_to_file() takes the Certificate Signing Request represented by csr and saves it as ascii-armoured text into the file named by outfilename.
The optional parameter notext affects the verbosity of the output; if it is FALSE then additional human-readable information is included in the output. The default value of notext is TRUE.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also openssl_csr_export(), openssl_csr_new() and openssl_csr_sign().
openssl_csr_export() takes the Certificate Signing Request represented by csr and stores it as ascii-armoured text into out, which is passed by reference.
The optional parameter notext affects the verbosity of the output; if it is FALSE then additional human-readable information is included in the output. The default value of notext is TRUE.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also openssl_csr_export_to_file(), openssl_csr_new() and openssl_csr_sign().
openssl_csr_new() generates a new CSR (Certificate Signing Request) based on the information provided by dn, which represents the Distinguished Name to be used in the certificate.
privkey should be set to a private key that was previously generated by openssl_pkey_new() (or otherwise obtained from the other openssl_pkey family of functions). The corresponding public portion of the key will be used to sign the CSR.
extraattribs is used to specify additional configuration options for the CSR. Both dn and extraattribs are associative arrays whose keys are converted to OIDs and applied to the relevant part of the request.
Nota: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.
By default, the information in your system openssl.conf is used to initialize the request; you can specify a configuration file section by setting the config_section_section key of configargs. You can also specify an alternative openssl configuration file by setting the value of the config key to the path of the file you want to use. The following keys, if present in configargs behave as their equivalents in the openssl.conf, as listed in the table below.
Tabella 1. Configuration overrides
configargs key | type | openssl.conf equivalent | description |
---|---|---|---|
digest_alg | string | default_md | Selects which digest method to use |
x509_extensions | string | x509_extensions | Selects which extensions should be used when creating an x509 certificate |
req_extensions | string | req_extensions | Selects which extensions should be used when creating a CSR |
private_key_bits | string | default_bits | Specifies how many bits should be used to generate a private key |
private_key_type | integer | none | Specifies the type of private key to create. This can be one of OPENSSL_KEYTYPE_DSA, OPENSSL_KEYTYPE_DH or OPENSSL_KEYTYPE_RSA. The default value is OPENSSL_KEYTYPE_RSA which is currently the only supported key type. |
encrypt_key | boolean | encrypt_key | Should an exported key (with passphrase) be encrypted? |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. openssl_csr_new() example - creating a self-signed-certificate
|
(PHP 4 >= 4.2.0, PHP 5)
openssl_csr_sign -- Sign a CSR with another certificate (or itself) and generate a certificateopenssl_csr_sign() generates an x509 certificate resource from the csr previously generated by openssl_csr_new(), but it can also be the path to a PEM encoded CSR when specified as file://path/to/csr or an exported string generated by openssl_csr_export(). The generated certificate will be signed by cacert. If cacert is NULL, the generated certificate will be a self-signed certificate. priv_key is the private key that corresponds to cacert. days specifies the length of time for which the generated certificate will be valid, in days. You can finetune the CSR signing by configargs. See openssl_csr_new() for more information about configargs. Since PHP 4.3.3 you can specify the serial number of issued certificate by serial. In earlier versions, it was always 0.
Returns an x509 certificate resource on success, FALSE on failure.
Nota: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.
Esempio 1. openssl_csr_sign() example - signing a CSR (how to implement your own CA)
|
Returns an error message string, or FALSE if there are no more error messages to return.
openssl_error_string() returns the last error from the openSSL library. Error messages are stacked, so this function should be called multiple times to collect all of the information.
openssl_free_key() frees the key associated with the specified key_identifier from memory.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. If successful the opened data is returned in open_data.
openssl_open() opens (decrypts) sealed_data using the private key associated with the key identifier priv_key_id and the envelope key env_key, and fills open_data with the decrypted data. The envelope key is generated when the data are sealed and can only be used by one specific private key. See openssl_seal() for more information.
Esempio 1. openssl_open() example
|
See also openssl_seal().
Decrypts the S/MIME encrypted message contained in the file specified by infilename using the certificate and its associated private key specified by recipcert and recipkey.
The decrypted message is output to the file specified by outfilename
Esempio 1. openssl_pkcs7_decrypt() example
|
openssl_pkcs7_encrypt() takes the contents of the file named infile and encrypts them using an RC2 40-bit cipher so that they can only be read by the intended recipients specified by recipcerts, which is either a lone X.509 certificate, or an array of X.509 certificates. headers is an array of headers that will be prepended to the data after it has been encrypted. flags can be used to specify options that affect the encoding process - see PKCS7 constants. headers can be either an associative array keyed by header name, or an indexed array, where each element contains a single header line. Cipher can be selected with cipherid since PHP 5.
Esempio 1. openssl_pkcs7_encrypt() example
|
openssl_pkcs7_sign() takes the contents of the file named infilename and signs them using the certificate and its matching private key specified by signcert and privkey parameters.
headers is an array of headers that will be prepended to the data after it has been signed (see openssl_pkcs7_encrypt() for more information about the format of this parameter.
flags can be used to alter the output - see PKCS7 constants - if not specified, it defaults to PKCS7_DETACHED.
extracerts specifies the name of a file containing a bunch of extra certificates to include in the signature which can for example be used to help the recipient to verify the certificate that you used.
Esempio 1. openssl_pkcs7_sign() example
|
openssl_pkcs7_verify() reads the S/MIME message contained in the filename specified by filename and examines the digital signature. It returns TRUE if the signature is verified, FALSE if it is not correct (the message has been tampered with, or the signing certificate is invalid), or -1 on error.
flags can be used to affect how the signature is verified - see PKCS7 constants for more information.
If the outfilename is specified, it should be a string holding the name of a file into which the certificates of the persons that signed the messages will be stored in PEM format.
If the cainfo is specified, it should hold information about the trusted CA certificates to use in the verification process - see certificate verification for more information about this parameter.
If the extracerts is specified, it is the filename of a file containing a bunch of certificates to use as untrusted CAs.
(PHP 4 >= 4.2.0, PHP 5)
openssl_pkey_export_to_file -- Gets an exportable representation of a key into a fileopenssl_pkey_export_to_file() saves an ascii-armoured (PEM encoded) rendition of key into the file named by outfilename. The key can be optionally protected by a passphrase. configargs can be used to fine-tune the export process by specifying and/or overriding options for the openssl configuration file. See openssl_csr_new() for more information about configargs. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.
(PHP 4 >= 4.2.0, PHP 5)
openssl_pkey_export -- Gets an exportable representation of a key into a stringopenssl_pkey_export() exports key as a PEM encoded string and stores it into out (which is passed by reference). The key is optionally protected by passphrase. configargs can be used to fine-tune the export process by specifying and/or overriding options for the openssl configuration file. See openssl_csr_new() for more information about configargs. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.
This function frees a private key created by openssl_pkey_new().
Returns a positive key resource identifier on success, or FALSE on error.
openssl_get_privatekey() parses key and prepares it for use by other functions. key can be one of the following:
a string having the format file://path/to/file.pem. The named file must contain a PEM encoded certificate/private key (it may contain both).
A PEM formatted private key.
The optional parameter passphrase must be used if the specified key is encrypted (protected by a passphrase).
(PHP 4 >= 4.2.0, PHP 5)
openssl_pkey_get_public -- Extract public key from certificate and prepare it for useReturns a positive key resource identifier on success, or FALSE on error.
openssl_get_publickey() extracts the public key from certificate and prepares it for use by other functions. certificate can be one of the following:
an X.509 certificate resource
a string having the format file://path/to/file.pem. The named file must contain a PEM encoded certificate/private key (it may contain both).
A PEM formatted private key.
openssl_pkey_new() generates a new private and public key pair. The public component of the key can be obtained using openssl_pkey_get_public(). You can finetune the key generation (such as specifying the number of bits) using configargs. See openssl_csr_new() for more information about configargs.
Nota: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.
openssl_private_decrypt() decrypts data that was previous encrypted via openssl_public_encrypt() and stores the result into decrypted. key must be the private key corresponding that was used to encrypt the data. padding defaults to OPENSSL_PKCS1_PADDING, but can also be one of OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, OPENSSL_NO_PADDING.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
You can use this function e.g. to decrypt data which were supposed only to you.
See also openssl_public_encrypt() and openssl_public_decrypt().
openssl_private_encrypt() encrypts data with private key and stores the result into crypted. Encrypted data can be decrypted via openssl_public_decrypt(). padding defaults to OPENSSL_PKCS1_PADDING, but can also be OPENSSL_NO_PADDING.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
This function can be used e.g. to sign data (or its hash) to prove that it is not written by someone else.
See also openssl_public_decrypt() and openssl_public_encrypt().
openssl_public_decrypt() decrypts data that was previous encrypted via openssl_private_encrypt() and stores the result into decrypted. key must be the public key corresponding that was used to encrypt the data. padding defaults to OPENSSL_PKCS1_PADDING, but can also be OPENSSL_NO_PADDING.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
You can use this function e.g. to check if the message was written by the owner of the private key.
See also openssl_private_encrypt() and openssl_private_decrypt().
openssl_public_encrypt() encrypts data with public key and stores the result into crypted. Encrypted data can be decrypted via openssl_private_decrypt(). padding defaults to OPENSSL_PKCS1_PADDING, but can also be one of OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, OPENSSL_NO_PADDING.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
This function can be used e.g. to encrypt message which can be then read only by owner of the private key. It can be also used to store secure data in database.
See also openssl_private_decrypt() and openssl_private_encrypt().
Returns the length of the sealed data on success, or FALSE on error. If successful the sealed data is returned in sealed_data, and the envelope keys in env_keys.
openssl_seal() seals (encrypts) data by using RC4 with a randomly generated secret key. The key is encrypted with each of the public keys associated with the identifiers in pub_key_ids and each encrypted key is returned in env_keys. This means that one can send sealed data to multiple recipients (provided one has obtained their public keys). Each recipient must receive both the sealed data and the envelope key that was encrypted with the recipient's public key.
Esempio 1. openssl_seal() example
|
See also openssl_open().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. If successful the signature is returned in signature.
openssl_sign() computes a signature for the specified data by using SHA1 for hashing followed by encryption using the private key associated with priv_key_id. Note that the data itself is not encrypted.
Esempio 1. openssl_sign() example
|
See also openssl_verify().
Returns 1 if the signature is correct, 0 if it is incorrect, and -1 on error.
openssl_verify() verifies that the signature is correct for the specified data using the public key associated with pub_key_id. This must be the public key corresponding to the private key used for signing.
Esempio 1. openssl_verify() example
|
See also openssl_sign().
(PHP 4 >= 4.2.0, PHP 5)
openssl_x509_check_private_key -- Checks if a private key corresponds to a certificateopenssl_x509_check_private_key() returns TRUE if key is the private key that corresponds to cert, or FALSE otherwise.
(PHP 4 >= 4.0.6, PHP 5)
openssl_x509_checkpurpose -- Verifies if a certificate can be used for a particular purposeReturns TRUE if the certificate can be used for the intended purpose, FALSE if it cannot, or -1 on error.
openssl_x509_checkpurpose() examines the certificate specified by x509cert to see if it can be used for the purpose specified by purpose.
cainfo should be an array of trusted CA files/dirs as described in Certificate Verification. It defaults to an empty array.
untrustedfile, if specified, is the name of a PEM encoded file holding certificates that can be used to help verify the certificate, although no trust in placed in the certificates that come from that file.
Tabella 1. openssl_x509_checkpurpose() purposes
Constant | Description |
---|---|
X509_PURPOSE_SSL_CLIENT | Can the certificate be used for the client side of an SSL connection? |
X509_PURPOSE_SSL_SERVER | Can the certificate be used for the server side of an SSL connection? |
X509_PURPOSE_NS_SSL_SERVER | Can the cert be used for Netscape SSL server? |
X509_PURPOSE_SMIME_SIGN | Can the cert be used to sign S/MIME email? |
X509_PURPOSE_SMIME_ENCRYPT | Can the cert be used to encrypt S/MIME email? |
X509_PURPOSE_CRL_SIGN | Can the cert be used to sign a certificate revocation list (CRL)? |
X509_PURPOSE_ANY | Can the cert be used for Any/All purposes? |
openssl_x509_export_to_file() stores x509 into a file named by outfilename in a PEM encoded format.
The optional parameter notext affects the verbosity of the output; if it is FALSE then additional human-readable information is included in the output. The default value of notext is TRUE.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
openssl_x509_export() stores x509 into a string named by output in a PEM encoded format.
The optional parameter notext affects the verbosity of the output; if it is FALSE then additional human-readable information is included in the output. The default value of notext is TRUE.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
openssl_x509_free() frees the certificate associated with the specified x509cert resource from memory.
(PHP 4 >= 4.0.6, PHP 5)
openssl_x509_parse -- Parse an X509 certificate and return the information as an arrayopenssl_x509_parse() returns information about the supplied x509cert, including fields such as subject name, issuer name, purposes, valid from and valid to dates etc. shortnames controls how the data is indexed in the array - if shortnames is TRUE (the default) then fields will be indexed with the short name form, otherwise, the long name form will be used - e.g.: CN is the shortname form of commonName.
The structure of the returned data is (deliberately) not yet documented, as it is still subject to change.
Questa estensione permette l'accesso ai server database Oracle. Vedere anche l'estensione OCI8.
You have to compile PHP with the option --with-oracle[=DIR], where DIR defaults to your environment variable ORACLE_HOME.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)
Ora_Bind -- effettua il binding di una variabile PHP ad un parametro di OracleRestituisce TRUE se il binding riesce, altrimenti FALSE. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Questa funzione collega la variabile PHP indicata con un parametro SQL. Il parametro SQL deve essere nella forma ":name". Con il parametro facoltativo type, si può determinare se il parametro SQL è di in/out (0, default), in (1) oppure out (2). Dalla versione 3.0.1 di PHP, su possono utilizzare le costanti ORA_BIND_INOUT, ORA_BIND_IN e ORA_BIND_OUT al posto dei numeri.
ora_bind deve essere invocata dopo ora_parse() e prima di ora_exec(). I valori di input possono essere dati mediante assegnamento alle variabili PHP collegate; dopo aver chiamato ora_exec() le variabili PHP collegate contengono i valori di output, se disponibili.
<?php ora_parse($curs, "declare tmp INTEGER; begin tmp := :in; :out := tmp; :x := 7.77; end;"); ora_bind($curs, "result", ":x", $len, 2); ora_bind($curs, "input", ":in", 5, 1); ora_bind($curs, "output", ":out", 5, 2); $input = 765; ora_exec($curs); echo "Result: $result<BR>Out: $output<BR>In: $input"; ?> |
Restituisce TRUE se la chiusura è effettuata, altrimenti FALSE. I dettagli dell'errore si ottengono con le funzioni ora_error() e ora_errorcode().
Questa funzione chiude un corsore dati aperto con ora_open().
Restituisce il nome del campo/colonna column nel cursore cursor. Il nome è restituito in lettere maiuscole. La colonna 0 è la prima.
(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)
ora_columnsize -- restituisce la dimensione di un campo risultato OracleRestituisce la dimensione del campo/colonna column nel cursore cursor. La colonna 0 è la prima.
Restituisce il tipo Oracle del campo/colonna column nel cursore cursor. La colonna 0 è la pirma. Il tipo restituito sarà uno dei seguenti:
"VARCHAR2" |
"VARCHAR" |
"CHAR" |
"NUMBER" |
"LONG" |
"LONG RAW" |
"ROWID" |
"DATE" |
"CURSOR" |
Questa funzione esegue una transazione Oracle. Una transazione è definita come tutti i cambiamenti su una data connessione dall'ultimo commit/rollback, con autocommit spento, o dall'inizio della connessione.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioniora_error() e ora_errorcode().
Questa funzione disabilita il commit automatico dopo ogni ora_exec().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Questa funzione abilita il commit automatico dopo ogni ora_exec() sulla connessione specificata.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Questa funzione è la combinazione veloce di ora_parse(), ora_exec() e ora_fetch(). Analizza, ed esegue un comando SQL, quindi scarica la prima tupla del risultato.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Vedere anche ora_parse(),ora_exec(), e ora_fetch().
Restituisce un messaggio d'errore nella forma XXX-NNNNN dove XXX è la sorgente dell'errore e NNNNN identifica il messaggio d'errore.
Nota: Il supporto per gli id di connessione è stato aggiunto nella versione 3.0.4.
Nelle versioni UNIX di Oracle, è possibile ottenere i dettagli dell'errore in questo modo: $ oerr ora 00001 00001, 00000, "unique constraint (%s.%s) violated" // *Cause: An update or insert statement attempted to insert a duplicate key // For Trusted ORACLE configured in DBMS MAC mode, you may see // this message if a duplicate entry exists at a different level. // *Action: Either remove the unique restriction or do not insert the key
Restituisce il codice numerico di errore dell'ultimo comando eseguito sul cursore o sulla connessione specificata.
Nota: Il supporto per gli id di connessione è stato aggiunto nella versione 3.0.4.
ora_exec() esegue il comando cursor, già analizzato da ora_parse().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Vedere anche ora_parse(), ora_fetch() e ora_do().
Recupera una tupla e la mette in un array. Il parametro flags ha due valori: se il flag ORA_FETCHINTO_NULLS è impostato, i campi con valori NULL vengono inseriti nell'array; se il flag ORA_FETCHINTO_ASSOC è impostato, viene creato un array associativo.
Restituisce il numero di campi acquisiti.
Vedere anche ora_parse(),ora_exec(), ora_fetch() e ora_do().
Acquisisce una tupla di dati dal cursore specificato.
Restituisce TRUE (la tupla è stata acquisita) o FALSE (non ci sono più tuple, o è avvenuto un errore). Se è avvenuto un errore, i dettagli si ottengono usando le funzioni ora_error() e ora_errorcode(). Se non sono avvenuti errori, ora_errorcode() restituirà 0.
Vedere anche ora_parse(),ora_exec(), e ora_do().
Restituisce i dati del campo o del risultato di una funzione.
Restituisce il contenuto del campo/colonna. Se avviene un errore, viene restituito il valore FALSE e ora_errorcode() restituirà un valore diverso da zero. Si noti, comunque, che un test al valore FALSE sul risultato di questa funzione può dare esito positivo anche in caso non ci siano errori (campo NULL, stringa vuota, il numero 0, la stringa "0").
Depenna l'utente e disconnette dal server.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Vedere anche ora_logon().
Stabilisce una connessione tra PHP e un database Oracle utilizzando la username user e password password specificate.
Le connessioni possono essere create usando SQL*Net fornendo il nomeTNS a user in questo modo:
Se i dati contengono caratteri non-ASCII, si deve controllare di avere impostato NLS_LANG nel proprio environment. Per quanto riguarda i moduli del server, occorre impostarlo nell' environment del server prima di avviarlo.
Restituisce un indice di connessione se l'operazione ha successo, oppure FALSE in caso di errore. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode() functions.
ora_numcols() restituisce il numero di campi di un risultato. Dopo una sequenza parse/exec/fetch restituisce solo risultati che abbiano coerenza.
Vedere anche ora_parse(),ora_exec(), ora_fetch() e ora_do().
ora_numrows() restituisce il numero di tuple in un risultato.
Apre un cursore Oracle associato alla connessione.
Restituisce un indice di cursore oppure FALSE in caso di errore. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Questa funziona analizza un comando SQL o un blocco PL/SQL e lo associa al cursore specificato.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche ora_exec(), ora_fetch() e ora_do().
Stabilisce una connessione permanente tra PHP ed un database Oracle con le username and password specificate.
Vedere anche ora_logon().
Questa funzione annulla una transazione Oracle. (Vedere ora_commit() per la definizione di una transazione.)
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode() functions.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
The PDO_OCI Data Source Name (DSN) is composed of the following elements:
The DSN prefix is oci:. If you are connecting to a database defined in tnsnames.ora, append the name of the database to the DSN prefix and your DSN is complete.
The URI for the Oracle Instant Client connection takes the form of dbname=//hostname:port-number/database.
The Output Control functions allow you to control when output is sent from the script. This can be useful in several different situations, especially if you need to send headers to the browser after your script has began outputting data. The Output Control functions do not affect headers sent using header() or setcookie(), only functions such as echo() and data between blocks of PHP code.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Output Control configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
output_buffering | "0" | PHP_INI_PERDIR | |
output_handler | NULL | PHP_INI_PERDIR | Available since PHP 4.0.4. |
implicit_flush | "0" | PHP_INI_ALL | PHP_INI_PERDIR in PHP <= 4.2.3. |
Breve descrizione dei parametri di configurazione.
You can enable output buffering for all files by setting this directive to 'On'. If you wish to limit the size of the buffer to a certain size - you can use a maximum number of bytes instead of 'On', as a value for this directive (e.g., output_buffering=4096). As of PHP 4.3.5, this directive is always Off in PHP-CLI.
You can redirect all of the output of your scripts to a function. For example, if you set output_handler to mb_output_handler(), character encoding will be transparently converted to the specified encoding. Setting any output handler automatically turns on output buffering.
Nota: You cannot use both mb_output_handler() with ob_iconv_handler() and you cannot use both ob_gzhandler() and zlib.output_compression.
Nota: Only built-in functions can be used with this directive. For user defined functions, use ob_start().
FALSE by default. Changing this to TRUE tells PHP to tell the output layer to flush itself automatically after every output block. This is equivalent to calling the PHP function flush() after each and every call to print() or echo() and each and every HTML block.
When using PHP within an web environment, turning this option on has serious performance implications and is generally recommended for debugging purposes only. This value defaults to TRUE when operating under the CLI SAPI.
See also ob_implicit_flush().
In the above example, the output from echo() would be stored in the output buffer until ob_end_flush() was called. In the mean time, the call to setcookie() successfully stored a cookie without causing an error. (You can not normally send headers to the browser after data has already been sent.)
Nota: When upgrading from PHP 4.1 (and 4.2) to 4.3 that due to a bug in earlier versions you must ensure that implict_flush is OFF in your php.ini, otherwise any output with ob_start() will not be hidden from output.
Flushes the output buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This effectively tries to push all the output so far to the user's browser.
flush() has no effect on the buffering scheme of your webserver or the browser on the client side. Thus you need to call both ob_flush() and flush() to flush the output buffers.
Several servers, especially on Win32, will still buffer the output from your script until it terminates before transmitting the results to the browser.
Server modules for Apache like mod_gzip may do buffering of their own that will cause flush() to not result in data being sent immediately to the client.
Even the browser may buffer its input before displaying it. Netscape, for example, buffers text until it receives an end-of-line or the beginning of a tag, and it won't render tables until the </table> tag of the outermost table is seen.
Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page.
This function discards the contents of the output buffer.
This function does not destroy the output buffer like ob_end_clean() does.
See also ob_flush(), ob_end_flush() and ob_end_clean().
This function discards the contents of the topmost output buffer and turns off this output buffering. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_clean() as the buffer contents are discarded when ob_end_flush() is called. The function returns TRUE when it successfully discarded one buffer and FALSE otherwise. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).
The following example shows an easy way to get rid of all output buffers:
Nota: If the function fails it generates an E_NOTICE.
The boolean return value was added in PHP 4.2.0.
See also ob_start(), ob_get_contents(), and ob_flush().
This function will send the contents of the topmost output buffer (if any) and turn this output buffer off. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_flush() as the buffer contents are discarded after ob_end_flush() is called. The function returns TRUE when it successfully discarded one buffer and FALSE otherwise. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).
Nota: This function is similar to ob_get_flush(), except that ob_get_flush() returns the buffer as a string.
The following example shows an easy way to flush and end all output buffers:
Nota: If the function fails it generates an E_NOTICE.
The boolean return value was added in PHP 4.2.0.
See also ob_start(), ob_get_contents(), ob_get_flush(), ob_flush() and ob_end_clean().
This function will send the contents of the output buffer (if any). If you want to further process the buffer's contents you have to call ob_get_contents() before ob_flush() as the buffer contents are discarded after ob_flush() is called.
This function does not destroy the output buffer like ob_end_flush() does.
See also ob_get_contents(), ob_clean(), ob_end_flush() and ob_end_clean().
This will return the contents of the output buffer and end output buffering. If output buffering isn't active then FALSE is returned. ob_get_clean() essentially executes both ob_get_contents() and ob_end_clean().
See also ob_start() and ob_get_contents().
This will return the contents of the output buffer or FALSE, if output buffering isn't active.
See also ob_start() and ob_get_length().
(PHP 4 >= 4.3.0, PHP 5)
ob_get_flush -- Flush the output buffer, return it as a string and turn off output bufferingob_get_flush() flushs the output buffer, return it as a string and turns off output buffering. ob_get_flush() returns FALSE if no buffering is active.
Nota: This function is similar to ob_end_flush(), except that this function returns the buffer as a string.
Esempio 1. ob_get_flush() example
Il precedente esempio visualizzerà:
|
See also ob_end_clean(), ob_end_flush() and ob_list_handlers().
This will return the length of the contents in the output buffer or FALSE, if output buffering isn't active.
See also ob_start() and ob_get_contents().
This will return the level of nested output buffering handlers or zero if output buffering is not activated.
See also ob_start() and ob_get_contents().
This will return the current status of output buffers. It returns array contains buffer status or FALSE for error.
See also ob_get_level().
Nota: ob_gzhandler() requires the zlib extension.
ob_gzhandler() is intended to be used as a callback function for ob_start() to help facilitate sending gz-encoded data to web browsers that support compressed web pages. Before ob_gzhandler() actually sends compressed data, it determines what type of content encoding the browser will accept ("gzip", "deflate" or none at all) and will return its output accordingly. All browsers are supported since it's up to the browser to send the correct header saying that it accepts compressed web pages.
Nota: mode was added in PHP 4.0.5.
Nota: You cannot use both ob_gzhandler() and zlib.output_compression. Also note that using zlib.output_compression is preferred over ob_gzhandler().
See also ob_start() and ob_end_flush().
ob_implicit_flush() will turn implicit flushing on or off (if no flag is given, it defaults to on). Implicit flushing will result in a flush operation after every output call, so that explicit calls to flush() will no longer be needed.
Turning implicit flushing on will disable output buffering, the output buffers current output will be sent as if ob_end_flush() had been called.
See also flush(), ob_start(), and ob_end_flush().
This will return an array with the output handlers in use (if any). If output_buffering is enabled or an anonymous function was used with ob_start(), ob_list_handlers() will return "default output handler".
Esempio 1. ob_list_handlers() example
Il precedente esempio visualizzerà:
|
See also ob_end_clean(), ob_end_flush(), ob_get_flush(), ob_start().
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.
The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.
An optional output_callback function may be specified. This function takes a string as a parameter and should return a string. The function will be called when ob_end_flush() is called, or when the output buffer is flushed to the browser at the end of the request. When output_callback is called, it will receive the contents of the output buffer as its parameter and is expected to return a new output buffer as a result, which will be sent to the browser. If the output_callback is not a callable function, this function will return FALSE. If the callback function has two parameters, the second parameter is filled with a bit-field consisting of PHP_OUTPUT_HANDLER_START, PHP_OUTPUT_HANDLER_CONT and PHP_OUTPUT_HANDLER_END.
Nota: In PHP 4.0.4, ob_gzhandler() was introduced to facilitate sending gz-encoded data to web browsers that support compressed web pages. ob_gzhandler() determines what type of content encoding the browser will accept and will return its output accordingly.
Nota: Before PHP 4.3.2 this function did not return FALSE in case the passed output_callback can not be executed.
Avvertimento |
Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change it back by e.g. chdir(dirname($_SERVER['SCRIPT_FILENAME'])) in the callback function. |
If the optional parameter chunk_size is passed, the callback function is called on every first newline after chunk_size bytes of output. The output_callback parameter may be bypassed by passing a NULL value.
If the optional parameter erase is set to FALSE, the buffer will not be deleted until the script finishes (as of PHP 4.3.0).
Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.
ob_end_clean(), ob_end_flush(), ob_clean(), ob_flush() and ob_start() may not be called from a callback function. If you call them from callback function, the behavior is undefined. If you would like to delete the contents of a buffer, return "" (a null string) from callback function. You can't even call functions using the output buffering functions like print_r($expression, true) or highlight_file($filename, true) from a callback function.
Esempio 1. User defined callback function example
Would produce:
|
See also ob_get_contents(), ob_end_flush(), ob_end_clean(), ob_implicit_flush(), ob_gzhandler(), ob_iconv_handler() mb_output_handler(), and ob_tidyhandler().
This function rewrite the URLs and forms with the given variable.
Nota: This function buffers the output.
Esempio 1. output_add_rewrite_var() example
Il precedente esempio visualizzerà:
|
See also output_reset_rewrite_vars(), ob_flush() and ob_list_handlers().
This function resets the URL rewriter and undo the changes made by output_add_rewrite_var() and/or by session_start() that are still in the buffer.
Esempio 1. output_reset_rewrite_vars() example
Il precedente esempio visualizzerà:
|
See also output_add_rewrite_var(), ob_flush(), ob_list_handlers() and session_start().
Ovrimos SQL Server, is a client/server, transactional RDBMS combined with Web capabilities and fast transactions.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.1.0.
Nota: Questo modulo non è disponibile su piattaforme Windows.
You'll need to install the sqlcli library available in the Ovrimos SQL Server distribution.
To enable Ovrimos support in PHP just compile PHP with the --with-ovrimos[=DIR] parameter to your configure line. DIR is the Ovrimos' libsqlcli install directory.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Esempio 1. Connect to Ovrimos SQL Server and select from a system table
|
ovrimos_close() is used to close the specified connection to Ovrimos. This has the effect of rolling back uncommitted transactions.
ovrimos_commit() is used to commit the transaction. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
ovrimos_connect() is used to connect to the specified database.
ovrimos_connect() returns a connection id (greater than 0) or 0 for failure. The meaning of host and db are those used everywhere in Ovrimos APIs. host is a host name or IP address and db is either a database name, or a string containing the port number.
Esempio 1. ovrimos_connect() Example
|
ovrimos_cursor() returns the name of the cursor. Useful when wishing to perform positioned updates or deletes.
ovrimos_exec() executes an SQL statement (query or update) and returns a result_id or FALSE. Evidently, the SQL statement should not contain parameters.
ovrimos_execute() executes a prepared statement. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. If the prepared statement contained parameters (question marks in the statement), the correct number of parameters should be passed in an array. Notice that I don't follow the PHP convention of placing just the name of the optional parameter inside square brackets. I couldn't bring myself on liking it.
ovrimos_fetch_into() fetches a row from the result set into result_array, which should be passed by reference. Which row is fetched is determined by the two last parameters. how is one of Next (default), Prev, First, Last, Absolute, corresponding to forward direction from current position, backward direction from current position, forward direction from the start, backward direction from the end and absolute position from the start (essentially equivalent to 'first' but needs 'rownumber'). Case is not significant. rownumber is optional except for absolute positioning. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. A fetch into example
|
ovrimos_fetch_row() fetches a row from the result set. Column values should be retrieved with other calls. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. A fetch row example
|
ovrimos_field_len() is used to get the length of the output column with number field_number (1-based), in result result_id.
ovrimos_field_name() returns the output column name at the (1-based) index specified.
ovrimos_field_num() returns the (1-based) index of the output column specified by field_name, or FALSE.
ovrimos_field_type() returns the (numeric) type of the output column at the (1-based) index specified by field_number.
ovrimos_free_result() frees the specified result_id. Returns TRUE.
(PHP 4 >= 4.0.3, PHP 5)
ovrimos_longreadlen -- Specifies how many bytes are to be retrieved from long datatypesovrimos_longreadlen() specifies how many bytes are to be retrieved from long datatypes (long varchar and long varbinary). Default is zero. It currently sets this parameter the specified result set. Returns TRUE.
ovrimos_num_fields() returns the number of columns in a result_id resulting from a query.
ovrimos_num_rows() returns the number of rows affected by update operations.
ovrimos_prepare() prepares an SQL statement and returns a result_id (or FALSE on failure).
Esempio 1. Connect to Ovrimos SQL Server and prepare a statement
|
ovrimos_result_all() prints the whole result set as an HTML table. Returns the number of rows in the generated table.
Esempio 1. Prepare a statement, execute, and view the result
|
Esempio 2. ovrimos_result_all() with meta-information
|
Esempio 3. ovrimos_result_all() example
|
ovrimos_result() retrieves the output column specified by field, either as a string or as an 1-based index. Returns FALSE on failure.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
This module allows to read Paradox database and primary index files. It has initial support for creating Paradox databases. Consider it to be experimental due to lack of documentation of the Paradox file format.
Nota: This module has not been tested on other platforms than Debian/GNU Linux for PPC.
Nota: This module is also in development and may change, though I don't expect major changes to the API.
You need at least PHP 5.0.0 and libpx >= 0.1.9. The paradox library (libpx) is available at http://pxlib.sourceforge.net.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
The paradox extension provides also an object oriented API. It consists of only one class called paradox_doc. Its methods only differ from the functions in its name and of course the missing first parameter. The following table will list all methods and its equivalent functions.
Tabella 1. Methods of class paradox_doc
Name of method | Equivalent function |
---|---|
Constructor | px_new() |
Destructor | px_delete() |
open_fp() | px_open_fp() |
create_fp() | px_create_fp() |
close() | px_close() |
numrecords() | px_numrecords() |
numfields() | px_numfields() |
get_record() | px_get_record() |
put_record() | px_put_record() |
get_field() | px_get_field() |
get_schema() | px_get_schema() |
get_info() | px_get_info() |
set_parameter() | px_set_parameter() |
get_parameter() | px_get_parameter() |
set_value() | px_set_value() |
get_value() | px_get_value() |
get_info() | px_get_info() |
set_targetencoding() | px_set_targetencoding() |
set_tablename() | px_set_tablename() |
set_blob_file() | px_set_blob_file() |
timestamp2string() | px_timestamp2string() |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
The following two tables lists all constants defined by the paradox extension.
Tabella 2. Contants for field types
Name | Meaning |
---|---|
PX_FIELD_ALPHA | Character data with fixed length |
PX_FIELD_DATE | Date |
PX_FIELD_SHORT | Short integer (2 Bytes) |
PX_FIELD_LONG | Long integer (4 Bytes) |
PX_FIELD_CURRENCY | same as PX_FIELD_NUMBER |
PX_FIELD_NUMBER | Double |
PX_FIELD_LOGICAL | Boolean |
PX_FIELD_MEMOBLOB | Binary large object (not supported) |
PX_FIELD_BLOB | Binary large object (not supported) |
PX_FIELD_FMTMEMOBLOB | Binary large object (not supported) |
PX_FIELD_OLE | OLE object (basically a blob, not supported) |
PX_FIELD_GRAPHIC | Graphic (basically a blob, not supported) |
PX_FIELD_TIME | time |
PX_FIELD_TIMESTAMP | timestamp (like the unix timestamp) |
PX_FIELD_AUTOINC | Auto incrementing interger (like PX_FIELD_LONG) |
PX_FIELD_BCD | Decimal number stored in bcd format (not supported) |
PX_FIELD_BYTES | Array of Bytes with not more than 255 bytes (not supported) |
PX_KEYTOLOWER | |
PX_KEYTOUPPER |
Tabella 3. Contants for file types
Name | Meaning |
---|---|
PX_FILE_INDEX_DB | Indexed database |
PX_FILE_PRIM_INDEX | Primary index |
PX_FILE_NON_INDEX_DB | None indexed database |
PX_FILE_NON_INC_SEC_INDEX | None incremental secondary index (not supported) |
PX_FILE_SEC_INDEX | Secondary index (not supported) |
PX_FILE_INC_SEC_INDEX | Incremental secondary index (not supported) |
PX_FILE_NON_INC_SEC_INDEX_G | (not supported) |
PX_FILE_SEC_INDEX_G | (not supported) |
PX_FILE_INC_SEC_INDEX_G | (not supported) |
Closes the paradox database. This function will not close the file. You will have to call fclose() afterwards.
Create a new paradox database file. The actual file has to be opened before with fopen(). Make sure the file is writable. The first parameter is the return value of px_new(). fielddesc is an array containing one element for each field containing its specification. Each field specification is an array itself with either two or three elements.The first element is always a string value used as the name of the field. It may not be larger than ten characters. The second element contains the field type which is one of the constants listed in the table Constants for field types. In the case of a character field, you will have to provide a third element specifying the length of the field.
Nota: This function is highly experimental, due to insufficient documentation of the paradox file format. Database files created with this function can be opened by px_open_fp() and has been successfully opened by the Paradox software, but your milage may vary.
Esempio 1. Creating a Paradox database with two fields
|
Deletes the resource of the paradox file and frees all memory.
Returns the specification of the fieldno'th database field as an associated array. The array contains three fields named name, type, and size.
Returns an associated array with lots of information about a paradox file. This array is likely to extend in the future.
Version of file multiplied by 10.
Name of table as stored in the file.
Number of records in this table.
Number of fields in this table.
Number of bytes used for the header. This is usually 0x800.
This value multiplied by 0x400 is the size of a data block in bytes.
The number of data blocks in the file. Each data block contains a certain number of records which depends on the record size and the data block size (maxtablesize). Data blocks may not necessarily be completely filled.
Number of fields used for the primary index. The fields do always start as field number 1.
The DOS codepage which was used for encoding fields with character data. If the target encoding is not set with px_set_targetencoding() this will be the encoding for character fields when records are being accessed with px_get_record().
The name can be one of the following:
The name of the table as it will be stored in the database header.
The encoding for the output. Data which is being read from character fields is being recode into the targetencoding.
The encoding of the input data which is to be stored into the database.
The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.
The optional mode can be PX_KEYTOLOWER or PX_KEYTOUPPER in order to convert the keys into lower or upper case. If mode is not passed or is 0, then the key will be exactly like the field name. The element values will contain the field values. NULL values will be retained and are different from 0.0, 0 or the empty string. Fields of type PX_FIELD_TIME will be returned as an integer counting the number of milliseconds starting at midnight. A timestamp is a floating point value also counting milliseconds starting at the beginning of julian calendar.
Returns the num'th record from the paradox database. The record is returned as an associated array with its keys being the field names.
px_get_schema() returns the database schema.
If the optional mode is PX_KEYTOLOWER or PX_KEYTOUPPER the key will be converted to lower or upper case. If mode is 0 or not passed at all, then the key name will be identical to the field name.
Returns the schema of a database file as an associated array. The key name is equal to the field name. Each array element is itself an associated array containing the two fields type and size. type is one of the constants in table Constants for field types.
name can be one of the following.
The number of primary keys. Paradox databases always use the first numprimkeys fields for the primary index.
Create a new paradox object. You will have to call this function before any further functions. px_new() does not create any file on the disk, it justs creates an instance of a paradox object.
Returns the number of fields in a database file. The return value of this function is identical to the element numfields in the associated array returned by px_get_info().
Returns the number of records in a database file. The return value of this function is identical to the element numrecords in the associated array returned by px_get_info().
Open an existing paradox database file. The actual file has to be opened before with fopen(). This function can also be used to open primary index files and tread them like a paradox database. This is supported for those who would like to investigate a primary index. It cannot be used to accelerate access to a database file.
Stores a record into a paradox database. The record is added at the end of the database.
Sets the name of the file where blobs are going to be read from. Without calling this function, px_get_record() will only return data in blob fields if the data is part of the record and not stored in the blob file. Blob data is stored in the record if it is small enough to fit in the size of the blob field.
Calling this function twice will close the first blob file and open the new one.
Sets various parameters.
name can be one of the following.
The name of the table as it will be stored in the database header.
The encoding for the output. Data which is being read from character fields is being recode into the targetencoding.
The encoding of the input data which is to be stored into the database.
Sets the table name of a paradox database, which was created with px_create_fp(). Applying this function on an existing database has no effect.
Set the encoding for data retrieved from a character field. All character fields will be recoded to the encoding set by this function. If the encoding is not set, the character data will be returned in the DOS code page encoding as specified in the database.
See also px_get_info() to determine the DOS code page.
Returns FALSE if the encoding could not be set, e.g. the encoding is unknown, or pxlib does not support recoding at all. In the second case a warning will be issued.
name can be one of the following.
The number of primary keys. Paradox databases always use the first numprimkeys fields for the primary index.
These functions allow runtime analysis of opcodes compiled from PHP scripts.
This PECL extension is not bundled with PHP.
Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/parsekit.
You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Return full detail, but without unnecessary NULL extries.
Return shorthand opcode notation.
Opnode Flag
Opnode Flag
Opnode Flag
Opnode Flag
Opnode Flag
Opnode Flag
Opnode Flag
Opnode Flag
Class Type
Class Type
Function Type
Function Type
Function Type
Function Type
Function Type
Node Type
Node Type
Node Type
Node Type
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
A string containing the name of the file to compile. Similar to the argument to include().
A 2D hash of errors (including fatal errors) encountered during compilation. Returned by reference.
One of either PARSEKIT_QUIET or PARSEKIT_SIMPLE. To produce varying degrees of verbosity in the returned output.
Esempio 1. parsekit_compile_file() example
Il precedente esempio visualizzerà:
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
A string containing phpcode. Similar to the argument to eval().
A 2D hash of errors (including fatal errors) encountered during compilation. Returned by reference.
One of either PARSEKIT_QUIET or PARSEKIT_SIMPLE. To produce varying degrees of verbosity in the returned output.
Esempio 1. parsekit_compile_string() example
Il precedente esempio visualizzerà:
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
A string describing a function, or an array describing a class/method.
Esempio 1. parsekit_func_arginfo() example
Il precedente esempio visualizzerà:
|
Process Control support in PHP implements the Unix style of process creation, program execution, signal handling and process termination. Process Control should not be enabled within a webserver environment and unexpected results may happen if any Process Control functions are used within a webserver environment.
This documentation is intended to explain the general usage of each of the Process Control functions. For detailed information about Unix process control you are encouraged to consult your systems documentation including fork(2), waitpid(2) and signal(2) or a comprehensive reference such as Advanced Programming in the UNIX Environment by W. Richard Stevens (Addison-Wesley).
PCNTL now uses ticks as the signal handle callback mechanism, which is much faster than the previous mechanism. This change follows the same semantics as using "user ticks". You use the declare() statement to specify the locations in your program where callbacks are allowed to occur. This allows you to minimize the overhead of handling asynchronous events. In the past, compiling PHP with pcntl enabled would always incur this overhead, whether or not your script actually used pcntl.
There is one adjustment that all pcntl scripts prior to PHP 4.3.0 must make for them to work which is to either to use declare() on a section where you wish to allow callbacks or to just enable it across the entire script using the new global syntax of declare().
Nota: Questo modulo non è disponibile su piattaforme Windows.
Process Control support in PHP is not enabled by default. You have to compile the CGI or CLI version of PHP with --enable-pcntl configuration option when compiling PHP to enable Process Control support.
Nota: Currently, this module will not function on non-Unix platforms (Windows).
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
The following list of signals are supported by the Process Control functions. Please see your systems signal(7) man page for details of the default behavior of these signals.
This example forks off a daemon process with a signal handler.
Esempio 1. Process Control Example
|
The pcntl_alarm() function creates a timer that will send a SIGALRM signal to the process after seconds seconds. If seconds is zero, no new alarm is created. Any call to pcntl_alarm() will cancel any previously set alarm.
pcntl_alarm() will return the time in seconds that any previously scheduled alarm had remaining before it was to be delivered, or 0 if there was no previously scheduled alarm.
pcntl_exec() executes the program path with arguments args. path must be the path to a binary executable or a script with a valid path pointing to an executable in the shebang ( #!/usr/local/bin/perl for example) as the first line. See your system's man execve(2) page for additional information.
args is an array of argument strings passed to the program.
envs is an array of strings which are passed as environment to the program. The array is in the format of name => value, the key being the name of the environmental variable and the value being the value of that variable.
pcntl_exec() returns FALSE on error and does not return on success.
The pcntl_fork() function creates a child process that differs from the parent process only in its PID and PPID. Please see your system's fork(2) man page for specific details as to how fork works on your system.
On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and a PHP error is raised.
See also pcntl_waitpid() and pcntl_signal().
pcntl_getpriority() gets the priority of pid. If pid is not specified, the pid of the current process is used. Because priority levels can differ between system types and kernel versions, please see your system's getpriority(2) man page for specific details.
pcntl_getpriority() returns the priority of the process or FALSE on error. A lower numerical value causes more favorable scheduling.
process_identifier is one of PRIO_PGRP, PRIO_USER or PRIO_PROCESS.
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
pcntl_setpriority() sets the priority of pid to priority. If pid is not specified, the pid of the current process is used.
priority is generally a value in the range -20 to 20. The default priority is 0 while a lower numerical value causes more favorable scheduling. Because priority levels can differ between system types and kernel versions, please see your system's setpriority(2) man page for specific details.
process_identifier is one of PRIO_PGRP, PRIO_USER or PRIO_PROCESS.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The pcntl_signal() function installs a new signal handler for the signal indicated by signo. The signal handler is set to handler which may be the name of a user created function, or either of the two global constants SIG_IGN or SIG_DFL. The optional restart_syscalls specifies whether system call restarting should be used when this signal arrives and defaults to TRUE.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: The optional restart_syscalls parameter became available in PHP 4.3.0.
Nota: The ability to use an object method as a callback became available in PHP 4.3.0. Note that when you set a handler to an object method, that object's reference count is increased which makes it persist until you either change the handler to something else, or your script ends.
Esempio 1. pcntl_signal() example
|
Nota: As of PHP 4.3.0 PCNTL uses ticks as the signal handle callback mechanism, which is much faster than the previous mechanism. This change follows the same semantics as using "user ticks". You must use the declare() statement to specify the locations in your program where callbacks are allowed to occur for the signal handler to function properly (as used in the above example).
See also pcntl_fork() and pcntl_waitpid().
The wait function suspends execution of the current process until a child has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function. If a child has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed. Please see your system's wait(2) man page for specific details as to how wait works on your system.
pcntl_wait() returns the process ID of the child which exited, -1 on error or zero if WNOHANG was provided as an option (on wait3-available systems) and no child was available.
If wait3 is available on your system (mostly BSD-style systems), you can provide the optional options parameter. If this parameter is not provided, wait will be used for the system call. If wait3 is not available, providing a value for options will have no effect. The value of options is the value of zero or more of the following two constants OR'ed together:
Tabella 1. Possible values for options if wait3 is available
WNOHANG | Return immediately if no child has exited. |
WUNTRACED | Return for children which are stopped, and whose status has not been reported. |
pcntl_wait() will store status information in the status parameter which can be evaluated using the following functions: pcntl_wifexited(), pcntl_wifstopped(), pcntl_wifsignaled(), pcntl_wexitstatus(), pcntl_wtermsig() and pcntl_wstopsig().
Nota: This function is equivalent to calling pcntl_waitpid() with a -1 pid and no options.
See also pcntl_fork(), pcntl_signal(), pcntl_wifexited(), pcntl_wifstopped(), pcntl_wifsignaled(), pcntl_wexitstatus(), pcntl_wtermsig(), pcntl_wstopsig() and pcntl_waitpid().
The pcntl_waitpid() function suspends execution of the current process until a child as specified by the pid argument has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function. If a child as requested by pid has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed. Please see your system's waitpid(2) man page for specific details as to how waitpid works on your system.
pcntl_waitpid() returns the process ID of the child which exited, -1 on error or zero if WNOHANG was used and no child was available
The value of pid can be one of the following:
Tabella 1. possible values for pid
< -1 | wait for any child process whose process group ID is equal to the absolute value of pid. |
-1 | wait for any child process; this is the same behaviour that the wait function exhibits. |
0 | wait for any child process whose process group ID is equal to that of the calling process. |
> 0 | wait for the child whose process ID is equal to the value of pid. |
Nota: Specifying -1 as the pid is equivalent to the functionality pcntl_wait() provides (minus options).
pcntl_waitpid() will store status information in the status parameter which can be evaluated using the following functions: pcntl_wifexited(), pcntl_wifstopped(), pcntl_wifsignaled(), pcntl_wexitstatus(), pcntl_wtermsig() and pcntl_wstopsig().
The value of options is the value of zero or more of the following two global constants OR'ed together:
Tabella 2. possible values for options
WNOHANG | return immediately if no child has exited. |
WUNTRACED | return for children which are stopped, and whose status has not been reported. |
See also pcntl_fork(), pcntl_signal(), pcntl_wifexited(), pcntl_wifstopped(), pcntl_wifsignaled(), pcntl_wexitstatus(), pcntl_wtermsig() and pcntl_wstopsig().
Returns the return code of a terminated child. This function is only useful if pcntl_wifexited() returned TRUE.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid() and pcntl_wifexited().
Returns TRUE if the child status code represents a successful exit.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid() and pcntl_wexitstatus().
(PHP 4 >= 4.1.0, PHP 5)
pcntl_wifsignaled -- Returns TRUE if status code represents a termination due to a signalReturns TRUE if the child process exited because of a signal which was not caught.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid() and pcntl_signal().
Returns TRUE if the child process which caused the return is currently stopped; this is only possible if the call to pcntl_waitpid() was done using the option WUNTRACED.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid().
Returns the number of the signal which caused the child to stop. This function is only useful if pcntl_wifstopped() returned TRUE.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid() and pcntl_wifstopped().
Returns the number of the signal that caused the child process to terminate. This function is only useful if pcntl_wifsignaled() returned TRUE.
The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().
See also pcntl_waitpid(), pcntl_signal() and pcntl_wifsignaled().
La sintassi utilizzata dalle espressioni regolari di queste funzioni ricorda da vicino Perl. Le espressioni regolari devono essere racchiuse tra delimitatori, ad esempio /. Ogni carattere che non sia alfanumerico od il backslash (\) può essere usato come delimitatore. Se il carattere usato come delimitatore deve essere utilizzato all'interno dell'espressione, questo deve essere preceduto dal carattere di escape (\). Infine, a partire dalla versione 4.0.4 di PHP, si possono anche usare i delimitatori stile Perl come (), {}, [], ed <>. Per maggiori dettagli vedere Sintassi dei criteri di riconoscimento.
Il delimitatore finale può essere seguito da vari modificatori che agiscono sul criterio di riconoscimento. Per maggiori informazioni si rimanda al capitolo Modificatori di criterio (Pattern Modifiers).
Utilizzando le funzioni POSIX-esteso il PHP è in grado di supportare le espressioni regolari scritte con la sintassi POSIX-esteso.
Avvertimento |
Occorre prestare attenzione ad alcune limitazioni di PCRE. Maggiori informazioni in merito possono essere reperite alla pagina http://www.pcre.org/pcre.txt for more info. |
Il supporto delle espressioni regolari è ottenuto mediante la libreria PCRE, che è un software open source, scritto da Philip Hazel, ed il cui copyright è detenuto dalla Università di Cambridge, Inghilterra. La libreria è disponibile all'indirizzo ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/.
A partire dalla versione 4.2.0 di PHP queste funzioni sono abilitate per default. Queste funzioni possono essere disattivate usando --without-pcre-regex. Utilizzare --with-pcre-regex=DIR per specificare la directory DIR in cui sono posizionati i file di include e le librerie di PCRE, nel caso non si desideri utilizzare le librerie incluse. Nelle vecchie versioni di PHP, occorre configurare e compilare il PHP con --with-pcre-regex[=DIR] per attivare queste funzioni.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 1. Costanti di PREG
costante | descrizione |
---|---|
PREG_PATTERN_ORDER | Ordina i risultati in modo tale che $matches[0] sia l'array di tutti i testi riconosciuti, $matches[1] sia l'array delle stringhe identificate dal primo criterio posto tra parentesi, e così via. Questa costante si usa solo con preg_match_all(). |
PREG_SET_ORDER | Ordina i risultati in modo tale che $matches[0] sia l'array del primo set di testi riconosciuti, $matches[1] sia l'array del secondo set, e così via. Questa costante si usa solo con preg_match_all(). |
PREG_OFFSET_CAPTURE | Vedere la descrizione di PREG_SPLIT_OFFSET_CAPTURE. Questa costante è disponibile a partire dalla versione 4.3.0 di PHP. |
PREG_SPLIT_NO_EMPTY | Questa costante indica a preg_split() di restituire solo segmenti non vuoti. |
PREG_SPLIT_DELIM_CAPTURE | Questa costante indica a preg_split() di catturare le espressioni tra parentesi nel criterio di delimitazione. Questa costante è disponibile a partire dalla versione 4.0.5 di PHP. |
PREG_SPLIT_OFFSET_CAPTURE | Se viene impostato questo flag, per ogni testo riconosciuto viene restituito l'offset nella stringa di ricerca. Occorre notare che questo cambia il tipo di valore restituito nell'array, ogni elemento è, a sua volta, un'array composto dalla stringa riconosciuta, all'indice 0, e dall'offset della stringa nell'indice 1. Questa costante è disponibile a partire dalla versione 4.3.0 di PHP e si utilizza solo nella funzione preg_split(). |
Di seguito saranno elencati i valori attualmente previsti. I nomi posti tra parentesi si riferiscono ai corrispettivi nomi usati internamente da PCRE.
- i (PCRE_CASELESS)
Se si attiva questo modificatore, l'espressione regolare viene riconosciuta senza distinguere tra le lettere maiuscole e minuscole.
- m (PCRE_MULTILINE)
Per default, PCRE tratta il testo su cui fare la ricerca come una "singola linea" di caratteri (anche se in realtà può contenere diversi "a capo" (newline)). Il carattere di "inizio riga" (^) indica solamente l'inizio del testo passato. Analogamente il carattere di "fine riga" ($) indica la fine del testo o prima se vi sono dei caratteri di "a capo" (a meno che non sia attivato il modificatore D). In questo modo si comporta anche Perl.
Invece quando viene indicato questo modificatore, "inizio riga" e "fine riga" vengono identificati in base ai caratteri di "a capo" presenti nel testo (rispettivamente subito dopo e subito prima di questo carattere). Questo comportamento è equivalente al modificatore /m di Perl. Se nel testo passato non vi sono caratteri di "a capo" o non vi sono occorrenze dei caratteri ^ o $ nell'espressione regolare, l'uso di questo modificatore non ha effetto.
- s (PCRE_DOTALL)
Se si attiva questo modificatore, il carattere . usato nell'espressione regolare indica tutti i possibili caratteri compreso il carattere di "a capo" (newline). Senza questo modificatore il carattere "a capo" viene escluso. Questo modificare è equivalente a /s di Perl. Una espressione regolare contenente una forma negativa, come [^a], riconosce sempre un "a capo" a prescindere da questo modificatore.
- x (PCRE_EXTENDED)
Se si attiva questo modificatore, verranno ignorati gli spazi presenti nell'espressione regolare, tranne quelli preceduti dal carattere di escape (\) o posti all'interno di una classe di caratteri. Saranno, inoltre, ignorati i caratteri posti tra il simbolo # (se non è preceduto dall'escape, ed è posto al di fuori di una classe di caratteri) ed il successivo carattere di "a capo" (newline). Questo comportamento equivale al flag /x di Perl e consente di inserire dei commenti all'interno di espressioni regolari complesse. Gli spazi bianchi non devono mai comparire all'interno di sequenze speciali di caratteri, come, ad esempio, la sequenza (?( che introduce ad un criterio condizionale.
- e
Se viene specificato questo modificatore, la funzione preg_replace() valuta la stringa di sostituzione come codice PHP, quindi utilizza il risultato come testo da sostituire alle stringhe cercate. Gli apici singoli e doppi sono preceduti dal backslash nei riferimenti sostituiti.
Soltanto preg_replace() utilizza questo modificatore; le altre funzioni di PCRE lo ignorano.
Nota: Questo modificatore non è disponibile in PHP 3.
- A (PCRE_ANCHORED)
Se si specifica questo modificatore, si forza un 'ancoraggio' del criterio di ricerca. In pratica questo viene costretto a riconoscere il testo su cui si fa la ricerca solo dall'inizio. Questo effetto può essere ottenuto anche con particolari costruzioni dell'espressione regolare, che rappresentano gli unici modi utilizzabili in Perl per ottenere il medesimo scopo.
- D (PCRE_DOLLAR_ENDONLY)
L'uso di questo modificatore forza il carattere $ dell'espressione regolare a indicare la fine della stringa oggetto della ricerca. Senza questo modificatore il carattere $ indica la posizione subito prima dell'ultimo carattere se questo è un "a capo" (ma comunque non prima di ogni altro "a capo"). Questo modificatore viene ignorato se è attivato il modificatore m. Non vi sono flag equivalenti in Perl.
- S
Quando una espressione regolare è destinata ad essere utilizzata diverse volte, vale la pena dedicare del tempo ad ottimizzare la velocità di riconoscimento. L'uso di questo modificatore permette questa analisi. Al momento lo studio della velocità è significativo per i criteri di ricerca "non ancorati", cioè espressioni che non hanno un carattere di partenza fisso.
- U (PCRE_UNGREEDY)
Questo modificatore inverte la "voracità" delle occorrenze, in modo da non essere voraci per default, ma lo tornano ad essere se seguiti da "?". Questo flag non è compatibile con Perl. Questo comportamento può anche essere settato dalla sequenza (?U) settaggio dei modificatori all'interno del criterio di ricerca
- X (PCRE_EXTRA)
Questo modificatore attiva funzionalità addizionali di PCRE che sono incompatibili con Perl. Ogni backslash (\) posto nell'espressione regolare che non sia seguito da una lettera con significato speciale causa un errore, ciò per riservare queste sequenze a future espansioni. Per default, Perl considera il backslash (\) seguito da una lettera priva di significato speciale come un qualsiasi testo. Al momento non vi sono altre caratteristiche gestite tramite questo modificatore.
- u (PCRE_UTF8)
Questo modificatore attiva funzionalità di PCRE che sono incompatibili con Perl. Le stringhe di ricerca sono considerate come UTF-8. Questo modificatore è disponibile dalla versione 4.1.0 di PHP di Unix e dalla versione 4.2.3 sulla piattaforma win32.
La libreria PCRE è costituita da una serie di funzioni che utilizzano come criterio di riconoscimento le espressioni regolari mutuando la stessa sintassi e la stessa semantica di Perl 5, a parte qualche lieve differenza descritta di seguito. L'attuale implementazione corrisponde alla versione 5.005 di Perl.
In questo capitolo saranno descritte le differenze rispetto a Perl 5.005.
Per default, lo spazio bianco indica tutti i caratteri riconoscibili dalla funzione isspace() della libreria C, ciò non pregiudica la possibilità di compilare PCRE con un set di caratteri alternativi. Normalmente isspace() riconosce gli spazi, il salto pagina, il carattere 'a capo' (newline), il carattere carriage return, la tabulazione orizzontale e verticale. Perl 5 non riconosce nel set dei caratteri indicati dallo "spazio bianco" la tabulazione verticale. Infatti il carattere di escape \v è stato presente per diverso tempo nella documentazione di Perl, ma di fatto non viene riconosciuto. Tuttavia lo stesso carattere viene trattato come spazio bianco fino alla versione 5.002 di Perl. Nelle versioni 5.004 e 5.005 non viene riconosciuto il carattere \s.
PCRE non supporta occorrenze ripetute in espressioni che "guardano avanti". Perl lo permette, ma non nel modo a cui si possa pensare. Ad esempio, (?!a){3}, non indica che i tre caratteri successivi non debbano essere delle "a", ma indica per tre volte che il carattere successivo non debba essere una "a".
Il riconoscimento di criteri parziali che possono verificarsi all'interno di espressioni che "guardano avanti" negative sono contati, ma i loro riferimenti non sono inseriti nel vettore degli offset. Perl valorizza le sue variabili da qualsiasi criterio che sia riconosciuto prima che l'espressione regolare fallisca nel riconoscere qualcosa, ma questo solo se l'espressione che "guarda avanti" contiene almeno un ramo alternativo.
Sebbene il carattere di 0 binario sia supportato nella stringa in cui si deve svolgere la ricerca, non è ammesso nel testo dell'espressione regolare, questo perché il testo viene passato come stringa C conclusa dal carattere zero. Si può comunque utilizzare la sequenza "\\x00" per richiedere il riconoscimento dello zero binario.
Non sono supportate le seguenti sequenze di escape di Perl: \l, \u, \L, \U, \E e \Q. Infatti queste sono implementate nelle funzioni di gestione delle stringhe di Perl e non nel suo motore di riconoscimento delle espressioni regolari.
L'asserzione di Perl \G non è supportata.
Ovviamente PCRE non supporta il costrutto (?{code}).
Al momento in cui si scrive, in Perl 5.005_02 vi sono alcune particolarità riguardanti la parametrizzazione delle stringhe catturate quando parte del criterio di riconoscimento viene ripetuto. Ad esempio, il riconoscimento di "aba" con il criterio /^(a(b)?)+$/, valorizza $2 con la lettera "b", usando il testo "aabbaa" con il criterio /^(aa(bb)?)+$/ non si ha la valorizzazione di $2. Tuttavia se il criterio di riconoscimento viene variato in /^(aa(b(b))?)+$/, sia $2 che $3 vengono valorizzate. Nelle versione 5.004 di Perl, la variabile $2 viene valorizzata in entrambi i casi, come pure è TRUE in PCRE. Se in futuro Perl cambierà nella gestione anche PCRE potrà cambiare di conseguenza.
Un'altra discrepanza non ancora risolta riguarda il criterio di riconoscimento /^(a)?(?(1)a|b)+$/, che in Perl 5.005_02 riconosce la stringa "a", mentre non accade in PCRE. Tuttavia in entrambi ( Perl e PCRE ) il riconoscimento di "a" con il criterio /^(a)?a/ non valorizza $1.
PCRE prevede alcune estensione alla gestione delle espressioni regolari di Perl:
Sebbene le asserzioni che "guardano indietro" richiedano testi di lunghezza fissa, è ammesso che ciascun ramo alternativo del criterio di ricerca possa intercettare stringhe di lunghezza differente. Al contrario Perl 5.005 richiede che tutte le stringhe abbiamo la stessa lunghezza.
Se viene settato PCRE_DOLLAR_ENDONLY e non viene attivato PCRE_MULTILINE, il meta-carattere $ indica soltanto la fine della stringa.
Se si attiva PCRE_EXTRA, un carattere backslash (\) seguito da una lettera che non abbia un significato speciale genera un errore.
Se si attiva PCRE_UNGREEDY, si inverte la "voracità" delle occorrenze, in modo da non essere voraci per default, ma lo tornano ad essere se seguiti da "?".
Di seguito verrà descritta la sintassi e la semantica delle espressioni regolari così come sono supportate da PCRE. La descrizione delle espressioni regolari può essere reperita anche nei manuali di Perl e in numerosi altri libri, alcuni dei quali ricchi di esempi. Ad esempio il libro di Jeffrey Friedl intitolato "Mastering Regular Expressions", edito da O'Reilly (ISBN 1-56592-257-3), li tratta in modo dettagliato. Questa descrizione, invece, viene intesa come una documentazione di riferimento. Una espressione regolare è un criterio utilizzato per identificare parti di un testo partendo da sinistra verso destra. La maggior parte delle lettere identifica se stessa nel testo oggetto del riconoscimento. Ad esempio il banale testo La volpe veloce intercetta la parte del testo uguale all'espressione regolare.
La potenza delle espressioni regolari deriva dalla possibilità di inserire criteri alternativi oppure ripetuti. Questi sono codificati nel criterio di ricerca tramite l'uso di meta-caratteri, lettere che non indicano se stesse, ma sono interpretate in modo particolare.
Esistono due differenti set di meta-caratteri: quelli che sono riconosciuti ovunque tranne che all'interno di parentesi quadrate, e quelli che sono riconosciuti all'interno di parentesi quadrate. I meta-caratteri che si usano all'esterno delle parentesi quadrate sono:
carattere di escape generico con diversi utilizzi
indica l'inizio del testo (o della linea in modalità multi-linea)
indica la fine del testo (o della linea in modalità multi-linea)
indica qualsiasi carattere tranne "a capo" (per default)
carattere di inizio della definizione di classe
carattere di fine della definizione di classe
inizio di un ramo alternativo
inizio di un criterio di riconoscimento parziale
fine del criterio di riconoscimento parziale
estende il significato di (, oppure 0 o 1 occorrenza, oppure occorrenza minima
0 o più occorrenze
1 o più occorrenze
inizia l'intervallo minimo/massimo di occorrenze
termina l'intervallo minimo/massimo di occorrenze
carattere di escape generico con diversi utilizzi
nega la classe, ma solo se posto all'inizio
indica un intervallo
chiude la classe di caratteri
Il carattere backslash (\) ha diversi utilizzi. Primo uso: se viene anteposto a caratteri non alfanumerici, rimuove gli eventuali significati speciali che il carattere può avere. Questo utilizzo di backslash come carattere di escape può essere svolto sia all'interno delle classi di caratteri sia all'esterno.
Ad esempio, un criterio che deve riconoscere il carattere "*" conterrà "\*". Ciò si applica indipendentemente dal carattere seguente, sia esso interpretabile come meta-carattere o meno. Nel caso in cui un carattere non alfanumerico debba identificare se stesso è opportuno farlo precedere dal "\". In particolare per identificare un backslash occorre scrivere "\\".
Se nel criterio di riconoscimento si specifica l'opzione PCRE_EXTENDED, lo spazio bianco (diversamente da quando si trova all'interno di una classe di caratteri), e i caratteri posti tra "#" e un "a capo" all'esterno di una classe di caratteri sono ignorati. Un backslash può essere usato come escape per inserire uno spazio bianco od il carattere "#" come parte del criterio di riconoscimento.
Un secondo utilizzo del backslash consiste nel codificare in modo visibile dei caratteri non visibili. Non ci sono restrizioni nella presenza di caratteri non-stampabili, a parte lo zero binario terminante la stringa dell'espressione regolare. Di seguito saranno elencate le sequenze di caratteri che è preferibile utilizzare per la loro semplicità al posto delle corrispondenti codifiche binarie.
allarme, il carattere BEL (hex 07)
"control-x", dove x è un qualsiasi carattere
escape (hex 1B)
salto pagina (hex 0C)
"a capo" (newline) (hex 0A)
carriage return (hex 0D)
tabulazione (hex 09)
carattere il cui codice esadecimale è hh
carattere il cui codice ottale è ddd, oppure riferimento all'indietro
Il preciso effetto di "\cx" è il seguente: se "x" è una lettera minuscola, viene convertita in lettera maiuscola. In pratica viene invertito il sesto bit (hex 40) del carattere. Quindi "\cz" diventa hex 1A, ma "\c{" diventa hex 3B, mentre "\c;" diventa hex 7B.
Dopo la sequenza "\x", saranno letti due numeri esadecimali (per le lettere non si distingue tra maiuscolo e minuscolo)
Dopo la sequenza "\0" saranno lette due cifre in ottale. In entrambi i casi se vi sono meno di due cifre, saranno usati i numeri presenti. Pertanto la sequenza "\0\x\07" indica 2 zeri binari seguiti dal carattere BEL. Occorre accertarsi di passare le cifre necessarie dopo lo zero iniziale se il carattere che segue può essere scambiato per una cifra in ottale.
Più complicata è la gestione del backslash seguito da una cifra diversa da 0. Al di fuori di una classe di caratteri, PCRE tratta le cifre che trova come numeri decimali. Se il numero è inferiore a 10, oppure vi sono state almeno altrettante parentesi sinistre, la sequenza viene considerata come un riferimento all'indietro. Più avanti, nella parte dei criteri parziali, sarà descritto come funzionano questi riferimenti.
All'interno di una classe di caratteri, oppure nel caso in cui il numero decimale è maggiore di 9 e non ci sono stati altrettanti criteri parziali, PCRE rilegge le prime 3 cifre seguenti il backslash in ottale e genera il carattere dagli 8 bit meno significativi del valore ottenuto. Ogni altra cifra seguente indica se stessa. Ad esempio:
è un'altro modo per indicare uno spazio
ha il medesimo significato dell'esempio precedente che non vi sono 40 sotto-criteri
è sempre un riferimento all'indietro
può essere un riferimento all'indietro o un'altro modo per indicare il carattere di tabulazione
è ancora il carattere di tabulazione
il carattere di tabulazione seguito da "3"
è il carattere con il codice ottale 113 (poiché non ci possono essere più di 99 riferimenti all'indietro)
è un byte con tutti i bit a 1
può essere un riferimento all'indietro o uno zero binario seguito da "8" e da "1"
Occorre rilevare che valori ottali maggiori di 100 non devono essere preceduti dallo zero, questo perché la libreria considera solo tre cifre.
Tutte le sequenze che definiscono il valore di un singolo byte possono essere utilizzate sia all'interno sia all'esterno delle classe di caratteri. Inoltre, all'interno delle classi di caratteri, la sequenza "\b" viene interpretata come carattere di backspace (hex 08), mentre all'esterno ha un'altro significato (come descritto più avanti).
Il terzo utilizzo possibile per il backslash consiste nello specificare il tipo di carattere:
qualsiasi cifra decimale
qualsiasi carattere che non sia una cifra decimale
qualsiasi carattere identificato come spazio bianco
qualsiasi carattere che non sia identificato come spazio bianco
qualsiasi carattere che sia una "parola" (word)
qualsiasi carattere che non sia una "parola" (word)
Ciascuna coppia di sequenze di escape suddivide il set completo dei caratteri in due insiemi disgiunti. Un dato carattere deve essere identificato da un solo insieme di ciascuna coppia.
I caratteri definiti "parole" sono quelle lettere o cifre o il carattere underscore (_), cioè qualsiasi carattere che possa essere parte di una "parola" in Perl. In PCRE le definizioni di lettere e cifre vengono gestite tramite le tabelle dei caratteri, che possono variare in base a specifici parametri di localizzazione (vedere il paragrafo intitolato "Supporto alle localizzazioni"). Ad esempio, nella localizzazione fr (relativa alla Francia), qualche codice carattere maggiore di 128 è utilizzato per le lettere accentate, e queste sono identificate tramite la sequenza \w.
Queste sequenze di tipi di caratteri possono apparire sia all'interno sia all'esterno delle classi di caratteri. Ciascuna di esse identifica un carattere del tipo appropriato. Se durante la fase di identificazione di un testo, si giunge al termine della stringa in cui si esegue il riconoscimento e si hanno ancora di queste sequenze da incrociare, l'operazione di identificazione fallirà perché, ovviamente, non vi sono più caratteri in cui riconoscere le suddette sequenze.
Il quarto utilizzo per il backslash riguarda la costruzione di particolari asserzioni. L'asserzione è una condizione che deve essere soddisfatta ad un certo punto del riconoscimento, senza "consumare" caratteri dalla stringa oggetto del riconoscimento. Più avanti verranno descritte asserzioni più complicate, costruite tramite l'uso di sotto-criteri di riconoscimento, per ora saranno illustrate delle semplici asserzioni costruite con il backslash:
limite di una parola
non limite di una parola
inizio dell'oggetto di ricerca (a prescindere dalla modalità multi-linea)
fine dell'oggetto di ricerca oppure newline alla fine (a prescindere dalla modalità multi-linea)
fine dell'oggetto di ricerca (a prescindere dalla modalità multi-linea)
Queste asserzioni non possono apparire all'interno di una classe di caratteri (attenzione che la sequenza "\b" all'interno di una classe di caratteri indica il carattere backspace).
Viene definito limite di una parola la posizione nella stringa oggetto della ricerca, nella quale il carattere corrente ed il carattere precedente non soddisfano la sequenza \w o la sequenza \W (ad esempio uno soddisfa la sequenza \w e l'altro carattere soddisfa la sequenza \W), oppure quella posizione, all'inizio o alla fine della stringa, nella quale rispettivamente il primo o l'ultimo carattere soddisfa la sequenza \w.
Le asserzioni \A, \Z e \z differiscono dai tradizionali caratteri "^" e "$" (descritti di seguito) per il fatto di identificare sempre l'inizio o la fine della stringa oggetto di ricerca a prescindere da quale opzione sia stata attivata. Infatti queste asserzioni non sono alterate da PCRE_MULTILINE oppure da PCRE_DOLLAR_ENDONLY. La differenza tra \Z e \z consiste nel fatto che \Z identifica sia il carattere precedente il newline posto al termine della stringa sia la fine della stringa, mentre \z identifica solo la fine.
In condizioni normali, il carattere "^", posto all'esterno di una classe di caratteri, indica un asserzione che è vera soltanto se il punto da cui si inizia a identificare il testo si trova all'inizio della stringa oggetto della ricerca. Al contrario, se il carattere "^" si trova all'interno di una classe di caratteri, assume altri significati (vedere i capitoli seguenti).
Non è necessario che il carattere "^" sia la prima lettera del criterio di riconoscimento nei casi in cui si utilizzino dei criteri di riconoscimento alternativi. Tuttavia è necessario che sia la prima lettera nei rami alternativi in cui compare. Se si inserisce il carattere "^" in tutte le alternative, caso che ricorre quando si vuole riconoscere un testo a partire dall'inizio della stringa, si dice che si è costruito un criterio di ricerca "ancorato". (Esistono anche altre costruzioni che portano all'ancoraggio di un criterio di ricerca).
Il carattere dollaro "$" è una asserzione che è TRUE soltanto se il punto a cui si è arrivati ad identificare il testo si trova alla fine della stringa oggetto della ricerca, o nella lettera immediatamente precedente il carattere di "a capo", che (per default) è l'ultimo carattere del testo. Il dollaro "$" non deve essere necessariamente l'ultima lettera di un criterio di riconoscimento se in questo si sono utilizzati dei criteri alternativi. Deve, comunque, essere l'ultima lettera nei criteri ove compare. Il carattere dollaro "$" non ha significati speciali all'interno di una classe di caratteri.
Il comportamento del simbolo "$" può essere variato in modo da identificare la reale fine della stringa oggetto di ricerca attivando il flag PCRE_DOLLAR_ENDONLY durante la compila o durante la fase di riconoscimento. Ciò non influisce sull'asserzione \Z.
Il comportamento dei simboli "^" e "$" può essere influenzato dall'opzione PCRE_MULTILINE. Quando viene attivata, questi caratteri identificano rispettivamente, oltre ai tradizionali inizio e fine testo, la lettera immediatamente successiva ed immediatamente precedente il carattere "\n" presente all'interno della stringa oggetto di ricerca. Per esempio il criterio /^abc$/ riconosce il testo "def\nabc" solo in modalità multi-linea. Di conseguenza i criteri di riconoscimento che sono "ancorati" in modalità singola linea, non lo sono in modalità multi-linea. L'opzione PCRE_DOLLAR_ENDONLY viene ignorata se si attiva il flag PCRE_MULTILINE .
Occorre rilevare che le sequenze \A, \Z e \z possono essere utilizzate per riconoscere l'inizio e la fine del testo in entrambe le modalità, e, se tutti i criteri alternativi iniziano con \A, si ha ancora un criterio "ancorato" a prescindere che sia attivata o meno l'opzione PCRE_MULTILINE.
Il carattere punto ".", all'esterno di una classe di caratteri, identifica qualsiasi carattere, anche quelli non stampabili, ma (per default) non il carattere "a capo". Invece se si abilita l'opzione PCRE_DOTALL si avrà anche il riconoscimento del carattere "a capo". La gestione del simbolo "." è svincolata dalla gestione dei simboli "^" ed "$", l'unica relazione che possono avere riguarda il carattere "a capo". Il punto "." non ha significati speciali all'interno delle classi di caratteri.
Un parentesi quadrata aperta "[" inizia una classe di caratteri; una parentesi quadrata chiusa "]" termina la definizione della classe. Di suo il carattere di parentesi quadrata chiusa non ha significati speciali. Se occorre inserire la parentesi chiusa all'interno di una classe di caratteri, questa deve essere la prima lettera (ovviamente deve seguire il carattere "^", se presente) oppure deve essere preceduta dal carattere di escape "\".
Una classe di caratteri identifica un singolo carattere nella stringa oggetto di ricerca; il carattere deve comparire nel set di caratteri definito dalla classe, a meno che il primo carattere della classe non sia l'accento circonflesso "^", in tal caso il carattere non deve essere nel set definito dalla classe. Se è richiesto l'inserimento del carattere "^" nel set definito dalla classe, questo non deve essere la prima lettera dopo la parentesi di apertura, oppure deve essere preceduto dal carattere di escape (\).
Ad esempio, la classe [aeiou] identifica ogni vocale minuscola, mentre [^aeiou] identifica tutti i caratteri che non siano delle vocali minuscole. Occorre notare che il simbolo "^" è un modo pratico per indicare i caratteri che sono nella classe, citando quelli che non lo sono. Questa non è una asserzione: consuma un carattere della stringa oggetto di ricerca e fallisce se ci si trova alla fine del testo.
In un riconoscimento senza distinzione tra minuscole e maiuscole, ogni lettera della classe identifica sia la versione maiuscola sia la minuscola. Così, ad esempio, la classe [aeiou] identifica sia "A" sia "a", e, in questo caso, [^aeiou] non identifica "A", mentre con la distinzione delle maiuscole [^aeiou] identifica la lettera "A".
Il carattere di "a capo" (newline) non viene trattato in modo speciale nelle classi di caratteri, indipendentemente dalle opzioni PCRE_DOTALL o PCRE_MULTILINE. La classe [^a] riconosce sempre il carattere "a capo".
Il segno meno (-) può essere usato per definire un intervallo all'interno della classe. Ad esempio, [d-m] identifica ogni lettera compresa tra d ed m inclusi. Se occorre inserire il segno meno (-) come carattere da riconoscere o lo si fa precedere dal carattere di escape (\), oppure lo si mette in una posizione tale che non possa essere identificato come definizione di un intervallo (ad esempio all'inizio o alla fine della definizione della classe).
Non è possibile usare il carattere "]" come limite di un intervallo. Un criterio definito come [W-]46], viene inteso come una classe di due caratteri (W e -) seguita dalla stringa 46], in tal modo sarebbero riconosciuti i testi "W46]" oppure "-46]". Quindi è necessario precedere la lettera "]" con il carattere di escape (\), in questo modo [W-\]46], viene interpretata correttamente come una singola classe contenente un range seguito da due caratteri separati. In alternativa, per delimitare l'intervallo si può utilizzare la notazione ottale di "]".
Gli intervalli utilizzano la sequenza di caratteri ASCII. Inoltre possono essere utilizzati per definire caratteri con specifica numerica (ad esempio [\000-\037]). Nei casi in cui si abiliti il riconoscimento senza distinzione tra lettere maiuscole e minuscole, gli intervalli comprendenti lettere identificano sia la lettera maiuscola che minuscola. Ad esempio, [W-c] è equivalente ad [][\^_`wxyzabc] (con il riconoscimento a prescindere dalla lettera maiuscole e minuscole), e, se si utilizza la tabella dei caratteri locali francesi "fr", [\xc8-\xcb] identifica la lettera "e" accentata sia maiuscola sia minuscola.
Nelle classi di caratteri si possono utilizzare le sequenze \d, \D, \s, \S, \w e \W per aggiungere altri tipi di caratteri alla classe. Ad esempio, [\dABCDEF] riconosce qualsiasi cifra esadecimale. Il carattere "^" può essere utilizzato con i caratteri maiuscoli per indicare un set di caratteri più ristretto che l'identificazione del set di caratteri minuscoli. Ad esempio, la classe [^\W_] identifica qualsiasi lettera o cifra ma non il trattino basso (_).
Tutti i caratteri non alfabetici, eccetto \, -, ^ (posto all'inizio) e ] non sono speciali per la classi di caratteri, e non sono dannosi se preceduti dal caratteri di escape (\).
La barra verticale (|) viene utilizzata per separare criteri di riconoscimento alternativi. Ad esempio il seguente criterio gilbert|sullivan può riconoscere "gilbert" oppure "sullivan". Ci possono essere innumerevoli alternative, compresa un'alternativa vuota (per identificare una stringa vuota). Il processo di riconoscimento prova tutte le alternative possibili (da sinistra a destra) fino a quando non ne trova una che sia soddisfatta. Se le alternative sono nella definizione di un criterio parziale il riconoscimento ha successo quando avviene su tutto il criterio.
Le opzioni PCRE_CASELESS, PCRE_MULTILINE , PCRE_DOTALL, PCRE_UNGREEDY e PCRE_EXTENDED possono essere cambiate "al volo" dall'interno del criterio di riconoscimento, utilizzando le sequenze di lettere definite per queste opzioni in Perl, racchiuse tra "(?" ed ")". Le lettere utilizzabili sono:
Tabella 1. Lettere per le opzioni interne
i | per PCRE_CASELESS |
m | per PCRE_MULTILINE |
s | per PCRE_DOTALL |
x | per PCRE_EXTENDED |
U | per PCRE_UNGREEDY |
Ad esempio, (?im) abilita il riconoscimento senza distinzione tra lettere maiuscole e minuscole e la modalità multi-linea. E' anche possibile disabilitare queste opzioni facendo precedere la lettera dal segno meno (-), o combinare l'attivazione con la disattivazione come nel caso (?im-sx), in cui si attiva PCRE_CASELESS e PCRE_MULTILINE e si disattiva PCRE_DOTALL e PCRE_EXTENDED. Se la lettera compare sia prima che dopo il segno meno (-) l'opzione resta disabilitata.
L'ambito di validità delle opzioni dipende da dove sono i flag di abilitazione/disabilitazione nel criterio di ricerca. Nei casi in cui il settaggio di un'opzione avvenga all'esterno di un qualsiasi criterio parziale (come definito in seguito) gli effetti sono medesimi di quando l'attivazione/disattivazione avviene all'inizio del criterio di riconoscimento. Gli esempi seguenti si comportano tutti allo stesso modo:
(?i)abc
a(?i)bc
ab(?i)c
abc(?i)
In questi esempi si attiva PCRE_CASELESS per il criterio "abc". In altre parole, questo settaggio compiuto al primo livello si applica a tutto il criterio (a meno che non vi siano altre variazioni nelle sotto-regole di riconoscimento). Qualora vi siano più settaggi per lo stesso parametro, viene utilizzato quello più a destra.
Se si inserisce la variazione di un'opzione in una sotto-regola gli effetti sono differenti. Questa è una variazione rispetto al comportamento di Perl 5.005. Una variazione apportata all'interno di una sotto-regola, vale solo per la parte della sotto-regola che segue la variazione, pertanto (a(?i)b)c identifica abc, aBc e nessuna altra stringa ( si assume che PCRE_CASELESS non sia usato). Da ciò deriva che le opzioni possono avere comportamenti differenti nelle varie parti del criterio di riconoscimento. Ogni variazione apportata ad una ramo alternativo del criterio viene estesa alle alternative successive della medesima sotto-regola. Ad esempio, (a(?i)b|c) identifica "ab", "aB", "c" e "C", anche se per identificare "C" viene scartato il primo ramo prima di incontrare il settaggio dell'opzione. Questo accade perché gli effetti dei settaggi vengono inseriti nella fase di compila. Diversamente si avrebbero dei comportamenti molto bizzarri.
Le opzioni specifiche di PCRE PCRE_UNGREEDY e PCRE_EXTRA possono essere variate nel medesimo modo delle opzioni Perl compatibili, utilizzando rispettivamente i caratteri U e X. Il flag (?X) è particolare poiché deve comparire prima di qualsiasi opzione esso attivi anche quando si trova al primo livello. E' opportuno inserirlo all'inizio.
Le sotto-regole sono delimitate dalle parentesi tonde e possono essere annidate. La definizione di una parte di una regola di riconoscimento come sotto-regola può servire a:
1. Localizzare un set di alternative. Ad esempio nel seguente criterio di riconoscimento cat(aract|erpillar|) si riconosce una tra le parole "cat", "cataract" oppure "caterpil- lar". Se non fossero state usate le parentesi, il criterio avrebbe permesso il riconoscimento delle parole "cataract", "erpillar" oppure una stringa vuota.
2. Identificare e catturare parte del testo riconosciuto dalla sotto-regola (come illustrato in seguito). Quando il riconoscimento dell'intero criterio ha avuto successo, le porzioni della stringa oggetto della ricerca identificate dalle sotto-regole sono restituite alla funzione chiamante tramite l'argomento vettore della funzione pcre_exec(). Per determinare il numero ordinale di ciascuna sotto-regola si contano le parentesi aperte da sinistra verso destra partendo da 1.
Ad esempio, se si esegue un riconoscimento nella frase "the red king" con il seguente criterio the ((red|white) (king|queen)) si ottengono i testi "red king", "red" e "king", rispettivamente identificati dalla sotto-regola 1, 2 e 3.
Il fatto che le parentesi tonde adempiano a due funzioni non sempre porta a situazioni comprensibili. Spesso capita di dovere raggruppare delle sotto-regole senza per questo essere richiesta la cattura del testo. A tale scopo l'uso della sequenza "?:" dopo la parentesi di apertura permette di indicare che questa sotto-regola non deve catturare il testo, e non deve essere conteggiata nel numero d'ordine delle sotto-regole di cattura. Ad esempio, applicando il criterio the ((?:red|white) (king|queen)) alla frase "the white queen", si catturano i testi "white queen" e "queen", rispettivamente numerati 1 e 2. Il numero massimo di testi catturabili è 99, il numero massimo di sotto-regole, a prescindere che siano di cattura o meno, è 200.
Come utile abbreviazione, nei casi in cui l'attivazione di alcune opzioni debba essere fatta all'inizio di una sotto-regola non di cattura, la lettera dell'opzione può comparire tra la "?" e ":". Pertanto i due criteri
(?i:saturday|sunday)
(?:(?i)saturday|sunday)
riconoscono esattamente lo stesso set di parole. Poiché i rami alternativi sono provati da sinistra verso destra, e le opzioni non sono azzerate fino a quando non si è conclusa la sotto-regola, una opzione attivata in un ramo alternativo si applica a tutte le alternative che seguono. Pertanto, nell'esempio di prima, sia la parola "SUNDAY" che la parola "Saturday" sono testi identificati correttamente.
Le ripetizioni sono il numero delle occorrenze che possono essere indicate dopo i seguenti elementi:
un singolo carattere, possibilmente preceduto dal carattere di escape (\)
il metacarattere .
una classe di caratteri
un riferimento all'indietro (vedere la sezione successiva)
una sotto-regola (a meno che non si tratti di una asserzione - vedere più avanti)
In generale una occorrenza specifica un numero minimo e massimo di riconoscimenti previsti tramite la specifica dei due limiti, posti tra parentesi graffe e separati da una virgola. Entrambi i numeri devono essere minori di 65536 ed il primo deve essere minore o uguale rispetto al secondo. Ad esempio: z{2,4} identifica "zz", "zzz" oppure "zzzz". La parentesi graffa chiusa di suo non rappresenta un carattere speciale. Se si omette il secondo numero, ma si lascia la virgola, non si indica un limite superiore; se sia la virgola sia il secondo numero sono omessi, l'occorrenza specifica l'esatto numero di riconoscimenti richiesti. Il criterio [aeiou]{3,} identifica almeno 3 o più vocali consecutive, mentre \d{8} identifica esattamente 8 cifre. Una parentesi graffa aperta che compaia in una posizione in cui non sia prevista una occorrenza, o che comunque non sia riconducibile alla sintassi di una occorrenza, viene tratta come il carattere "{". Ad esempio {,6} non indica delle occorrenze, ma una stringa di 4 caratteri.
L'indicazione {0} è permessa. Indica di comportarsi come se l'elemento precedente all'occorrenza non fosse presente.
Per praticità (e compatibilità verso il passato) si usano 3 abbreviazioni per le occorrenze più comuni:
E' anche possibile creare un ciclo infinito facendo seguire ad una sotto-regola che non identifica alcun carattere una occorrenza priva di limite superiore. Ad esempio: (a?)*
Le versioni precedenti di Perl e di PCRE segnalavano un errore durante la fase di compila per questi criteri. Tuttavia, poiché vi sono casi dove questi criteri possono essere utili, queste regole sono accettate, ma, se la ripetizione non riconosce alcun carattere, il ciclo viene interrotto.
Per default le occorrenze sono "bramose", infatti identificano più testi possibile (fino al numero massimo permesso), senza per questo fare fallire il riconoscimento della parte rimanente del criterio di ricerca. Il classico esempio dove questo comportamento può essere un problema, riguarda il riconoscimento dei commenti nei programmi C. Questi compaiono tra le sequenze /* ed */, ma all'interno, nel commento, si possono usare sia il carattere *, sia il carattere /. Il tentativo di individuare i commenti C con il seguente criterio /\*.*\*/ se applicato al commento /* primo commento */ nessun commento /* secondo commento */ non ha successo, perché identifica l'intera stringa a causa della "bramosia" dell'elemento ".*".
Tuttavia, se un'occorrenza è seguita da un punto interrogativo, questa cessa di essere "bramosa", e identifica il numero minimo di testi permessi. Pertanto il criterio /\*.*?\*/ si comporta correttamente con i commenti C. Il significato delle varie occorrenze non è stato cambiato, si è soltanto modificato il numero delle occorrenze da riconoscere. Attenzione a non confondere questo uso del punto interrogativo con il suo proprio significato. Dati i due utilizzi del ?, può anche capitare di averli entrambi come in \d??\d che, preferibilmente, identifica una cifra, ma può riconoscerne due se questa è l'unica via per soddisfare il riconoscimento dell'intero criterio.
Se si attiva l'opzione PCRE_UNGREEDY (un'opzione disponibile anche in Perl), per default le occorrenze non sono "bramose", ma ogni singola occorrenza può essere resa "bramosa" se seguita dal punto interrogativo. In altre parole si è invertito il normale comportamento.
Quando si indica un numero minimo di occorrenze maggiore di 1, per una sotto-regola posta tra parentesi, oppure si indica un numero massimo di occorrenze, la fase di compila richiede più spazio in proporzione ai valori minimo e massimo.
Se un criterio inizia con .* oppure .{0,} e si è attivata l'opzione PCRE_DOTALL (equivalente al /s di Perl), permettendo al . di identificare il carattere di "a capo", si dice che il criterio è implicitamente ancorato, perché qualsiasi elemento che segue sarà confrontato con ciascun carattere della stringa oggetto della ricerca, e pertanto non vi è nessuna posizione, a parte la prima, da cui ripartire per ritentare il riconoscimento dell'intero criterio. PCRE tratta tale criterio come se fosse preceduto dalla sequenza \A. Nei casi in cui è noto a priori che la stringa oggetto di ricerca non contiene caratteri di "a capo", vale la pena di attivare l'opzione PCRE_DOTALL se il criterio di ricerca inizia con ".*", per ottenere questa ottimizzazione, oppure, in alternativa, usare "^" per indicare in modo esplicito un ancoraggio.
Quando si ripete una sotto-regola di cattura, il testo estrapolato è la parte identificata dall'iterazione finale. Ad esempio se il criterio (tweedle[dume]{3}\s*)+ viene applicato al testo "tweedledum tweedledee", il testo estrapolato sarà "tweedledee". Tuttavia se vi sono delle sotto-regole annidate, il testo catturato può essere determinato dalle iterazioni precedenti. Ad esempio nel criterio /(a|(b))+/ applicato a "aba", la seconda stringa catturata è "b".
Esternamente ad una classe di caratteri, un backslah (\) seguito da una o più cifre maggiori di 0 è un riferimento all'indietro verso testi catturati precedentemente (ad esempio alla sinistra rispetto a dove ci si trova), conteggiati tramite il numero delle parentesi chiuse precedenti.
Tuttavia, se il numero che segue il backslash (\) è un valore inferiore a 10, si assume che si tratti sempre di un riferimento all'indietro, e pertanto viene generato un errore se nel criterio non vi sono almeno altrettante parentesi chiuse di sotto-regole di cattura. In altre parole per i numeri inferiori a 10 non è necessario che il numero parentesi precedenti (a sinistra) alla sotto-regola sia pari o maggiore al numero indicato. Vedere la sezione relativa al backslash per informazioni su come gestire le cifre seguenti il backslash.
Un riferimento all'indietro identifica ciò che è già stato catturato dalla sotto-regola, e non ciò che la sotto-regola stessa possa riconoscere. Ad esempio il criterio (sens|respons)e and \1ibility può riconoscere "sense and sensibility" oppure "response and responsibility", ma non il testo "sense and responsibility". Se al momento del riferimento all'indietro, è attiva la distinzione tra lettere maiuscole e minuscole, il formato della lettera diventa rilevante. Ad esempio, ((?i)rah)\s+\1 può identificare "rah rah" e "RAH RAH", ma non "RAH rah", anche se la sotto-regola originale eseguiva dei riconoscimenti a prescindere dalle lettere maiuscole e minuscole.
Nella medesima sotto-regola si possono avere più di un riferimento all'indietro. Se una sotto-regola non viene utilizzata in un particolare riconoscimento, un riferimento a questa ha sempre esito negativo. Ad esempio il criterio (a|(bc))\2 non avrà mai successo se l'identificazione della stringa inizia con "a" e non con "bc". Dato che sono possibili fino a 99 riferimenti all'indietro, tutte le cifre che seguono un backslash (\) sono considerate come parte di un potenziale numero di riferimento. Se il criterio continua con altri caratteri numerici, occorre stabilire un carattere per delimitare il numero del riferimento. Se si attiva l'opzione PCRE_EXTENDED questo carattere può essere lo spazio. Altrimenti si può usare un commento vuoto.
Un riferimento all'indietro non ha successo se viene inserito in una sotto regola prima che sia applicata. Con questo si intende, ad esempio, che (a\1) non avrà mai successo, ma, nel caso di una sottoregola ripetuta, si avrà un riscontro positivo. Ad esempio (a|b\1)+ identificherà qualsiasi numero di "a", ma anche "aba" oppure "ababaa" eccetera. In pratica a ciascuna iterazione della sotto-regola il riferimento andrà a sostituire la stringa riconosciuta tramite la sotto-regola dell'iterazione precedente. Affinchè il tutto funzioni, è necessario che la prima iterazione sia identificata senza l'ausilio del riferimento "all'indietro". Ciò può essere ottenuto o usando casi alternativi, come nell'esempio precedente, o usando le occorrenze indicando come numero minimo di occorrenze il valore zero.
L'asserzione è un test basato su un carattere, che può precedere o seguire l'attuale punto di riconoscimento, e non consuma alcun carattere. Le semplici asserzioni quali \b, \B, \A, \Z, \z, ^ e $ sono state descritte precedentemente. Asserzioni più complesse possono essere strutturate come delle sotto-regole. Se ne hanno di due tipologie: quelle che "guardano avanti" alla posizione attuale nella stringa oggetto del riconoscimento, e quelle che "guardano dietro" la posizione attuale.
Una asserzione definita come sotto-regola esegue il riconoscimento nel modo usuale, ma tale riconoscimento non sposta la posizione attuale nella stringa. Le asserzioni che "guardano avanti" cominciano per "(?=", se sono positive, per "(?!", se sono asserzioni negative. Ad esempio \w+(?=;) riconosce una parola seguita da ";", ma non include il punto e virgola nel riconoscimento, mentre foo(?!bar) identifica qualsiasi occorrenza di "foo" che non sia seguita da "bar". Attenzione che il criterio, apparentemente simile, (?!foo)bar non riconosce alcuna occorrenza di "bar" se questa è preceduta da qualsiasi testo che non sia "foo"; infatti l'espressione riconosce qualsiasi occorrenza di "bar", poiché l'asserzione (?!foo) è sempre TRUE quando i tre caratteri successivi sono "bar". Pertanto è necessario una asserzione che "guarda" all'indietro per ottenere effetto desiderato.
Le asserzioni che "guardano" indietro positive iniziano con "(?<=", e con "(?<!" le negative. Ad esempio: (?<!foo)bar riconosce una occorrenza di "bar" che non sia preceduta da "foo". Le asserzioni che "guardano" indietro hanno una limitazione: tutte le stringhe che riconoscono devono avere lunghezza fissa. Mentre, se si hanno casi alternativi, la limitazione della lunghezza fissa non sussiste. Quindi (?<=bullock|donkey) è una asserzione permessa, ma (?<!dogs?|cats?) genera un errore durante la fase di compila. Rami alternativi con lunghezze di stringa differenti sono permessi solo al primo livello dell'asserzione. Questa è da considerarsi una estensione rispetto a Perl 5.005, che richiede a tutte le alternative possibili la medesima lunghezza di stringa. Quindi una asserzione tipo (?<=ab(c|de)) non è permessa, poiché il suo singolo ramo di primo livello può identificare testi di due lunghezze differenti, ma è accettabile se riscritta usando due alternative di primo livello: (?<=abc|abde) L'implementazione di questo tipo di asserzioni consiste, per ciascuna alternativa, di uno spostamento all'indietro temporaneo per la lunghezza fissa necessaria, e ad un tentativo di riconoscimento del testo. Se non ci sono sufficienti caratteri precedenti alla posizione attuale, l'asserzione è destinata a fallire. L'uso accoppiato delle asserzioni che "guardano" indietro con sotto-regole a riconoscimento singolo può essere utile per identificare la fine dei testi; un esempio è illustrato al termine della sezione sulle sotto-regole a riconoscimento singolo.
Diverse asserzioni (di qualsiasi tipologia) possono essere utilizzate in modo consecutivo. Ad esempio: (?<=\d{3})(?<!999)foo riconosce "foo" preceduto da tre cifre che non siano "999". Occorre rilevare che ciascuna asserzione viene applicata singolarmente sul medesimo punto nella stringa oggetto di riconoscimento. Nell'esempio precedente per prima cosa si verifica che i tre caratteri precedenti siano cifre, quindi che non siamo "999". Questo esempio non identifica il testo se "foo" è preceduto da sei caratteri di cui i primi tre siano cifre e i secondi tre non siano "999". In pratica il testo "123abcfoo" non viene riconosciuto. Un criterio per riconoscere tale stringa può essere: (?<=\d{3}...)(?<!999)foo
In questo caso la prima asserzione controlla i primi sei caratteri verificando che i primi tre siano cifre, mentre la seconda asserzione verifica che i secondi tre caratteri non siano "999".
Le asserzioni possono essere annidate in qualsiasi combinazione. Il seguente esempio (?<=(?<!foo)bar)baz identifica il testo "baz" se è preceduto da "bar" il quale non deve essere preceduto da "foo", mentre (?<=\d{3}...(?<!999))foo è un'altro criterio che riconosce "foo" preceduto da tre cifre e da tre caratteri che non siano "999".
Le asserzioni definite come sotto-regole non catturano parte del testo e non possono essere ripetute (non avrebbe senso ripetere il medesimo riconoscimento sul medesimo testo). Se una di queste asserzioni contiene una sotto-regola di cattura questa viene conteggiata ai fini della numerazione delle regole di cattura. Tuttavia il testo viene effettivamente catturato solo nelle asserzioni positive, dato che non avrebbe senso farlo in quelle negative.
Le asserzioni possono essere composte fino ad un massimo di 200 sotto-regole. subpatterns.
Con l'indicazione del numero minimo e massimo di ripetizioni, il fallimento del riconoscimento della parte successiva del testo causa una ripetizione dell'identificazione con un numero di occorrenze diverse per verificare se in questa situazione anche il resto del testo viene identificato. In alcune situazioni può essere utile bloccare questo meccanismo, per la cambiata natura del criterio, oppure per fare fallire la ricerca prima di quando potrebbe accadere, oppure quando l'autore sa che non ci sono punti da cui ripartire.
Consideriamo, ad esempio, il criterio \d+foo applicato alla seguente linea 123456bar
Dopo avere identificato le 6 cifre ed avere mancato nel riconoscimento di "foo", il comportamento normale consiste nel tentare di procedere identificando 5 cifre per l'elemento \d+, quindi tentare con 4 e così via, prima di fallire definitivamente. Le sotto-regole a riconoscimento singolo permettono di specificare che, una volta riconosciuta una porzione della regola, questa non debba essere più considerata, in maniera tale da abortire immediatamente il riconoscimento se non si ha successo nell'identificare la parte restante del criterio. L'espressione per definire questo tipo di sotto-regola richiede un'altro tipologia di utilizzo speciale delle parentesi. Infatti iniziano con (?> come nell'esempio seguente: (?>\d+)bar
Questa tipologia di parentesi "inchioda" la parte di criterio una volta che avviene il riconoscimento, e, quindi, un fallimento successivo impedisce la ri-elaborazione di questo segmento. Tuttavia, occorre notare che gli elementi precedenti a questo si comportano in modo normale, e pertanto la ri-elaborazione, pur non toccando questo elemento, passa ai precedenti.
Una descrizione alternativa di questa tipologia di sotto-regola potrebbe essere che questo criterio identifica un testo come avrebbe fatto un singolo criterio se fosse stato ancorato alla posizione corrente.
Le sotto-regole a riconoscimento singolo non compiono la cattura del testo identificato. I casi semplici illustrati in precedenza possono essere considerati come una estremizzazione della ripetizione che porta ad inglobare tutto ciò che può. Pertanto, da una parte \d+ e \d+? sono sequenze che si adattano a riconoscere il numero corretto di cifre affinchè la ricerca abbia successo, dall'altra la sequenza (?>\d+) riconosce soltanto una sequenza di cifre.
Ovviamente queste costruzioni possono contenere diverse sotto-regole sia complesse, sia annidate.
Le sotto-regole a riconoscimento singolo possono essere usate congiuntamente alle asserzioni che guardano indietro, per definire una regola efficiente per riconoscere la fine della stringa. Ad esempio si consideri questo semplice criterio: abcd$ quando viene applicato ad un lungo testo può non avere successo. Questo perché il riconoscimento procede da sinistra verso destra, quindi PCRE prima cerca la "a", e poi cerca di riconoscere la parte restante del criterio. Se si modifica il criterio nel seguente modo ^.*abcd$ allora la sequenza iniziale .* in prima battuta identificherà tutto il testo, ma quando fallisce (poiché non vi sono più "a"), la ricerca tornerà indietro di uno (quindi tutto il testo tranne l'ultimo carattere), quindi, se continua non esserci la "a", si torna indietro di due, e così via. Continuando a tornare indietro alla ricerca della "a" si percorre tutto il testo da destra a sinistra, senza ottenere nulla di valido. Tuttavia se si riscrive il criterio come: ^(?>.*)(?<=abcd) non si attiva più lo scorrimento verso sinistra per .* , ma viene costretto a riconoscere tutto il testo (esito del primo tentativo). La asserzione successiva, esegue una verifica sulle ultime 4 lettere.Se fallisce, ciò avviene immediatamente, provocando un impatto sensibile nei tempi di elaborazione con testi molto lunghi.
Quando un criterio di riconoscimento contiene un elemento ripetuto senza limite all'interno di una sotto-regola che anch'essa possa ripetuta illimitatamente, l'uso delle sotto-regole a riconoscimento singolo è l'unico mezzo per evitare che certi mancati riconoscimenti richiedano molto tempo per essere rilevati. Ad esempio il criterio (\D+|<\d+>)*[!?] riconosce un numero indefinito di frammenti di testo contenenti a loro volta numeri o caratteri non numerici racchiusi tra <>, seguiti dai caratteri ! o ?. Quando il riconoscimento ha successo l'esecuzione è rapida, ma quando viene applicato al testo aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa richiede molto tempo prima di evidenziare l'errore. Questo accade perché la stringa può essere suddivisa tra i due elementi ripetuti in un elevato numero di modi che debbono essere verificati. Nell'esempio si usa [!?] piuttosto che un singolo carattere alla fine, questo perché sia Perl sia PCRE hanno una ottimizzazione che permette un veloce riconoscimento dell'errore se si usa un solo carattere. Infatti memorizzano l'ultimo carattere singolo richiesto per un riconoscimento, e, se non lo trovano nel testo, falliscono subito. Se il criterio viene modificato in ((?>\D+)|<\d+>)*[!?] le sequenze di caratteri non numerici non possono essere interrotte e pertanto il mancato riconoscimento viene rilevato più velocemente.
E' possibile forzare il processo di riconoscimento a obbedire alle sotto-regole in modo condizionato, oppure a scegliere tra due alternative in base al risultato di una asserzione, o piuttosto se la sotto-regola di cattura precedente ha riconosciuto il proprio testo. I due metodi possibili per esprimere una sotto-regola condizionale sono:
(?(condizione)yes-pattern)
(?(condizione)yes-pattern|no-pattern)
Se la condizione è soddisfatta, si usa la regola indicata in yes-pattern, altrimenti si applica il no-pattern (qualora sia specificato). Se nella sotto-regola vi sono più di due alternative, PCRE segnala un errore in fase di compila.
Vi sono due tipi di condizioni. Se il testo tra le parentesi consiste in una sequenza di cifre, allora la condizione è soddisfatta se la sotto-regola di cattura di quel numero è stata precedentemente riconosciuta. Si consideri il seguente criterio contenente degli spazi non significativi per renderlo più leggibile (si assuma che sia attiva l'opzione PCRE_EXTENDED) e lo si divida in tre parti per praticità di discussione: ( \( )? [^()]+ (?(1) \) )
La prima parte riconosce una parentesi aperta opzionale, e, se è presente, indica quello come primo segmento di stringa catturato. La seconda parte riconosce uno o più caratteri che non siano parentesi. Infine la terza parte è una sotto-regola condizionale che verifica se la prima parentesi è stata identifica o meno. Se accade, come nel caso in cui il testo inizi con una parentesi aperta, la condizione è TRUE, e quindi viene eseguito il ramo yes-pattern, richiedendo, conseguentemente, la parentesi chiusa. Diversamente, poiché non è specificato ramo no-pattern, non si esegue nessun altro riconoscimento. In altre parole questo criterio identifica un testo che possa essere racchiuso tra parentesi opzionali.
Se la condizione non è una sequenza di cifre, deve essere una asserzione. Questa può essere sia una asserzione che guarda avanti, sia una asserzione cha guarda indietro, sia positiva sia negativa. Si consideri il seguente criterio, ancora una volta contenente spazi non significativi, e con due alternative nella seconda linea:
(?(?=[^a-z]*[a-z])
\d{2}-[a-z]{3}-\d{2} | \d{2}-\d{2}-\d{2} )
La condizione è una asserzione che guarda avanti positiva, la quale identifica una sequenza opzionale di caratteri non alfabetici seguiti da una lettera. In altre parole, si testa la presenza di almeno una lettera nel testo. Se la lettera viene trovata si applica il primo criterio per il riconoscimento del testo, altrimenti viene applicato il secondo criterio. Questo criterio riconosce stringhe in due formati dd-aaa-dd oppure dd-dd-dd, dove aaa sono lettere e dd sono numeri.
La sequenza (?# indica l'inizio di un commento che si conclude con la successiva parentesi chiusa. Parentesi annidate non sono permesse. I caratteri che fanno parte di un commento non giocano alcun ruolo nella fase di riconoscimento.
Se viene attivata l'opzione PCRE_EXTENDED, un carattere # privo della sequenza di escape (\) all'esterno di una classe di caratteri apre un commento che continua fino al carattere di "a capo".
Si consideri il caso in cui si debba riconoscere una stringa tra parentesi, si supponga inoltre di dovere ammettere un numero arbitrario di parentesi annidate. Senza l'uso della ricorsione, il miglior metodo consiste nel preparare un criterio che identifichi un numero finito di parentesi annidate. Però, in questo modo non si gestisce un numero arbitrario si parentesi annidate. Nella versione 5.6 di Perl è stata introdotta, a livello sperimentale, la possibilità per i criteri di riconoscimento di essere ricorsivi. Allo scopo è stata definita la sequenza speciale (?R). Il criterio illustrato di seguito risolve il problema delle parentesi (si assume che l'opzione PCRE_EXTENDED sia attivata in modo da ignorare gli spazi): \( ( (?>[^()]+) | (?R) )* \)
In principio si identifica la parentesi di apertura. Quindi si cerca un numero indefinito di stringhe che possano essere composte da caratteri che non siano parentesi, oppure che siano riconosciute ricorsivamente dal criterio (ad esempio una stringa correttamente tra parentesi). Infine si cerca la parentesi di chiusura.
In questo particolare esempio si hanno arbitrarie ripetizioni annidate, e quindi l'uso delle sotto-regole a riconoscimento singolo per il riconoscimento della stringa priva di parentesi è particolarmente utile se il criterio viene applicato ad un testo non riconoscibile. Ad esempio, applicando il criterio a (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() si ottiene un esito di mancato riconoscimento rapidamente. Se, al contrario, non si fosse usato il criterio a riconoscimento singolo, sarebbe occorso molto tempo per avere un esito dato che vi sono moltissimi modi in cui i caratteri di ripetizione + e * possono essere applicati al testo, richiedendo, pertanto, la verifica di tutte le combinazioni prima di fornire l'esito negativo.
Il valori restituiti da una sotto-regola di cattura sono quelli ottenuti dal livello di ricorsione più esterno. Se il criterio illustrato in precedenza venisse applicato al testo (ab(cd)ef) Il valore ottenuto sarebbe "ef", che rappresenta l'ultimo valore catturato al livello più alto. Se si aggiungono altre parentesi al criterio, ottenendo \( ( ( (?>[^()]+) | (?R) )* ) \) allora il testo ottenuto sarebbe "ab(cd)ef", cioè il valore delle parentesi di livello più alto. Se nel criterio vi sono più di 15 sotto-regole di cattura, PCRE ha necessità di ottenere maggiore memoria per archiviare le informazioni durante la ricorsione. Questa memoria è ottenuta utilizzando pcre_malloc, al termine verrà liberata con pcre_free. Se non può essere ottenuta ulteriore memoria, si ha il salvataggio delle informazioni dei primi 15 testi catturati, dato che non vi è modo di restituire un messaggio di memoria insufficiente dalla ricorsione.
Certi elementi utilizzati per i criteri di riconoscimento sono più efficienti di altri. E' più efficiente usare le classi di caratteri come [aeiou] piuttosto che un gruppo di alternative come (a|e|i|o|u). In generale la costruzione più semplice per ottenere un dato scopo è la più efficiente. Nel libro di Jeffrey Friedl sono illustrate varie tecniche sull'ottimizzazione delle espressioni regolari.
Quando un criterio comincia con .* ed è attiva l'opzione PCRE_DOTALL, il criterio è implicitamente ancorato da PCRE, dato che può rico- noscere solo l'inizio della stringa. Tuttavia, se non è attivo PCRE_DOTALL, PCRE non può fare questa ottimizzazione, perché il meta-carattere . non ri- conosce più il carattere di "a capo", e quindi se la stringa contiene dei caratteri di "a capo", il riconoscimento può par- tire dal carattere immediatamente successivo ad uno di questi e non dall'inizio. Ad esempio il criterio (.*) second può eseguire un riconoscimento nel testo "first\nand second" (dove \n indica il carattere "a capo") ottenendo "and" come prima stringa catturata. perché ciò accada è necessario che PCRE possa iniziare il riconoscimento dopo ogni "a capo".
Se si deve usare un simile criterio in stringhe che non conten- gono caratteri di "a capo", le performance migliori si possono ottenere abilitando PCRE_DOTALL, oppure iniziando il criterio con ^.* in modo da richiedere un ancoraggio esplicito. Così si risparmia a PCRE di scandirsi il testo alla ricerca di un "a capo" da cui ripartire per la ri- cerca.
Occorre prestare attenzione ai criteri che contengono ripeti- zioni indefinite annidate. Possono richiedere molto tempo se applicati a stringhe non riconoscibili. Si consideri il fram- mento (a+)*
Questo può riconoscere "aaaa" in 33 modi differenti, e questo numero può crescere molto rapidamente se la stringa da ricono- scere è più lunga. (Il carattere di ripetizione * può eseguire riconoscimenti per 0,1,2,3 o 4 ripetizioni, e per ciascuna di esse, tranne lo 0, il carattere di ripetizione + può esegui- re riconoscimenti per diversi numeri di volte). Quindi se la parte successiva del criterio è tale da non permettere il com- pletamento del riconoscimento, PCRE, per principio, ugualmente tenta tutte le possibili variazioni, richiedendo diverso tempo.
Una ottimizzazione riesce a catturare qualche caso semplice come in (a+)*b dove si indica che seguirà un carattere alfanumerico. PCRE, prima di imbarcarsi nella procedura standard di riconoscimen- to, verifica se nel testo vi è la lettera "b", e se non c'è restituisce immediatamente un esito negativo. Tuttavia se non viene indicata una lettera seguente questa ottimizzazione non può essere utilizzata. Se ne può notare la differenza analiz- zando il comportamento del criterio (a+)*\d rispetto al precedente. Il primo, utilizzato con una stringa composta da "a", fallisce immediatamente, l'ultimo richiede un tempo apprezzabile, soprattutto se applicato a stringhe con più di 20 caratteri.
(PHP 4, PHP 5)
preg_grep -- Restituisce una matrice degli elementi riconosciuti tramite le espressioni regolariLa funzione preg_grep() restituisce una matrice composta dagli elementi dell'array testo che soddisfano i criteri impostati nel parametro espressione_regolare.
Il parametro flags può assumere i seguenti valori:
Con questo valore, la funzione preg_grep()gli elementi della matrice di input che non soddisfano la data espressione_regolare. Questo valore è disponibile a partire da PHP 4.2.0.
A partire dalla versione 4.0.4 di PHP, la matrice risultante dalla funzione preg_grep(), viene indicizzata utilizzando le chiavi dalla matrice di input. Se non si desidera un comportamento simile, applicare la funzione array_values() alla matrice ottenuta da questa funzione per ricalcolare gli indici.
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
preg_match_all -- Esegue un riconoscimento globale con le espressioni regolariLa funzione ricerca tutte le espressioni regolari passate nel parametro espressione_regolare all'interno della stringa testo. I testi riconosciuti sono posti all'interno della matrice TestiRiconosciuti, nell'ordine specificato da flags.
Dopo avere riconosciuto il primo segmento di testo, le ricerche seguenti saranno effettuate a partire dall'ultima ricerca specificata.
Il parametro flags può essere la combinazione dei seguenti flag (da notare che non ha senso utilizzare PREG_PATTERN_ORDER in unione a PREG_SET_ORDER):
I testi riconosciuti saranno organizzati in modo tale da avere in $TestiRiconosciuti[0] la matrice di tutti i testi riconosciuti, in $TestiRiconosciuti[1] la matrice di tutti i testi che soddisfino il primo criterio di riconoscimento posto tra parentesi tonde, in $TestiRiconosciuti[2] si avranno i testi che soddisfino il secondo criterio e cosi via.
<?php preg_match_all("|<[^>]+>(.*)</[^>]+>|U", "<b>example: </b><div align=left>this is a test</div>", $out, PREG_PATTERN_ORDER); echo $out[0][0].", ".$out[0][1]."\n"; echo $out[1][0].", ".$out[1][1]."\n"; ?> |
Questo esempio produrrà:
<b>example: </b>, <div align=left>this is a test</div> example: , this is a test |
Nell'esempio, $out[0] contiene la matrice di tutte le stringhe che soddisfano i criteri impostati, $out[1] contiene la matrice dei testi delimitati dai tag.
Usando questo parametro come ordine dei riconoscimenti, si avrà in $TestiRiconosciuti[0] una matrice con il primo set di testi riconosciuti, in $TestiRiconosciuti[1], la matrice con il secondo set di testi riconosciuti e così via.
<?php preg_match_all("|<[^>]+>(.*)</[^>]+>|U", "<b>example: </b><div align=\"left\">this is a test</div>", $out, PREG_SET_ORDER); echo $out[0][0].", ".$out[0][1]."\n"; echo $out[1][0].", ".$out[1][1]."\n"; ?> |
Questo esempio visualizzerà:
<b>example: </b>, example: <div align="left">this is a test</div>, this is a test |
In questo esempio $out[0] è la matrice del primo set di testi riconosciuti. Nel dettaglio $out[0][0] conterrà il testo che incrocia l'intero criterio impostato, $out[0][1] conterrà il testo riconosciuto tramite il prima regola di riconoscimento presente nel criterio globale. Analogo discorso si può fare per $out[1]. In questo caso il ragionamento verrà svolto su un secondo segmento della stringa che soddisfi le condizioni poste dal criterio di riconoscimento.
Se viene impostato questo flag, per ogni testo riconosciuto viene restituito l'offset della stringa. Occorre notare che questo cambia il tipo di valore restituito nell'array, infatti ogni elemento è, a sua volta, un'array composto dalla stringa riconosciuta, all'indice 0, e dall'offset della stringa nell'indice 1. Questa costante è disponibile a partire dalla versione 4.3.0 di PHP.
Qualora non si specifichi il parametro flags, si assume per default il valore PREG_PATTERN_ORDER.
Normalemente la ricerca parte dall'inizio della stringa oggetto di ricerca. Con il parametro opzionale offset si può specificare da dove cominciare la ricerca. Equivale a passare substr()($testo, $offset) alla funzione preg_match() al posto del parametro testo. Il parametro offset è disponibile a partire dalla versione 4.3.3 di PHP.
La funzione restituisce il numero dei riconoscimenti completi svolti (che possono essere zero), oppure FALSE se si verificano degli errori.
Esempio 2. Ricerca di tag HTML
Questo esempio visualizzerà:
|
Vedere anche preg_match(), preg_replace() e preg_split().
Esegue un riconoscimento nel parametro testo utilizzando l'espressione regolare indicata in criterio.
Se viene fornito il terzo parametro, testi_riconosciuti, questo verrà valorizzato con i risultati della ricerca. In dettaglio $testi_riconosciuti[0] conterrà il testo che si incrocia con l'intero criterio di ricerca, $testi_riconosciuti[1] conterrà il testo che soddisfa il primo criterio posto tra parentesi, $testi_riconosciuti[2] il secondo e così via.
Il parametro flags può assumere i seguenti valori:
Se viene impostato questo flag, per ogni testo riconosciuto viene restituito l'offset della stringa. Occorre notare che questo cambia il tipo di valore restituito nell'array, infatti ogni elemento è, a sua volta, un'array composto dalla stringa riconosciuta, all'indice 0, e dall'offset della stringa nell'indice 1. Questa costante è disponibile a partire dalla versione 4.3.0 di PHP.
Normalemente la ricerca parte dall'inizio della stringa oggetto di ricerca. Con il parametro opzionale offset si può specificare da dove cominciare la ricerca. Equivale a passare substr()($testo, $offset) alla funzione preg_match() al posto del parametro testo. Il parametro offset è disponibile a partire dalla versione 4.3.3 di PHP.
La funzione preg_match() restituisce il numero di volte in cui è avvenuto il riconoscimento del criterio. Questo può essere 0 (nessun riconoscimento) oppure 1 se preg_match() si ferma dopo il primo riconoscimento. In condizioni normali, preg_match_all() continua il riconoscimento fino alla fine del parametro testo. preg_match() restituirà FALSE se si verifica un errore.
Suggerimento: Non utilizzare la funzione preg_match() se si desidera controllare se una stringa è contenuta in un'altra. Piuttosto utilizzare strpos() oppure strstr() che sono più veloci.
Esempio 2. Cerca la parola "web"
|
Esempio 3. Estrapolazione del dominio da un URL
L'esempio visualizzerà:
|
Vedere anche preg_match_all(), preg_replace() e preg_split().
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
preg_quote -- Inserisce il carattere di escape nei caratteri delle espressioni regolariLa funzione preg_quote() inserisce il carattere di escape (\) davanti ad ogni carattere presente in stringa che sia parte della sintassi di una espressione regolare. Questa funzione è utile nei casi in cui si generino, durante l'esecuzione, delle stringhe da usare come criteri di riconoscimento, e queste possano contenere dei caratteri speciali per le espressioni regolari.
Se viene specificato un carattere come parametro delimitatore, anche a questo sarà anteposto il carattere di escape (\). Ciò è particolarmente utile per porre il carattere di escape nei delimitatori richiesti dalle funzioni PCRE. Il carattere di delimitazione più comunemente utilizzato è /.
I caratteri speciali per le espressioni regolari sono: . \\ + * ? [ ^ ] $ ( ) { } = ! < > | :
Esempio 2. Esempio di come rendere in corsivo una qualsiasi parola di un testo
|
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
(PHP 4 >= 4.0.5, PHP 5)
preg_replace_callback -- Esegue ricerche e sostituzioni con espressioni regolari usando il callbackFondamentalmente questa funzione si comporta come preg_replace(), eccetto che per la presenza del callback. Con quest'ultimo parametro si indica una funzione da richiamare a cui verrà passata una matrice con i testi riconosciuti in testo. La funzione di callback dovrebbe restituire la stringa da sostituire.
Esempio 1. Esempio dell'uso di preg_replace_callback()
|
Spesso si ha la necessità di richiamare la funzione callback soltanto in un unico posto. In questo caso si può utilizzare create_function() per dichiarare una funzione anonima come callback per preg_replace_callback().In questo modo si hanno tutte le informazioni per la chiamata in un unico posto e non si disperde con funzioni di callback non utilizzate altrove.
Esempio 2. preg_replace_callback() e create_function()
|
Vedere anche preg_replace() create_function(), e information about the callback type.
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
preg_replace -- Esegue una ricerca ed una sostituzione con le espressioni regolariLa funzione ricerca in testo i criteri impostati in espressione_regolare. Se riconosce dei testi, li sostituisce con sostituto. Se si specifica limite, verranno sostituiti solamente limite testi riconosciuti; se viene omesso, oppure impostato a -1, verranno sostituiti tutti i testi riconosciuti.
Il parametro sostituto può contenere riferimenti nella forma di \\n, oppure, a partire dalla versione 4.0.4 di PHP, $n , con la preferenza per la seconda sintassi. Questo tipo di riferimento verrà sostituito dal testo che soddisfa l'n -esimo criterio presente in espressione_regolare . Sono ammessi numeri compresi tra 0 e 99 inclusi. Il valore 0 (\\0 oppure $0) si riferisce al testo riconosciuto tramite tutta l'espressione regolare passata. Nel conteggio dei criteri di riconoscimento presenti, sono contate le parentesi aperte da sinistra verso destra partendo da 1.
Quando si lavora con un criterio di sostituzione in cui un riferimento all'indietro è immediatamente seguito da un'altro numero (ad esempio un numero che segue immediatamente il criterio riconosciuto), non si possono utilizzare le solite notazioni, \\1, per i riferimenti all'indietro. Ad esempio, il testo \\11 confonderebbe preg_replace() poichè non saprebbe se si desidera il riferimento all'indietro \\1 seguito dal numero 1, oppure se è desiderato il riferimento \\11 seguito da niente. In questi casi la soluzione consiste nell'uso di \${1}1. In questo modo si crea un riferimento all'indietro $1 isolato dal numero 1.
Se verranno riconosciuti dei testi, la funzione restituisce la nuova versione di testo, altrimenti il parametro sarà restituito inalterato.
Ogni parametro passato alla funzione preg_replace(), (eccetto limite) può essere una matrice ad una dimensione. Quando si utilizzano matrici con espressione_regolare e sostituto, le chiavi sono processate nell'ordine con cui appaiono nella matrice. Questo non è necessariamente l'ordine numerico dell'indice. Se si utilizzano degli indici per identificare quale espressione_regolare debba essere sostituita da sostituto, occorre eseguire la funzione ksort() su ciascuna matrice prima di eseguire preg_replace().
Esempio 2. Uso di matrici indicizzate con preg_replace()
Output:
Utilizzando ksort su entrambe le matrici otteniamo cio che vogliamo.
Output :
|
Se il campo testo è una matrice, la ricerca e la sostituzione sarà eseguita su ogni elemento della matrice, e conseguentemente la funzione restituirà una matrice.
Se espressione_regolare ed sostituto sono entrambi delle matrici, la funzione preg_replace() utilizza gli elementi di ciascuna matrice per la ricerca e la sostituzione delle stringhe in testo. Nel caso in cui la matrice passata in sostituto abbia meno elementi che espressione_regolare, la funzione utilizzerà una stringa vuota per compensare gli elementi mancanti nella fase di sostituzione. Se, invece, espressione_regolare è una matrice, mentre il campo sostituto è una stringa, quest'ultima sarà usata come valore da sostituire ad ogni testo riconosciuto. Un discorso contrario non ha senso.
Il modificatore /e, permette alla funzione di considerare il testo posto in sostituto come codice PHP dopo aver valorizzato gli opportuni riferimenti. Suggerimento: accertarsi che sostituto sia del codice PHP valido, altrimenti si ottiene un errore di parsing alla linea della funzione preg_replace().
Esempio 5. Esempio di conversione di codice HTML in testo
|
Nota: Il parametro limite è stato aggiunto successivamente alla versione 4.0.1pl2 di PHP.
Vedere anche preg_match(), preg_match_all() e preg_split().
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
preg_split -- Suddivisione di una stringa tramite le espressioni regolariLa funzione restituisce una matrice di parti di testo suddivisi tramite i criteri indicati da espressione_regolare.
Se viene specificato il parametro limite, la funzione restituisce tante parti del testo iniziale quante sono indicate da limite. Può essere usato il valore -1 per indicare "nessun limite". Ciò torna utile in abbinamento all'uso del parametro flags.
Il parametro flags può essere la combinazione dei seguenti flag (la combinazione di più flag avviene con l'operatore |):
Specificando questo flag, la funzione preg_split() restituisce spezzoni di testo non vuoti.
Con l'uso di questo flag, la funzione cattura e restituisce eventuali espressioni poste tra parentesi nel parametro espressione_regolare. Questo flag è stato aggiunto nella versione 4.0.5.
Se viene impostato questo flag, per ogni testo riconosciuto viene restituito l'offset della stringa. Occorre notare che questo cambia il tipo di valore restituito nell'array; infatti ogni elemento è, a sua volta, un'array composto dalla stringa riconosciuta, all'indice 0, e dall'offset della stringa nell'indice 1. Questa costante è disponibile a partire dalla versione 4.3.0 di PHP.
Esempio 3. Suddivisione di una stringa in testi riconosciuti con i relativi offset.
visualizzerà
|
Nota: Il parametro flags è stato aggiunto nella versione 4 Beta 3 di PHP.
Vedere anche spliti(), split(), implode(), preg_match(), preg_match_all() e preg_replace().
The PDF functions in PHP can create PDF files using the PDFlib library created by Thomas Merz.
The documentation in this section is only meant to be an overview of the available functions in the PDFlib library and should not be considered an exhaustive reference. Please consult the documentation included in the source distribution of PDFlib for the full and detailed explanation of each function here. It provides a very good overview of what PDFlib is capable of doing and contains the most up-to-date documentation of all functions.
All of the functions in PDFlib and the PHP module have identical function names and parameters. You will need to understand some of the basic concepts of PDF and PostScript to efficiently use this extension. All lengths and coordinates are measured in PostScript points. There are generally 72 PostScript points to an inch, but this depends on the output resolution. Please see the PDFlib documentation included with the source distribution of PDFlib for a more thorough explanation of the coordinate system used.
Please note that most of the PDF functions require a pdfdoc as its first parameter. Please see the examples below for more information.
Nota: If you're interested in alternative free PDF generators that do not utilize external PDF libraries, see this related FAQ.
Nota: This extension has been moved to PECL as of PHP 4.3.9.
PDFlib is available for download at http://www.pdflib.com/products/pdflib/index.html, but requires that you purchase a license for commercial use. The JPEG and TIFF libraries are required to compile this extension.
Any version of PHP 4 after March 9, 2000 does not support versions of PDFlib older than 3.0.
PDFlib 3.0 or greater is supported by PHP 3.0.19 and later.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/pdflib.
To get these functions to work in PHP < 4.3.9, you have to compile PHP with --with-pdflib[=DIR]. DIR is the PDFlib base install directory, defaults to /usr/local. In addition you can specify the jpeg, tiff, and pnglibrary for PDFlib to use, which is optional for PDFlib 4.x. To do so add to your configure line the options --with-jpeg-dir[=DIR] --with-png-dir[=DIR] --with-tiff-dir[=DIR].
When using version 3.x of PDFlib, you should configure PDFlib with the option --enable-shared-pdflib.
As of PHP 4.3.9, you must install this extension through PEAR, using the following command: pear install pdflib.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Starting with PHP 4.0.5, the PHP extension for PDFlib is officially supported by PDFlib GmbH. This means that all the functions described in the PDFlib manual (V3.00 or greater) are supported by PHP 4 with exactly the same meaning and the same parameters. Only the return values may differ from the PDFlib manual, because the PHP convention of returning FALSE was adopted. For compatibility reasons, this binding for PDFlib still supports the old functions, but they should be replaced by their new versions. PDFlib GmbH will not support any problems arising from the use of these deprecated functions.
Tabella 1. Deprecated functions and their replacements
Old function | Replacement |
---|---|
pdf_put_image() | Not needed anymore. |
pdf_execute_image() | Not needed anymore. |
pdf_get_annotation() | pdf_get_bookmark() using the same parameters. |
pdf_get_font() | pdf_get_value() passing "font" as the second parameter. |
pdf_get_fontsize() | pdf_get_value() passing "fontsize" as the second parameter. |
pdf_get_fontname() | pdf_get_parameter() passing "fontname" as the second parameter. |
pdf_set_info_creator() | pdf_set_info() passing "Creator" as the second parameter. |
pdf_set_info_title() | pdf_set_info() passing "Title" as the second parameter. |
pdf_set_info_subject() | pdf_set_info() passing "Subject" as the second parameter. |
pdf_set_info_author() | pdf_set_info() passing "Author" as the second parameter. |
pdf_set_info_keywords() | pdf_set_info() passing "Keywords" as the second parameter. |
pdf_set_leading() | pdf_set_value() passing "leading" as the second parameter. |
pdf_set_text_rendering() | pdf_set_value() passing "textrendering" as the second parameter. |
pdf_set_text_rise() | pdf_set_value() passing "textrise" as the second parameter. |
pdf_set_horiz_scaling() | pdf_set_value() passing "horizscaling" as the second parameter. |
pdf_set_text_matrix() | Not available anymore |
pdf_set_char_spacing() | pdf_set_value() passing "charspacing" as the second parameter. |
pdf_set_word_spacing() | pdf_set_value() passing "wordspacing" as the second parameter. |
pdf_set_transition() | pdf_set_parameter() passing "transition" as the second parameter. |
pdf_open() | pdf_new() plus an subsequent call of pdf_open_file() |
pdf_set_font() | pdf_findfont() plus an subsequent call of pdf_setfont() |
pdf_set_duration() | pdf_set_value() passing "duration" as the second parameter. |
pdf_open_gif() | pdf_open_image_file() passing "gif" as the second parameter. |
pdf_open_jpeg() | pdf_open_image_file() passing "jpeg" as the second parameter. |
pdf_open_tiff() | pdf_open_image_file() passing "tiff" as the second parameter. |
pdf_open_png() | pdf_open_image_file() passing "png" as the second parameter. |
pdf_get_image_width() | pdf_get_value() passing "imagewidth" as the second parameter and the image as the third parameter. |
pdf_get_image_height() | pdf_get_value() passing "imageheight" as the second parameter and the image as the third parameter. |
Most of the functions are fairly easy to use. The most difficult part is probably creating your first PDF document. The following example should help to get you started. It creates test.pdf with one page. The page contains the text "Times Roman outlined" in an outlined, 30pt font. The text is also underlined.
Esempio 1. Creating a PDF document with PDFlib
|
The PDFlib distribution contains a more complex example which creates a page with an analog clock. Here we use the in-memory creation feature of PDFlib to alleviate the need to use temporary files. The example was converted to PHP from the PDFlib example. (The same example is available in the CLibPDF documentation.)
Esempio 3. pdfclock example from PDFlib distribution
|
Add a nested bookmark under parent, or a new top-level bookmark if parent = 0. Returns a bookmark descriptor which may be used as parent for subsequent nested bookmarks. If open = 1, child bookmarks will be folded out, and invisible if open = 0. Parameters parent and open are optional before PHP 4.3.5 or with PDFlib less than 5.
Esempio 1. pdf_add_bookmark() example
|
Adds a link to a web resource specified by filename. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_add_locallink().
Add a link annotation to a target within the current PDF file. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
dest is the zoom setting on the destination page, it can be one of retain, fitpage, fitwidth, fitheight or fitbbox.
See also pdf_add_launchlink().
Sets an annotation for the current page. icon is one of comment, insert, note, paragraph, newparagraph, key, or help. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. Adding a note to a PDF document with PDFlib
|
Add a file link annotation (to a PDF target). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_add_locallink() and pdf_add_weblink().
Adds an existing image as thumbnail for the current page. Thumbnail images must not be wider or higher than 106 pixels. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_open_image(), pdf_open_image_file() and pdf_open_memory_image().
Add a weblink annotation to a target url on the Web. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Add a counterclockwise circular arc from alpha to beta degrees with center (x; y) and radius r. Actual drawing of the circle is performed by the next stroke or fill operation.
Esempio 1. pdf_arcn() example
|
See also: pdf_arcn(), pdf_circle(), pdf_stroke(), pdf_fill() and pdf_fill_stroke().
Add a clockwise circular arc from alpha to beta degrees with center (x; y) and radius r. Actual drawing of the circle is performed by the next stroke or fill operation.
Esempio 1. pdf_arcn() example
|
See also: pdf_arc(), pdf_circle(), pdf_stroke(), pdf_fill() and pdf_fillstroke().
Add a file attachment annotation. icon is one of graph, paperclip, pushpin, or tag. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Only the 'Full' Acrobat software will be able to display these file attachments. All other PDF viewers will either show nothing or display a question mark.
Add a new page to the document. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. The width and height are specified in points, which are 1/72 of an inch.
Tabella 1. Common Page Sizes in Points
name | size |
---|---|
A0 | 2380✗3368 |
A1 | 1684✗2380 |
A2 | 1190✗1684 |
A3 | 842✗1190 |
A4 | 595✗842 |
A5 | 421✗595 |
A6 | 297✗421 |
B5 | 501✗709 |
letter (8.5"✗11") | 612✗792 |
legal (8.5"✗14") | 612✗1008 |
ledger (17"✗11") | 1224✗792 |
11"✗17" | 792✗1224 |
See also pdf_end_page().
Starts a new pattern definition and returns a pattern handle. width, and height define the bounding box for the pattern. xstep and ystep give the repeated pattern offsets. painttype=1 means that the pattern has its own colour settings whereas a value of 2 indicates that the current colour is used when the pattern is applied.
See also pdf_end_pattern().
Start a new template definition.
Add a circle with center (x, y) and radius r to the current page. Actual drawing of the circle is performed by the next stroke or fill operation.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. pdf_circle() example
|
See also: pdf_arc(), pdf_arcn(), pdf_curveto(), pdf_stroke(), pdf_fill() and pdf_fill_stroke().
Use the current path as clipping path. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Close an image retrieved with the pdf_open_image() function.
Close the page handle, and free all page-related resources. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Close all open page handles, and close the input PDF document. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_open_pdi().
Close the generated PDF file, and free all document-related resources. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_new().
Close the path, fill, and stroke it. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_closepath() and pdf_closepath_stroke().
Close the path, and stroke it. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_closepath() and pdf_closepath_fil_stroke().
Close the current path. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_closepath_stroke() and pdf_closepath_fil_stroke().
Concatenate a matrix to the CTM. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Print text at the next line. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Draw a Bezier curve from the current point, using 3 more control points. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Delete the PDF resource, and free all internal resources. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_new().
Finish the page. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_begin_page().
Finish the pattern definition. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_begin_pattern().
Finish the template definition. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
This function is deprecated, use one of the pdf_stroke(), pdf_clip() or pdf_closepath_fill_stroke() functions instead.
Fill and stroke the path with the current fill and stroke color. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_setcolor().
Fill the interior of the path with the current fill color. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_setcolor().
Prepare a font for later use with pdf_setfont(). The metrics will be loaded, and if embed is nonzero, the font file will be checked, but not yet used. encoding is one of builtin, macroman, winansi, host, a user-defined encoding name or the name of a CMap. Parameter embed is optional before PHP 4.3.5 or with PDFlib less than 5.
pdf_findfont() returns a font handle or FALSE on error.
Get the contents of the PDF output buffer. The result must be used by the client before calling any other PDFlib function.
Returns the major version number of the PDFlib.
See also pdf_get_minorversion().
Returns the minor version number of the PDFlib.
See also pdf_get_majorversion().
Get the contents of some PDFlib parameter with string type. Parameter modifier is optional before PHP 4.3.5 or with PDFlib less than 5.
Get the contents of some PDI document parameter with string type.
Get the contents of some PDI document parameter with numerical type.
Get the contents of some PDFlib parameter with float type. Parameter modifier is optional before PHP 4.3.5 or with PDFlib less than 5.
Reset all implicit color and graphics state parameters to their defaults. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Draw a line from the current point to (x, y). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Make a named spot color from the current color. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_setcolor().
Set the current point to (x, y. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: The current point for graphics and the current text output position are maintained separately. See pdf_set_text_pos() to set the text output position.
Create a new PDF resource, using default error handling and memory management.
See also pdf_close().
Open a raw CCITT image.
Create a new PDF file using the supplied file name. If filename is empty the PDF document will be generated in memory instead of on file. The result must be fetched by the client with the pdf_get_buffer() function. Parameter filename is optional before PHP 4.3.5 or with PDFlib less than 5. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The following example shows how to create a pdf document in memory and how to output it correctly.
Esempio 1. Creating a PDF document in memory
|
Open an image file. Supported types are jpeg, tiff, gif, and png. stringparam is either empty, mask, masked, or page. intparam is either 0, the image id of the applied mask, or the page. Parameters stringparam and intparam are optional before PHP 4.3.5 or with PDFlib less than 5.
Use image data from a variety of data sources. Supported types are jpeg, ccitt, raw. Supported sources are memory, fileref, url. len is only used when type is raw, params is only used when type is ccitt.
(PHP 3 >= 3.0.10, PHP 4, PECL)
pdf_open_memory_image -- Opens an image created with PHP's image functionsThe pdf_open_memory_image() function takes an image created with the PHP's image functions and makes it available for the pdf resource. The function returns a pdf image identifier.
See also pdf_close_image() and pdf_place_image().
Prepare a page for later use with pdf_place_image()
Opens an existing PDF document and prepares it for later use.
See also pdf_close_pdi().
Place an image with the lower left corner at (x, y), and scale it. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Place a PDI page with the lower left corner at (x, y), and scale it. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Draw a (width * height) rectangle at lower left (x, y). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Restore the most recently saved graphics state. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Rotate the coordinate system by phi degrees. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Save the current graphics state. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Scale the coordinate system. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 3 >= 3.0.12, PHP 4, PECL)
pdf_set_border_color -- Sets color of border around links and annotationsSet the border color for all kinds of annotations. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Sets the border dash style for all kinds of annotations. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_setdash().
(PHP 3 >= 3.0.12, PHP 4, PECL)
pdf_set_border_style -- Sets style of border around links and annotationsSets the border style for all kinds of annotations. style is solid or dashed. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 3 >= 3.0.6, PHP 4, PECL)
pdf_set_info_author -- Deprecated: Fills the author field of the document(PHP 3 >= 3.0.6, PHP 4, PECL)
pdf_set_info_creator -- Deprecated: Fills the creator field of the document(PHP 3 >= 3.0.6, PHP 4, PECL)
pdf_set_info_keywords -- Deprecated: Fills the keywords field of the document(PHP 3 >= 3.0.6, PHP 4, PECL)
pdf_set_info_subject -- Deprecated: Fills the subject field of the document(PHP 3 >= 3.0.6, PHP 4, PECL)
pdf_set_info_title -- Deprecated: Fills the title field of the documentFill document information field key with value. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. key is one of Subject, Title, Creator, Author, Keywords, or a user-defined key.
Sets some PDFlib parameters with string type. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_set_value().
Set the text output position specified by x and y. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Set the value of some PDFlib parameter with float type. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_set_parameter().
Set the current color space and color. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. The parameter type can be fill, stroke or both to specify that the color is set for filling, stroking or both filling and stroking. The parameter colorspace can be gray, rgb, cmyk, spot or pattern. The parameters c1, c2, c3 and c4 represent the color components for the color space specified by colorspace. Except as otherwise noted, the color components are floating-point values that range from 0 to 1. Parameters c2, c3 and c4 are optional before PHP 4.3.5 or with PDFlib less than 5.
For gray only c1 is used.
For rgb parameters c1, c2, and c3 specify the red, green and blue values respectively.
For cmyk, parameters c1, c2, c3, and c4 are the cyan, magenta, yellow and black values, respectively.
For spot, c1 should be a spot color handles returned by pdf_makespotcolor() and c2 is a tint value between 0 and 1.
For pattern, c1 should be a pattern handle returned by pdf_begin_pattern().
Set the current dash pattern to b black and w white units. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Sets the flatness to a value between 0 and 100 inclusive. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Set the current font in the given size, using a font handle returned by pdf_findfont(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_findfont().
Set the current fill color to a gray value between 0 and 1 inclusive. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current stroke color to a gray value between 0 and 1 inclusive. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current fill and stroke color. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the linecap parameter to a value between 0 and 2 inclusive.
Sets the line join parameter to a value between 0 and 2 inclusive. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Sets the current linewidth to width. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Explicitly set the current transformation matrix. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Set the miter limit to a value greater than or equal to 1. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Set the current fill color to the supplied RGB values. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current stroke color to the supplied RGB values. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current fill and stroke color to the supplied RGB values. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Format text in the current font and size into the supplied text box according to the requested formatting mode, which must be one of left, right, center, justify or fulljustify. If width and height are 0, only a single line is placed at the point (left, top) in the requested mode. Parameter feature is optional before PHP 4.3.5 or with PDFlib less than 5.
Returns the number of characters that did not fit in the specified box. Returns 0 if all characters fit or the width and height parameters were set to 0 for single-line formatting.
Print text in the current font at ( x, y). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Print text in the current font and size at the current position. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Skew the coordinate system in x and y direction by alpha and beta degrees. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Returns the width of text using the parameters font and size. Please note that font is a font handle returned by pdf_findfont(). Parameters font and size are optional before PHP 4.3.5 or with PDFlib less than 5. If they are not specified, the font set by pdf_setfont() is used.
Nota: Both the font and size parameters must be used together.
See also pdf_setfont() and pdf_findfont().
Stroke the path with the current color and line width, and clear it. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions. Note that you cannot perform any database functions using the PDO extension by itself; you must use a database-specific PDO driver to access a database server.
PDO provides a data-access abstraction layer, which means that, regardless of which database you're using, you use the same functions to issue queries and fetch data. PDO does not provide a database abstraction; it doesn't rewrite SQL or emulate missing features. You should use a full-blown abstraction layer if you need that facility.
PDO ships with PHP 5.1, and is available as a PECL extension for PHP 5.0; PDO requires the new OO features in the core of PHP 5, and so will not run with earlier versions of PHP.
PHP 5.1 and up on Unix systems
If you're running a PHP 5.1 release, PDO is included in the distribution; it will be automatically enabled when you run configure. It is recommended that you build PDO as a shared extension, as this will allow you to take advantage of updates that are made available via PECL. The recommended configure line for building PHP with PDO support should enable zlib support (for the pear installer) as well. You may also need to enable the PDO driver for your database of choice; consult the documentation for database-specific PDO drivers to find out more about that.
./configure --with-zlib --enable-pdo=shared |
After installing PDO as a shared module, you must edit your php.ini file so that the PDO extension will be loaded automatically when PHP runs. You will also need to enable any database specific drivers there too; make sure that they are listed after the pdo.so line, as PDO must be initialized before the database specific extensions can be loaded. If you built the extensions statically, you can skip this step.
extension=pdo.so |
Having PDO as a shared module will allow you to run pear upgrade pdo as new versions of PDO are published, without forcing you to rebuild the whole of PHP. Note that if you do this, you also need to upgrade your database specific PDO drivers at the same time.
PHP 5.0 and up on Unix systems
PDO is available as a PECL extension from http://pecl.php.net/package/pdo. Installation can be performed via the pear tool; this is enabled by default when you configure PHP. You should ensure that PHP was configured --with-zlib in order for pear to be able to handle the compressed package files.
Run the following command to download, build, and install the latest stable version of PDO:
pear install pdo |
If PDO is still in beta (and at the time of writing, it is), you will need to tell the pear tool that it's ok to fetch the beta package. Instead of running the command above, run the following:
pear install pdo-beta |
The pear command automatically installs the PDO module into your PHP extensions directory. To enable the PDO extension on Linux or Unix operating systems, you must add the following line to php.ini:
extension=pdo.so |
For more information about building PECL packages, consult the PECL installation section of the manual.
Windows users running PHP 5.1 and up
PDO and all the major drivers ship with PHP as shared extensions, and simply need to be activated by editing the php.ini file:
extension=php_pdo.dll |
Next, choose the other DB specific DLL files and either use dl() to load them at runtime, or enable them in php.ini below php_pdo.dll. For example:
extension=php_pdo.dll extension=php_pdo_firebird.dll extension=php_pdo_mssql.dll extension=php_pdo_mysql.dll extension=php_pdo_oci.dll extension=php_pdo_oci8.dll extension=php_pdo_odbc.dll extension=php_pdo_pgsql.dll extension=php_pdo_sqlite.dll |
These DLLs should exist in the system's extension_dir.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.
Breve descrizione dei parametri di configurazione.
Defines DSN alias. See PDO::__construct for thorough explanation.
The following drivers currently implement the PDO interface:
Driver name | Supported databases |
---|---|
PDO_DBLIB | FreeTDS / Microsoft SQL Server / Sybase |
PDO_FIREBIRD | Firebird/Interbase 6 |
PDO_MYSQL | MySQL 3.x/4.x |
PDO_OCI | Oracle Call Interface |
PDO_ODBC | ODBC v3 (IBM DB2, unixODBC and win32 ODBC) |
PDO_PGSQL | PostgreSQL |
PDO_SQLITE | SQLite 3 and SQLite 2 |
Connections are established by creating instances of the PDO base class. It doesn't matter which driver you want to use; you always use the PDO class name. The constructor accepts parameters for specifying the database source (known as the DSN) and optionally for the username and password (if any).
If there are any connection errors, a PDOException object will be thrown. You may catch the exception if you want to handle the error condition, or you may opt to leave it for an application global exception handler that you set up via set_exception_handler().
Avvertimento |
If your application does not catch the exception thrown from the PDO constructor, the default action taken by the zend engine is to terminate the script and display a back trace. This back trace will likely reveal the full database connection details, including the username and password. It is your responsibility to catch this exception, either explicitly (via a catch statement) or implicitly via set_exception_handler(). |
Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.
Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.
Nota: If you're using the PDO ODBC driver and your ODBC libraries support ODBC Connection Pooling (unixODBC and Windows are two that do; there may be more), then it's recommended that you don't use persistent PDO connections, and instead leave the connection caching to the ODBC Connection Pooling layer. The ODBC Connection Pool is shared with other modules in the process; if PDO is told to cache the connection, then that connection would never be returned to the ODBC connection pool, resulting in additional connections being created to service those other modules.
Now that you're connected via PDO, you should be able to understand how PDO manages transactions before you start issuing queries. If you've never encountered transactions before, they offer 4 major features: Atomicity, Consistency, Isolation and Durability (ACID). In layman's terms, any work carried out in a transaction, even if it is carried out in stages, is guaranteed to be applied to the database safely, and without interference from other connections, when it is committed. Transactional work can also be automatically undone at your request (provided you haven't already committed it), which makes error handling in your scripts easier.
Transactions are typically implemented by "saving-up" your batch of changes to be applied all at once; this has the nice side effect of drastically improving the efficiency of those updates. In other words, transactions can make your scripts faster and potentially more robust (you still need to use them correctly to reap that benefit).
Unfortunately, not every database supports transactions, so PDO needs to run in what is known as "auto-commit" mode when you first open the connection. Auto-commit mode means that every query that you run has its own implicit transaction, if the database supports it, or no transaction if the database doesn't support transactions. If you need a transaction, you must use the PDO::beginTransaction() method to initiate one. If the underlying driver does not support transactions, a PDOException will be thrown (regardless of your error handling settings: this is always a serious error condition). Once you are in a transaction, you may use PDO::commit() or PDO::rollBack() to finish it, depending on the success of the code you run during the transaction.
When the script ends or when a connection is about to be closed, if you have an outstanding transaction, PDO will automatically roll it back. This is a safety measure to help avoid inconsistency in the cases where the script terminates unexpectedly--if you didn't explicitly commit the transaction, then it is assumed that something went awry, so the rollback is performed for the safety of your data.
Avvertimento |
The automatic rollback only happens if you initiate the transaction via PDO::beginTransaction(). If you manually issue a query that begins a transaction PDO has no way of knowing about it and thus cannot roll it back if something bad happens. |
Esempio 5. Executing a batch in a transaction In the following sample, let's assume that we are creating a set of entries for a new employee, who has been assigned an ID number of 23. In addition to entering the basic data for that person, we also need to record their salary. It's pretty simple to make two separate updates, but by enclosing them within the PDO::beginTransaction() and PDO::commit() calls, we are guaranteeing that no one else will be able to see those changes until they are complete. If something goes wrong, the catch block rolls back all changes made since the transaction was started, and then prints out an error message.
|
You're not limited to making updates in a transaction; you can also issue complex queries to extract data, and possibly use that information to build up more updates and queries; while the transaction is active, you are guaranteed that no one else can make changes while you are in the middle of your work. In truth, this isn't 100% correct, but it is a good-enough introduction, if you've never heard of transactions before.
Many of the more mature databases support the concept of prepared statements. What are they? You can think of them as a kind of compiled template for the SQL that you want to run, that can be customized using variable parameters. Prepared statements offer two major benefits:
The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize it's plan for executing the query. For complex queries this process can take up enough time that it will noticably slow down your application if you need to repeat the same query many times with different parameters. By using a prepared statement you avoid repeating the analyze/compile/optimize cycle. In short, prepared statements use fewer resources and thus run faster.
The parameters to prepared statements don't need to be quoted; the driver handles it for you. If your application exclusively uses prepared statements, you can be sure that no SQL injection will occur. (However, if you're still building up other parts of the query based on untrusted input, you're still at risk).
Prepared statements are so useful that they are the only feature that PDO will emulate for drivers that don't support them. This ensures that you will be able to use the same data access paradigm regardless of the capabilities of the database.
Esempio 6. Repeated inserts using prepared statements This example performs an INSERT query by substituting a name and a value for the named placeholders.
|
Esempio 7. Repeated inserts using prepared statements This example performs an INSERT query by substituting a name and a value for the positional ? placeholders.
|
Esempio 8. Fetching data using prepared statements This example fetches data based on a key value supplied by a form. The user input is automatically quoted, so there is no risk of a SQL injection attack.
|
If the database driver supports it, you may also bind parameters for output as well as input. Output parameters are typically used to retrieve values from stored procedures. Output parameters are slightly more complex to use than input parameters, in that you must know how large a given parameter might be when you bind it. If the value turns out to be larger than the size you suggested, an error is raised.
You may also specify parameters that hold values both input and output; the syntax is similar to output parameters. In this next example, the string 'hello' is passed into the stored procedure, and when it returns, hello is replaced with the return value of the procedure.
Esempio 10. Calling a stored procedure with an input/output parameter
|
PDO offers you a choice of 3 different error handling strategies, to fit your style of application development.
PDO::ERRMODE_SILENT
This is the default mode. PDO will simply set the error code for you to inspect using the PDO::errorCode() and PDO::errorInfo() methods on both the statement and database objects; if the error resulted from a call on a statement object, you would invoke the PDOStatement::errorCode() or PDOStatement::errorInfo() method on that object. If the error resulted from a call on the database object, you would invoke those methods on the database object instead.
PDO::ERRMODE_WARNING
In addition to setting the error code, PDO will emit a traditional E_WARNING message. This setting is useful during debugging/testing, if you just want to see what problems occurred without interrupting the flow of the application.
PDO::ERRMODE_EXCEPTION
In addition to setting the error code, PDO will throw a PDOException and set its properties to reflect the error code and error information. This setting is also useful during debugging, as it will effectively "blow up" the script at the point of the error, very quickly pointing a finger at potential problem areas in your code (remember: transactions are automatically rolled back if the exception causes the script to terminate).
Exception mode is also useful because you can structure your error handling more clearly than with traditional PHP-style warnings, and with less code/nesting than by running in silent mode and explicitly checking the return value of each database call.
See Exceptions for more information about Exceptions in PHP.
PDO standardizes on using SQL-92 SQLSTATE error code strings; individual PDO drivers are responsible for mapping their native codes to the appropriate SQLSTATE codes. The PDO::errorCode() method returns a single SQLSTATE code. If you need more specific information about an error, PDO also offers an PDO::errorInfo() method which returns an array containing the SQLSTATE code, the driver specific error code and driver specific error string.
At some point in your application, you might find that you need to store "large" data in your database. Large typically means "around 4kb or more", although some databases can happily handle up to 32kb before data becomes "large". Large objects can be either textual or binary in nature. PDO allows you to work with this large data type by using the PDO::PARAM_LOB type code in your PDOStatement::bindParam() or PDOStatement::bindColumn() calls. PDO::PARAM_LOB tells PDO to map the data as a stream, so that you can manipulate it using the PHP Streams API.
Esempio 11. Displaying an image from a database This example binds the LOB into the variable named $lob and then sends it to the browser using fpassthru(). Since the LOB is represented as a stream, functions such as fgets(), fread() and stream_get_contents() can be used on it.
|
Esempio 12. Inserting an image into a database This example opens up a file and passes the file handle to PDO to insert it as a LOB. PDO will do its best to get the contents of the file up to the database in the most efficient manner possible.
|
Represents a connection between PHP and a database server.
beginTransaction - begins a transaction
commit - commits a transaction
errorCode - retrieves an error code, if any, from the database
errorInfo - retrieves an array of error information, if any, from the database
exec - issues an SQL statement and returns the number of affected rows
getAttribute - retrieves a database connection attribute
lastInsertId - retrieves the value of the last row that was inserted into a table
prepare - prepares an SQL statement for execution
query - issues an SQL statement and returns a result set
quote - returns a quoted version of a string for use in SQL statements
rollBack - roll back a transaction
setAttribute - sets a database connection attribute
Represents a prepared statement and, after the statement is executed, an associated result set.
bindColumn - binds a PHP variable to an output column in a result set
bindParam - binds a PHP variable to a parameter in the prepared statement
bindValue - binds a value to a parameter in the prepared statement
closeCursor - closes the cursor, allowing the statement to be executed again
columnCount - returns the number of columns in the result set
errorCode - retrieves an error code, if any, from the statement
errorInfo - retrieves an array of error information, if any, from the statement
execute - executes a prepared statement
fetch - fetches a row from a result set
fetchAll - fetches an array containing all of the rows from a result set
fetchColumn - returns the data from a single column in a result set
getAttribute - retrieves a PDOStatement attribute
getColumnMeta - retrieves metadata for a column in the result set
nextRowset - retrieves the next rowset (result set)
rowCount - returns the number of rows that were affected by the execution of an SQL statement
setAttribute - sets a PDOStatement attribute
setFetchMode - sets the fetch mode for a PDOStatement
Represents an error raised by PDO. You should not throw a PDOException from your own code. See Exceptions for more information about Exceptions in PHP.
Esempio 13. The PDOException class
|
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Avvertimento |
PDO uses class constants since PHP 5.1. Prior releases use global constants in the form PDO_PARAM_BOOL. |
Represents a boolean data type.
Represents the SQL NULL data type.
Represents the SQL INTEGER data type.
Represents the SQL CHAR, VARCHAR, or other string data type.
Represents the SQL large object data type.
Represents a recordset type. Not currently supported by any drivers.
Specifies that the parameter is an INOUT parameter for a stored procedure. You must bitwise-OR this value with an explicit PDO::PARAM_* data type.
Specifies that the fetch method shall return each row as an object with variable names that correspond to the column names returned in the result set. PDO::FETCH_LAZY creates the object variable names as they are accessed.
Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO::FETCH_ASSOC returns only a single value per column name.
Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO::FETCH_NAMED returns an array of values per column name.
Specifies that the fetch method shall return each row as an array indexed by column number as returned in the corresponding result set, starting at column 0.
Specifies that the fetch method shall return each row as an array indexed by both column name and number as returned in the corresponding result set, starting at column 0.
Specifies that the fetch method shall return each row as an object with property names that correspond to the column names returned in the result set.
Specifies that the fetch method shall return TRUE and assign the values of the columns in the result set to the PHP variables to which they were bound with the PDOStatement::bindParam() or PDOStatement::bindColumn() methods.
Specifies that the fetch method shall return only a single requested column from the next row in the result set.
Specifies that the fetch method shall return a new instance of the requested class, mapping the columns to named properties in the class.
Specifies that the fetch method shall update an existing instance of the requested class, mapping the columns to named properties in the class.
If this value is FALSE, PDO attempts to disable autocommit so that the connection begins a transaction.
Setting the prefetch size allows you to balance speed against memory usage for your application. Not all database/driver combinations support setting of the prefetch size. A larger prefetch size results in increased performance at the cost of higher memory usage.
Sets the timeout value in seconds for communications with the database.
See the Errors and error handling section for more information about this attribute.
This is a read only attribute; it will return information about the version of the database server to which PDO is connected.
This is a read only attribute; it will return information about the version of the client libraries that the PDO driver is using.
This is a read only attribute; it will return some meta information about the database server to which PDO is connected.
Force column names to a specific case specified by the PDO::CASE_* constants.
Get or set the name to use for a cursor. Most useful when using scrollable cursors and positioned updates.
Selects the cursor type. PDO currently supports either PDO::CURSOR_FWDONLY and PDO::CURSOR_SCROLL. Stick with PDO::CURSOR_FWDONLY unless you know that you need a scrollable cursor.
Returns the name of the driver.
Convert empty strings to SQL NULL values on data fetches.
Request a persistent connection, rather than creating a new connection. See Connections and Connection management for more information on this attribute.
Prepend the containing catalog name to each column name returned in the result set. The catalog name and column name are separated by a decimal (.) character. Support of this attribute is at the driver level; it may not be supported by your driver.
Prepend the containing table name to each column name returned in the result set. The table name and column name are separated by a decimal (.) character. Support of this attribute is at the driver level; it may not be supported by your driver.
Do not raise an error or exception if an error occurs. The developer is expected to explicitly check for errors. This is the default mode. See Errors and error handling for more information about this attribute.
Issue a PHP E_WARNING message if an error occurs. See Errors and error handling for more information about this attribute.
Throw a PDOException if an error occurs. See Errors and error handling for more information about this attribute.
Leave column names as returned by the database driver.
Force column names to lower case.
Force column names to upper case.
Fetch the next row in the result set. Valid only for scrollable cursors.
Fetch the previous row in the result set. Valid only for scrollable cursors.
Fetch the first row in the result set. Valid only for scrollable cursors.
Fetch the last row in the result set. Valid only for scrollable cursors.
Fetch the requested row by row number from the result set. Valid only for scrollable cursors.
Fetch the requested row by relative position from the current position of the cursor in the result set. Valid only for scrollable cursors.
Create a PDOStatement object with a forward-only cursor. This is the default cursor choice, as it is the fastest and most common data access pattern in PHP.
Create a PDOStatement object with a scrollable cursor. Pass the PDO::FETCH_ORI_* constants to control the rows fetched from the result set.
Corresponds to SQLSTATE '00000', meaning that the SQL statement was successfully issued with no errors or warnings. This constant is for your convenience when checking PDO::errorCode() or PDOStatement::errorCode() to determine if an error occurred. You will usually know if this is the case by examining the return code from the method that raised the error condition anyway.
Turns off autocommit mode. While autocommit mode is turned off, changes made to the database via the PDO object instance are not committed until you end the transaction by calling PDO::commit(). Calling PDO::rollback() will roll back all changes to the database and return the connection to autocommit mode.
Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.
Esempio 1. Roll back a transaction The following example begins a transaction and issues two statements that modify the database before rolling back the changes. On MySQL, however, the DROP TABLE statement automatically commits the transaction so that none of the changes in the transaction are rolled back.
|
Commits a transaction, returning the database connection to autocommit mode until the next call to PDO::beginTransaction() starts a new transaction.
(no version information, might be only in CVS)
PDO::__construct -- Creates a PDO instance representing a connection to a databaseCreates a PDO instance to represent a connection to the requested database.
The Data Source Name, or DSN, contains the information required to connect to the database.
In general, a DSN consists of the PDO driver name, followed by a colon, followed by the PDO driver-specific connection syntax. Further information is available from the PDO driver-specific documentation.
The dsn parameter supports three different methods of specifying the arguments required to create a database connection:
dsn contains the full DSN.
dsn consists of uri: followed by a URI that defines the location of a file containing the DSN string. The URI can specify a local file or a remote URL.
uri:file:///path/to/dsnfile
dsn consists of a name name that maps to pdo.dsn.name in php.ini defining the DSN string.
Nota: The alias must be defined in php.ini, and not .htaccess or httpd.conf
The user name for the DSN string. This parameter is optional for some PDO drivers.
The password for the DSN string. This parameter is optional for some PDO drivers.
A key=>value array of driver-specific connection options.
PDO::construct() throws a PDOException if the attempt to connect to the requested database fails.
Esempio 1. Create a PDO instance via driver invocation
|
Esempio 2. Create a PDO instance via URI invocation The following example assumes that the file /usr/local/dbconnect exists with file permissions that enable PHP to read the file. The file contains the PDO DSN to connect to a DB2 database through the PDO_ODBC driver:
The PHP script can then create a database connection by simply passing the uri: parameter and pointing to the file URI:
|
Esempio 3. Create a PDO instance using an alias The following example assumes that php.ini contains the following entry to enable a connection to a MySQL database using only the alias mydb:
|
(no version information, might be only in CVS)
PDO::errorCode -- Fetch the SQLSTATE associated with the last operation on the database handleReturns a SQLSTATE, a five-character alphanumeric identifier defined in the ANSI SQL-92 standard. Briefly, an SQLSTATE consists of a two-character class value followed by a three-character subclass value. A class value of 01 indicates a warning and is accompanied by a return code of SQL_SUCCESS_WITH_INFO. Class values other than '01', except for the class 'IM', indicate an error. The class 'IM' is specific to warnings and errors that derive from the implementation of PDO (or perhaps ODBC, if you're using the ODBC driver) itself. The subclass value '000' in any class indicates that there is no subclass for that SQLSTATE.
PDO::errorCode() only retrieves error codes for operations performed directly on the database handle. If you create a PDOStatement object through PDO::prepare() or PDO::query() and invoke an error on the statement handle, PDO::errorCode() will not reflect that error. You must call PDOStatement::errorCode() to return the error code for an operation performed on a particular statement handle.
(no version information, might be only in CVS)
PDO::errorInfo -- Fetch extended error information associated with the last operation on the database handlePDO::errorInfo() returns an array of error information about the last operation performed by this database handle. The array consists of the following fields:
Element | Information |
---|---|
0 | SQLSTATE error code (a five-character alphanumeric identifier defined in the ANSI SQL standard). |
1 | Driver-specific error code. |
2 | Driver-specific error message. |
PDO::errorInfo() only retrieves error information for operations performed directly on the database handle. If you create a PDOStatement object through PDO::prepare() or PDO::query() and invoke an error on the statement handle, PDO::errorInfo() will not reflect the error from the statement handle. You must call PDOStatement::errorInfo() to return the error information for an operation performed on a particular statement handle.
Esempio 1. Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
PDO::exec -- Execute an SQL statement and return the number of affected rowsPDO::exec() executes an SQL statement in a single function call, returning the number of rows affected by the statement.
PDO::exec() does not return results from a SELECT statement. For a SELECT statement that you only need to issue once during your program, consider issuing PDO::query(). For a statement that you need to issue multiple times, prepare a PDOStatement object with PDO::prepare() and issue the statement with PDOStatement::execute().
PDO::exec() returns the number of rows that were modified or deleted by the SQL statement you issued. If no rows were affected, PDO::exec() returns 0.
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
The following example incorrectly relies on the return value of PDO::exec(), wherein a statement that affected 0 rows results in a call to die():
<?php $db->exec() or die($db->errorInfo()); ?> |
Esempio 1. Issuing a DELETE statement Count the number of rows deleted by a DELETE statement with no WHERE clause.
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
PDO::getAttribute -- Retrieve a database connection attributeThis function returns the value of a database connection attribute. To retrieve PDOStatement attributes, refer to PDOStatement::getAttribute().
Note that some database/driver combinations may not support all of the database connection attributes.
One of the PDO::ATTR_* constants. The constants that apply to database connections are as follows:
PDO::ATTR_AUTOCOMMIT |
PDO::ATTR_CASE |
PDO::ATTR_CLIENT_VERSION |
PDO::ATTR_CONNECTION_STATUS |
PDO::ATTR_DRIVER_NAME |
PDO::ATTR_ERRMODE |
PDO::ATTR_ORACLE_NULLS |
PDO::ATTR_PERSISTENT |
PDO::ATTR_PREFETCH |
PDO::ATTR_SERVER_INFO |
PDO::ATTR_SERVER_VERSION |
PDO::ATTR_TIMEOUT |
A successful call returns the value of the requested PDO attribute. An unsuccessful call returns null.
Esempio 1. Retrieving database connection attributes
|
(no version information, might be only in CVS)
PDO::getAvailableDrivers -- Return an array of available PDO driversThis function returns all currently available PDO drivers which can be used in DSN parameter of PDO::__construct(). This is a static method.
PDO::getAvailableDrivers() returns an array of PDO driver names. If no drivers are available, it returns an empty array.
(no version information, might be only in CVS)
PDO::lastInsertId -- Returns the ID of the last inserted row or sequence valueReturns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver.
Nota: This method may not return a meaningful/consistent result across different PDO drivers, because the underlying database may not even support the notion of auto-increment fields or sequences.
If a sequence name was not specified for the name parameter, PDOStatement::lastInsertId() returns a string representing the row ID of the last row that was inserted into the database.
If a sequence name was specified for the name parameter, PDOStatement::lastInsertId() returns a string representing the last value retrieved from the specified sequence object.
If the PDO driver does not support this capability, PDO::lastInsertID() triggers an IM001 SQLSTATE.
(no version information, might be only in CVS)
PDO::prepare -- Prepares a statement for execution and returns a statement objectPrepares an SQL statement to be executed by the PDOStatement::execute() method. The SQL statement can contain zero or more named (:name) or question mark (?) parameter markers for which real values will be substituted when the statement is executed. You cannot use both named and question mark parameter markers within the same SQL statement; pick one or the other parameter style.
Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.
PDO will emulate prepared statements/bound parameters for drivers that do not natively support them, and can also rewrite named or question mark style parameter markers to something more appropriate, if the driver supports one style but not the other.
This must be a valid SQL statement for the target database server.
This array holds one or more key=>value pairs to set attribute values for the PDOStatement object that this method returns. You would most commonly use this to set the PDO::ATTR_CURSOR value to PDO::CURSOR_SCROLL to request a scrollable cursor. Some drivers have driver specific options that may be set at prepare-time.
If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object.
Esempio 1. Prepare an SQL statement with named parameters
|
Esempio 2. Prepare an SQL statement with question mark parameters
|
(no version information, might be only in CVS)
PDO::query -- Executes an SQL statement, returning a result set as a PDOStatement objectPDO::query() executes an SQL statement in a single function call, returning the result set (if any) returned by the statement as a PDOStatement object.
For a query that you need to issue multiple times, you will realize better performance if you prepare a PDOStatement object using PDO::prepare() and issue the statement with multiple calls to PDOStatement::execute().
Esempio 1. Demonstrate PDO::query A nice feature of PDO::query() is that it enables you to iterate over the rowset returned by a successfully executed SELECT statement.
Il precedente esempio visualizzerà:
|
PDO::quote() places quotes around the input string and escapes and single quotes within the input string, using a quoting style appropriate to the underlying driver.
If you are using this function to build SQL statements, you are strongly recommended to use PDO::prepare() to prepare SQL statements with bound parameters instead of using PDO::quote() to interpolate user input into a SQL statement. Prepared statements with bound parameters are not only more portable, more convenient, and vastly more secure, but are often much faster than interpolating user input into slight variations on the same basic SQL statement.
Not all PDO drivers implement this method (notably PDO_ODBC). Consider using prepared statements instead.
The string to be quoted.
Provides a data type hint for drivers that have alternate quoting styles. The default value is PDO_PARAM_STR.
Returns a quoted string that is theoretically safe to pass into an SQL statement. Returns FALSE if the driver does not support quoting in this way.
Esempio 2. Quoting a dangerous string
Il precedente esempio visualizzerà:
|
Esempio 3. Quoting a complex string
Il precedente esempio visualizzerà:
|
Rolls back the current transaction, as initiated by PDO::beginTransaction(). It is an error to call this method if no transaction is active.
If the database was set to autocommit mode, this function will restore autocommit mode after it has rolled back the transaction.
Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.
Esempio 1. Roll back a transaction The following example begins a transaction and issues two statements that modify the database before rolling back the changes. On MySQL, however, the DROP TABLE statement automatically commits the transaction so that none of the changes in the transaction are rolled back.
|
Sets an attribute on the database handle. Some of the available generic attributes are listed below; some drivers may make use of additional driver specific attributes.
PDO::ATTR_CASE: Force column names to a specific case.
PDO::CASE_LOWER: Force column names to lower case.
PDO::CASE_NATURAL: Leave column names as returned by the database driver.
PDO::CASE_UPPER: Force column names to upper case.
(no version information, might be only in CVS)
PDOStatement::bindColumn -- Bind a column to a PHP variablePDOStatement::bindColumn() arranges to have a particular variable bound to a given column in the result-set from a query. Each call to PDOStatement::fetch() or PDOStatement::fetchAll() will update all the variables that are bound to columns.
Nota: Since information about the columns is not always available to PDO until the statement is executed, portable applications should call this function after PDO::execute().
Number of the column (1-indexed) or name of the column in the result set. If using the column name, be aware that the name should match the case of the column, as returned by the driver.
Name of the PHP variable to which the column will be bound.
Data type of the parameter, specified by the PDO::PARAM_* constants.
Esempio 1. Binding result set output to PHP variables Binding columns in the result set to PHP variables is an effective way to make the data contained in each row immediately available to your application. The following example demonstrates how PDO allows you to bind and retrieve columns with a variety of options and with intelligent defaults.
Il precedente esempio visualizzerà:
|
PDOStatement::execute() |
PDOStatement::fetch() |
PDOStatement::fetchAll() |
PDOStatement::fetchColumn() |
(no version information, might be only in CVS)
PDOStatement::bindParam -- Binds a parameter to the specified variable nameBinds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was use to prepare the statement. Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.
Most parameters are input parameters, that is, parameters that are used in a read-only fashion to build up the query. Some drivers support the invocation of stored procedures that return data as output parameters, and some also as input/output parameters that both send in data and are updated to receive it.
Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.
Name of the PHP variable to bind to the SQL statement parameter.
Explicit data type for the parameter using the PDO::PARAM_* constants. To return an INOUT parameter from a stored procedure, use the bitwise OR operator to set the PDO::PARAM_INPUT_OUTPUT bits for the data_type parameter.
Length of the data type. To indicate that a parameter is an OUT parameter from a stored procedure, you must explicitly set the length.
Esempio 1. Execute a prepared statement with named placeholders
|
Esempio 2. Execute a prepared statement with question mark placeholders
|
Esempio 3. Call a stored procedure with an INOUT parameter
|
(no version information, might be only in CVS)
PDOStatement::bindValue -- Binds a value to a parameterBinds a value to a corresponding named or question mark placeholder in the SQL statement that was use to prepare the statement.
Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.
The value to bind to the parameter.
Explicit data type for the parameter using the PDO::PARAM_* constants.
Esempio 1. Execute a prepared statement with named placeholders
|
Esempio 2. Execute a prepared statement with question mark placeholders
|
(no version information, might be only in CVS)
PDOStatement::closeCursor -- Closes the cursor, enabling the statement to be executed again.PDOStatement::closeCursor() frees up the connection to the server so that other SQL statements may be issued, but leaves the statement in a state that enables it to be executed again.
This method is useful for database drivers that do not support executing a PDOStatement object when a previously executed PDOStatement object still has unfetched rows. If your database driver suffers from this limitation, the problem may manifest itself in an out-of-sequence error.
PDOStatement::closeCursor() is implemented either as an optional driver specific method (allowing for maximum efficiency), or as the generic PDO fallback if no driver specific function is installed. The PDO generic fallback is semantically the same as writing the following code in your PHP script:
<?php do { while ($stmt->fetch()) ; if (!$stmt->nextRowset()) break; } while (true); ?> |
Esempio 1. A PDOStatement::closeCursor() example In the following example, the $stmt PDOStatement object returns multiple rows but the application fetches only the first row, leaving the PDOStatement object in a state of having unfetched rows. To ensure that the application will work with all database drivers, the author inserts a call to PDOStatement::closeCursor() on $stmt before executing the $otherStmt PDOStatement object.
|
(no version information, might be only in CVS)
PDOStatement::columnCount -- Returns the number of columns in the result setUse PDOStatement::columnCount() to return the number of columns in the result set represented by the PDOStatement object.
If the PDOStatement object was returned from PDO::query(), the column count is immediately available.
If the PDOStatement object was returned from PDO::prepare(), an accurate column count will not be available until you invoke PDOStatement::execute().
Returns the number of columns in the result set represented by the PDOStatement object. If there is no result set, PDOStatement::columnCount() returns 0.
Esempio 1. Counting columns This example demonstrates how PDOStatement::columnCount() operates with and without a result set.
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
PDOStatement::errorCode -- Fetch the SQLSTATE associated with the last operation on the statement handleIdentical to PDO::errorCode(), except that PDOStatement::errorCode() only retrieves error codes for operations performed with PDOStatement objects.
(no version information, might be only in CVS)
PDOStatement::errorInfo -- Fetch extended error information associated with the last operation on the statement handlePDOStatement::errorInfo() returns an array of error information about the last operation performed by this statement handle. The array consists of the following fields:
Esempio 1. Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
PDOStatement::execute -- Executes a prepared statementExecute the prepared statement. If the prepared statement included parameter markers, you must either:
call PDOStatement::bindParam() to bind PHP variables to the parameter markers: bound variables pass their value as input and receive the output value, if any, of their associated parameter markers
or pass an array of input-only parameter values
Esempio 1. Execute a prepared statement with bound variables
|
Esempio 2. Execute a prepared statement with an array of insert values
|
Esempio 3. Execute a prepared statement with question mark placeholders
|
PDO::prepare() |
PDOStatement::bindParam() |
PDOStatement::fetch() |
PDOStatement::fetchAll() |
PDOStatement::fetchColumn() |
(no version information, might be only in CVS)
PDOStatement::fetch -- Fetches the next row from a result setFetches a row from a result set associated with a PDOStatement object.
Controls how the next row will be returned to the caller. This value must be one of the PDO::FETCH_* constants, defaulting to PDO::FETCH_BOTH.
PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set
PDO::FETCH_BOTH (default): returns an array indexed by both column name and column number as returned in your result set
PDO::FETCH_BOUND: returns TRUE and assigns the values of the columns in your result set to the PHP variables to which they were bound with the PDOStatement::bindParam() method
PDO::FETCH_LAZY: combines PDO::FETCH_BOTH and PDO::FETCH_OBJ, creating the object variable names as they are accessed
PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names returned in your result set
PDO::FETCH_NUM: returns an array indexed by column number as returned in your result set, starting at column 0
For a PDOStatement object representing a scrollable cursor, this value determines which row will be returned to the caller. This value must be one of the PDO::FETCH_ORI_* constants, defaulting to PDO::FETCH_ORI_NEXT.
For a PDOStatement object representing a scrollable cursor for which the cursor_orientation parameter is set to PDO::FETCH_ORI_ABS, this value specifies the absolute number of the row in the result set that shall be fetched.
For a PDOStatement object representing a scrollable cursor for which the cursor_orientation parameter is set to PDO::FETCH_ORI_REL, this value specifies the row to fetch relative to the cursor position before PDOStatement::fetch() was called.
Esempio 1. Fetching rows using different fetch styles
Il precedente esempio visualizzerà:
|
Esempio 2. Fetching rows with a scrollable cursor
Il precedente esempio visualizzerà:
|
PDO::query() |
PDOStatement::fetchAll() |
PDOStatement::fetchColumn() |
PDOStatement::prepare() |
PDOStatement::setFetchMode() |
(no version information, might be only in CVS)
PDOStatement::fetchAll -- Returns an array containing all of the result set rows
Controls the contents of the returned array as documented in PDOStatement::fetch(). Defaults to PDO::FETCH_BOTH.
To return an array consisting of all values of a single column from the result set, specify PDO::FETCH_COLUMN.
To fetch only the unique values of a single column from the result set, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_UNIQUE.
To return an associative array grouped by the values of a specified column, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_GROUP.
Returns the indicated 0-indexed column when the value of fetch_style is PDO::FETCH_COLUMN. Defaults to 0.
PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name.
Using this method to fetch large result sets will result in a heavy demand on system and possibly network resources. Rather than retrieving all of the data and manipulating it in PHP, consider using the database server to manipulate the result sets. For example, use the WHERE and SORT BY clauses in SQL to restrict results before retrieving and processing them with PHP.
Esempio 1. Fetch all remaining rows in a result set
Il precedente esempio visualizzerà:
|
Esempio 2. Fetching all values of a single column from a result set The following example demonstrates how to return all of the values of a single column from a result set, even though the SQL statement itself may return multiple columns per row.
Il precedente esempio visualizzerà:
|
Esempio 3. Grouping all values by a single column The following example demonstrates how to return an associative array grouped by the values of the specified column in the result set. The array contains three keys: values apple and pear are returned as arrays that contain two different colours, while watermelon is returned as an array that contains only one colour.
Il precedente esempio visualizzerà:
|
PDO::query() |
PDOStatement::fetch() |
PDOStatement::fetchColumn() |
PDOStatement::prepare() |
PDOStatement::setFetchMode() |
(no version information, might be only in CVS)
PDOStatement::fetchColumn -- Returns a single column from the next row of a result setReturns a single column from the next row of a result set.
Number of the column you wish to retrieve from the row. If no value is supplied, PDOStatement::fetchColumn() fetches the first column.
PDOStatement::fetchColumn() returns a single column in the next row of a result set.
Avvertimento |
There is no way to return another column from the same row if you use PDOStatement::fetchColumn() to retrieve data. |
Esempio 1. Return first column of the next row
Il precedente esempio visualizzerà:
|
PDO::query() |
PDOStatement::fetch() |
PDOStatement::fetchAll() |
PDOStatement::prepare() |
PDOStatement::setFetchMode() |
(no version information, might be only in CVS)
PDOStatement::getAttribute -- Retrieve a statement attributeAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
PDOStatement::getColumnMeta -- Returns metadata for a column in a result setAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Retrieves the metadata for a 0-indexed column in a result set as an associative array.
Avvertimento |
Not all PDO drivers support PDOStatement::getColumnMeta(). |
Returns an associative array containing the following values representing the metadata for a single column:
Tabella 1. Column metadata
Name | Value |
---|---|
native_type | The PHP native type used to represent the column value. |
driver:decl_type | The SQL type used to represent the column value in the database. If the column in the result set is the result of a function, this value is not returned by PDOStatement::getColumnMeta(). |
flags | Any flags set for this column. |
name | The name of this column as returned by the database. |
len | The length of this column. Normally -1 for types other than floating point decimals. |
precision | The numeric precision of this column. Normally 0 for types other than floating point decimals. |
pdo_type | The type of this column as represented by the PDO::PARAM_* constants. |
Returns FALSE if the requested column does not exist in the result set, or if no result set exists.
Esempio 1. Retrieving column metadata The following example shows the results of retrieving the metadata for a single column generated by a function (COUNT) in a PDO_SQLITE driver.
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
PDOStatement::nextRowset -- Advances to the next rowset in a multi-rowset statement handleSome database servers support stored procedures that return more than one rowset (also known as a result set). PDOStatement::nextRowSet() enables you to access the second and subsequent rowsets associated with a PDOStatement object. Each rowset can have a different set of columns from the preceding rowset.
Esempio 1. Fetching multiple rowsets returned from a stored procedure The following example shows how to call a stored procedure, MULTIPLE_RESULTS, that returns three rowsets. We use a do / while loop to loop over the PDOStatement::nextRowset() method, which returns false and terminates the loop when no more rowsets can be returned.
Il precedente esempio visualizzerà:
|
PDOStatement::columnCount() |
PDOStatement::execute() |
PDOStatement::getColumnMeta() |
PDOStatement::query() |
(no version information, might be only in CVS)
PDOStatement::rowCount -- Returns the number of rows affected by the last SQL statementPDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
Esempio 1. Return the number of deleted rows PDOStatement::rowCount() returns the number of rows affected by a DELETE, INSERT, or UPDATE statement.
Il precedente esempio visualizzerà:
|
Esempio 2. Counting rows returned by a SELECT statement For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
PDOStatement::setAttribute -- Set a statement attributeAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
PDOStatement::setFetchMode -- Set the default fetch mode for this statement
Esempio 1. Setting the fetch mode The following example demonstrates how PDOStatement::setFetchMode() changes the default fetch mode for a PDOStatement object.
Il precedente esempio visualizzerà:
|
Queste funzioni permettono di accedere a diverse informazioni sul PHP stesso, come la configurazione di runtime, il moduli caricati, la versione e molto altro. Si troveranno anche funzioni per impostare le opzioni di runtime del PHP. Probabilmente la più nota tra queste è - phpinfo() -.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Parametri di configurazione per PHP Opzioni/informazioni
Nome | Default | Modificabile |
---|---|---|
assert.active | "1" | PHP_INI_ALL |
assert.bail | "0" | PHP_INI_ALL |
assert.warning | "1" | PHP_INI_ALL |
assert.callback | NULL | PHP_INI_ALL |
assert.quiet_eval | "0" | PHP_INI_ALL |
enable_dl | "1" | PHP_INI_SYSTEM |
max_execution_time | "30" | PHP_INI_ALL |
max_input_time | "60" | PHP_INI_ALL |
magic_quotes_gpc | "1" | PHP_INI_PERDIR|PHP_INI_SYSTEM |
magic_quotes_runtime | "0" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
Abilita l'analisi degli assert().
Termina uno script a fronte di un assert fallito.
Invia un PHP warning per ogni asserzione fallita.
Funzione utente da richiamare a fronte di un assert fallito
Utilizzare questo parametro di error_reporting() durante l'analisi dei un'asserzione. Se è abilitato, non sono visualizzati gli errori (error_reporting(0)) durante il parsing di una asserzione. Se disabilitato, gli errori saranno visualizzati in base all'impostazione di error_reporting().
Questa direttiva è utile soltanto nella versione di PHP attiva come modulo di Apache. Essa permette di caricare in modo dinamico le estensioni di PHP potendo impostare dl() on oppure off in base al server virtuale o per directory.
La ragione principale per disabilitare il caricamento dinamico dei moduli è la sicurezza. Con il caricamento dinamico è possibile ignorare tutte le restrizioni open_basedir. Per default il caricamento dinamico è attivo tranne quando si utilizza il modalità sicura. In modalità sicura, è sempre impossibile utilizzare dl().
Questo parametro imposta il tempo massimo in secondi concessi ad uno script per l'esecuzione prima di essere interrotto dal parser. Questo aiuta a prevenire che script scritti male blocchino il server. Per default è impostato a 30.
Il tempo massimo di esecuzione non è condizionato dalle chiamate di sistema, dalle operazioni sugli stream, eccetera. Vedere la funzione set_time_limit() per maggiori dettagli.
Non si può cambiare questo parametro con ini_set() quando il PHP gira in modalità sicura. L'unico modo è di disabilitare il safe mode oppure di cambiare il limite di tempo nel php.ini.
Anche il server web ha i propri timeout. Ad esempio Apache ha un proprio parametro Timeout, IIS ha una funzione di timeout sugli script CGI, entrambi con default 300 secondi. Vedere la documentazione del server web per maggiori dettagli.
Impostail tempo massimo in secondi concesso ad uno script per ricevere i dati di input, tipo POST, GET e upload di file. Il valore di default è 60.
Imposta il parametro magic_quote per GPC (Get/Post/Cookie). Quando magic_quote è impostato a on, tutti i ' (apici singoli), " (doppi apici), \ (backslash) e NUL sono vengono preceduti in automatico dal backslash.
Nota: Se il parametro magic_quotes_sybase è impostato a ON, questo è prioritario rispetto a magic_quotes_gpc. Avere entrambi i parametri attivi significa che soltanto gli apici singoli sono preceduti dal carattere di escape come ''. Doppi apici, backslash, e NUL non vengono toccati.
Vedere anche get_magic_quotes_gpc()
Se si abilita magic_quotes_runtime, diverse funzioni che restituiscono dati da ogni tipo di fonte esterna, compresi i database ed i file di testo, avranno gli apici preceduti dal backslash. Se è anche attivato magic_quotes_sybase, soltanto l'apice singolo sarà preceduto dal carattere di escape costituito da un apice singolo anzichè il backslash.
Le costanti qui elencate sono sempre disponibili in quanto parte del core di PHP.
Tabella 2. Costanti predefinite per phpcredits()
Costante | Valore | Descrizione |
---|---|---|
CREDITS_GROUP | 1 | Lista degli sviluppatori principali |
CREDITS_GENERAL | 2 | Lista generale: design e progetto del linguaggio, autori del PHP e del modulo SAPI. |
CREDITS_SAPI | 4 | Lista delle API server e dei loro sviluppatori. |
CREDITS_MODULES | 8 | Lista dei moduli e dei loro sviluppatori. |
CREDITS_DOCS | 16 | La lista del gruppo di documentazione. |
CREDITS_FULLPAGE | 32 | Solitamente utilizzato in combinazione con altri flag. Indica che la pagina completa HTML deve essere stampata includendo le infomazioni di altri flag. |
CREDITS_QA | 64 | Elenca i riconoscimenti per il gruppo della qualità. |
CREDITS_ALL | -1 | Tutta la lista dei meriti, equivale a CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_FULLPAGE. Genera una pagina HTML completa. Questa è l'impostazione di default. |
Tabella 3. Costanti di phpinfo()
Costante | Valore | Descrizione |
---|---|---|
INFO_GENERAL | 1 | La linea di configurazione, php.ini luogo, data di compila, Web Server, sistema e altro. |
INFO_CREDITS | 2 | PHP Credits. Vedere anche phpcredits(). |
INFO_CONFIGURATION | 4 | Impostazioni correnti e di base delle opzioni PHP. Vedere anche ini_get(). |
INFO_MODULES | 8 | Moduli caricati e le loro impostazioni. |
INFO_ENVIRONMENT | 16 | Variabili d'ambiente disponibili in $_ENV. |
INFO_VARIABLES | 32 | Visualizza tutte le variabili predefinite da EGPCS (Environment, GET, POST, Cookie, Server). |
INFO_LICENSE | 64 | Informazioni sulla licenza di PHP. Vedere anche faq sulla licenza. |
INFO_ALL | -1 | Visualizza tutto quanto descritto. Questo è il valore dei default. |
Usando assert_options() si è in grado di impostare vari parametri di controllo per la funzione assert(), oppure ottenerne l'impostazione corrente.
Tabella 1. Opzioni di assert
opzione | parametro ini | default | descrizione |
---|---|---|---|
ASSERT_ACTIVE | assert.active | 1 | abilita l'assert() |
ASSERT_WARNING | assert.warning | 1 | indica a PHP i generare un warning per ogni asserzione fallita |
ASSERT_BAIL | assert.bail | 0 | termina l'esecuzione alla prima asserzione fallita |
ASSERT_QUIET_EVAL | assert.quiet_eval | 0 | disabilita la gestione degli errori nelle espressioni di asserzione |
ASSERT_CALLBACK | assert.callback | (NULL) | funzione utente da richiamare per le asserzioni fallite |
assert_options() restituirà l'impostazione originale di ogni opzione, oppure FALSE se fallisce.
assert() verifica se la data assertion è FALSE, nel caso intraprende le opportune azioni.
Se il parametro assertion è una stringa questo sarà considerato da assert() come codice PHP. I vantaggi di usare le stringhe con assertion sono che si ha meno overhead nella verifica e la visualizzazione dei messaggi che contengono assertion quando questa fallisce. Ciò significa che se si passa una condizione booleana come assertion, questa condizione non sarà mostrata come parametro della funzione che può essere definita con assert_options(), la condizione sarò in stringa prima di chiamare la funzione handler, e il valore booleano FALSE viene convertito in una stringa vuota.
Le asserzioni dovrebbero essere utilizzate solo per il debug. Si possono usare per controlli di coerenza che sono sempre TRUE e che, in caso contrario, indichino errori di programmazione, oppure per verificare la presenza o meni di certe caratteristiche, tipo le estensioni, oppure certi limiti di sistema o caratteristiche.
Le asserzioni non dovrebbero essere utilizzate per le normali operazioni di runtime quali il controllo dei parametri di input. Come regola si deve avere che il programma possa girare senza la presenza delle regole di asserzione.
Il comportamento di assert() può essere impostato tramite assert_options() oppure tramite .ini-settings come descritto nel pagine del manuale relative a quelle funzioni.
La funzione assert_options() e/o il parametro ASSERT_CALLBACK permetto di attivare una funzione di callback per gestire una asserzione fallita.
I callback di assert() sono particolarmente utili per costruire suite di test poiché permettono di catturare facilmente il codice passato all'assert, oltre alle informazioni su dove l'assert è scattato. Sebbene quest'ultime informazioni siano rilevabili anche con altri metodi, l'uso delle asserzione rende il tutto più semplice!
Le funzioni di callback devono accettare tre parametri. Il primo conterrà il nome del file in cui si trova l'asserzione fallita. Il secondo parametro conterrà il numero di linea dell'asserzione fallita, ed il terzo conterrà l'espressione dell'asserzione (se fornito - valori alfanumerici quali 1 o due" non saranno passati a questo parametro).
Esempio 1. Gestione di una asserzione fallita con codice personalizzato
|
La funzione carica il modulo di PHP passato nel parametro library. Il parametro library indica soltanto il nome del file del modulo da caricare il quale può dipendere dal piattaforma utilizzata. Ad esempio il modulo sockets (se compilato come modulo condiviso, non è il default!) sulle piattaforme Unix si chiama sockets.so, mentre in Windows si chiama php_sockets.dll.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. Se la funzionalità di carico dei moduli non è disponibile (vedi note), oppure è stata disabilitata (sia disabilitando enable_dl oppure attivando modalità sicura nel php.ini), sarà generato un E_ERROR e sarà bloccata l'esecuzione dello script. Se dl() fallisce perché non riesce a caricare la libreria indicata, oltre a restituire FALSE verrà generato un messaggio di tipo E_WARNING.
Si può utilizzare extension_loaded() per testare se un modulo è veramente affidabile o meno. Questa funzione si applica sia a moduli built-in sia ai moduli caricati (tramite php.ini oppure dl()).
La funzione dl() è deprecata dal PHP 5. Piuttosto utilizzare Parametri per il carico dei moduli.
Esempio 1. Esempio di uso di dl()
|
La directory da cui vengono caricate le estensioni dipende dal sistema operativo della macchina:
Windows - Se non viene impostato esplicitamente nel php.ini, i moduli sono caricati da c:\php4\extensions\ .
Unix - Se non viene impostato esplicitamente nel php.ini, la directory di default dipenda da
se il PHP è stato compilato con --enable-debug o meno
se il PHP è stato compilato con (versione sperimentale) ZTS (Zend Thread Safety) o meno
il valore attuale di ZEND_MODULE_API_NO (numero interno del modulo API Zend, il quale indica la data in cui si sono apportate le maggiori modifiche al modulo, ad esempio 20010901)
Nota: La funzione dl() non è supportata dai web server multithread. Utilizzare il parametro del php.ini extensions quando si debba utilizzare tali server. Mentre le versioni CGI e CLI non hanno questa limitazione.
Nota: La dl() è sensibile alla maiuscole sulle piattaforme Unix.
Nota: Questa funzione è disabilitata nella modalitàsafe-mode
Vedere anche Direttive per il carimaneto dei moduli e extension_loaded().
Restituisce TRUE se il modulo specificato da name è caricato, oppure FALSE.
Si può verificare il nome dei vari moduli caricati tramite phpinfo(), o, se si sta utilizzando le versioni CGI o CLI di PHP, si può utilizzare l'opzione -m:
$ php -m [PHP Modules] xml tokenizer standard sockets session posix pcre overload mysql mbstring ctype [Zend Modules] |
Nota: La funzione extension_loaded() utilizza i nomi interni dei moduli per verificare se tale modulo è disponibile o meno. La maggior parte dei nomi interni sono scritti in minuscolo, ma possono esserci moduli con nomi contenenti lettere maiuscole. Fare attenzione che questa funzione distingue tra lettere minuscole e maiuscole
Vedere anche get_loaded_extensions(), get_extension_funcs(), phpinfo() e dl().
Restituisce il valore corrente della variabile di configurazione indicata da varname, oppure FALSE se si verifica un errore.
La funzione non restituisce informazioni di configurazione nel caso in cui il PHP è compilato, o caricato da un file di configurazione di Apache (tramite le direttive php3_configuration_option).
Per verificare se il sistema utilizza un file di configurazione, tentare di ricavare il valore di cfg_file_path. Se è disponibile significa che si utilizza un file di configurazione.
Vedere anche ini_get().
Restituisce il nome del proprietario dello script PHP.
Vedere anche getmyuid(), getmygid(), getmypid(), getmyinode() e getlastmod().
(PHP 4 >= 4.1.0, PHP 5)
get_defined_constants -- Restituisve un array associativo con i nomi di tutte le costanti ed i loro valoriQuesta funzione restituisce i nomi ed i valori di tutte le costanti attualmente definite. Queste includono sia quelle create dalle estensioni sia quelle create con la funzione define().
Ad esempio la linea seguente:
<?php print_r(get_defined_constants()); ?> |
visualizzerà il seguente elenco:
Array ( [E_ERROR] => 1 [E_WARNING] => 2 [E_PARSE] => 4 [E_NOTICE] => 8 [E_CORE_ERROR] => 16 [E_CORE_WARNING] => 32 [E_COMPILE_ERROR] => 64 [E_COMPILE_WARNING] => 128 [E_USER_ERROR] => 256 [E_USER_WARNING] => 512 [E_USER_NOTICE] => 1024 [E_ALL] => 2047 [TRUE] => 1 ) |
Vedere anche: defined(), get_loaded_extensions(), get_defined_functions() e get_defined_vars().
Questa funzione restituisce i nomi di tutte le funzioni definite all'interno del modulo indicato da module_name.
Nota: Il parametro module_name deve essere in minuscolo.
Ad esempio, il seguente comando:
<?php print_r(get_extension_funcs("xml")); print_r(get_extension_funcs("gd")); ?> |
visualizzerà l'elenco delle funzioni definite nei moduli xml e gd.
Vedere anche: get_loaded_extensions()
(PHP 4 >= 4.3.0, PHP 5)
get_include_path -- Restituisce il valore del parametro di configurazione include_pathRestituisce il valore di include_path.
Vedere anche ini_get(), restore_include_path(), set_include_path() e include().
Restituisce una matrice contenente i nomi di tutti i file che sono stati includi tramite le funzioni include(), include_once(), require() oppure require_once().
Lo script originario viene considerato come 'file incluso', pertanto sarà elencato insieme agli altri file referenziati da include() e simili.
File che sono inclusi più volte saranno elencati soltanto una volta sola
Nota: File inclusi tramite la direttiva auto_prepend_file non saranno inseriti nella matrice.
Esempio 1. Esempio di uso di get_included_files() del file (abc.php)
l'esempio visualizzerà:
|
Nota: In PHP 4.0.1pl2 e nelle versioni precedenti get_included_files() assumeva che i file inclusi avessero come estensione .php; file con altre estensioni erano ignorati. La matrice restituita da get_included_files() era una matrice associativa e riportava soltanto i file inclusi con include() e include_once().
Vedere anche include(), include_once(), require(), require_once() e get_required_files().
(PHP 4, PHP 5)
get_loaded_extensions -- Restituisce una matrice con il nome di tutti i moduli compilati e caricatiRestituisce una matrice con il nome di tutti i moduli compilati e caricati nell'interprete PHP.
Ad esempio la seguente linea:
<?php print_r(get_loaded_extensions()); ?> |
restituirà qualcosa simile a:
Array ( [0] => xml [1] => wddx [2] => standard [3] => session [4] => posix [5] => pgsql [6] => pcre [7] => gd [8] => ftp [9] => db [10] => calendar [11] => bcmath ) |
Vedere anche get_extension_funcs(), extension_loaded(), dl() e phpinfo().
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
get_magic_quotes_gpc -- Restituisce l'attuale configurazione di magic quotes gpcRestituisce l'impostazione attuale della direttiva di configurazione magic_quotes_gpc (0 uguale a off, 1 per on).
Nota: Se la direttiva magic_quotes_sybase è impostata a ON, questa è prioritaria rispetto a magic_quotes_gpc. Pertanto, anche se get_magic_quotes() restituisce TRUE ne i doppi apici, ne i backslashes o i NUL saranno preceduti dal caratteri di escape. Lo saranno soltanto gli apici singoli. In questo caso saranno: ''
Si ricordi che magic_quotes_gpc non può essere impostata a runtime.
Esempio 1. Esempio di uso di get_magic_quotes_gpc()
|
Nell'ottica di scrittura di codice portabile (codice che funzioni in qualsiasi ambiente), o, se non si hanno i permessi di modifica del php.ini, è possibile disabilitare gli effetti della funzione da script. Questo può essere fatto in due modi, o con una impostazione da .htaccess (php_value magic_quotes_gpc 0), oppure aggiungendo il codice sottostante allo script.
Esempio 2. Disattivare magic quotes da script
|
Vedere anche addslashes(), stripslashes(), get_magic_quotes_runtime() e ini_get().
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
get_magic_quotes_runtime -- Restituisce l'impostazione corrente della direttiva magic_quotes_runtimeRestituisce l'impostazione corrente della direttiva magic_quotes_runtime (0 per off, 1 per on).
Vedere anche get_magic_quotes_gpc() e set_magic_quotes_runtime().
Restituisce il valore della variabile d'ambiente varname, oppure FALSE in caso di errore.
Si può accedere all'elenco di tutte le variabili d'ambiente utilizzando phpinfo(). Si può avere una descrizione della maggior parte di queste alla pagina specifiche CGI , in modo particolare nella pagina delle variabili d'ambiente.
Nota: Questa funzione non gira in modalità ISAPI.
Vedere anche putenv().
Restituisce la data dell'ultima modifica alla pagina corrente. Il valore restituito è un timestamp, può essere elaborato con la funzione date(). Restituisce FALSE su errore.
Nota: Se si è interessati ad avere la data dell'ultima modifica di un'altro file, si consideri l'uso di filemtime().
Vedere anche date(), getmyuid(), getmygid(), get_current_user(), getmyinode(), getmypid() e filemtime().
Restituisce l'ID del gruppo del proprietario dello script, oppure FALSE per errore.
Vedere anche getmyuid(), getmypid(), get_current_user(), getmyinode() e getlastmod().
Restituisce l'inode dello script, oppure FALSE su errore.
Vedere anche getmygid(), getmyuid(), get_current_user(), getmypid() e getlastmod().
Nota: Questa funzione non è implementata su piattaforme Windows
Restituisce l'ID del processo PHP, oppure FALSE in caso errore.
Avvertimento |
Gli ID di processo non sono univoci, poichè sono sorgenti di bassa entropia. Si raccomanda di non basarsi sul pid nei contesti basati sulla sicurezza. |
Vedere anche getmygid(), getmyuid(), get_current_user(), getmyinode() e getlastmod().
Restituisce l'ID utente del proprietario dello script, oppure FALSE in caso di errore.
Vedere anche getmygid(), getmypid(), get_current_user(), getmyinode() e getlastmod().
Restituisce una matrcie associativa con l'accoppiata opzione / valore basata sulle opzioni attese indicate in options, oppure FALSE in caso di errore.
Sulle piattaforme che supportano la funzione C getopt_long, le opzioni 'lunghe' possono essere spcificate con il parametro longopts (dal PHP 4.3.0).
Il parametro options può contenere i seguenti elementi: caratteri individualie e caratteri seguiti dai due punti per indicare un'opzione seguita da un valore. Ad esempio, la stringa di opzione x identifica il parametro -x, e una stringa x: identifica un parametro ed il suo valore -x argument. Non è rilevante se il vlore è precedeuto da spazio.
Questa funzione restituisce l'accoppiata opzione / valore. Se l'opzione non ha valori, il valore restituito sarà FALSE.
Nota: Questa funzione non è implementata su piattaforme Windows
Questa funzione è un interfaccia a getrusage(2). Restituisce una matrice associativa contente le informazioni restituite dalla chiamata di sistema. Se il parametro who vale 1, getrusage()sarà eseguita con RUSAGE_CHILDREN.
Tutte le informazioni sono accessibili tramite i nomi dei campi documentati.
Nota: Questa funzione non è implementata su piattaforme Windows
Restituisce tutte le opzioni di configurazione come una matrice associativa. Se viene specificato il parametro opzionale extension La funzione restituirà solo le opzioni specifiche per quel modulo.
I nomi delle opzioni faranno da indice per la matrcie restituita, quindi gli elementi potranno essere: global_value (impostata in php.ini), local_value (impostata in ini_set() oppure in .htaccess), e access (il livello di accesso). Per avere informazioni su cosa siano i livello di accesso, vedere la pagina del manuale su modifiche di configurazione
Nota: Per le direttive è possibile avere più livelli di accesso, è per questo che access restituisce le appropriate maschere di bit.
Esempio 1. Esempio di uso di ini_get_all()
Parte dell'aoutput potrebbe essere:
|
Vedere anche ini_get(), ini_restore(), ini_set(), get_loaded_extensions() e phpinfo().
Restituisce il valore delle opzioni di configurazione. In caso di errore, tipo la richiesta per un valore inesistente, sarà restituita una stringa vuota.
Richieste per valori booleani: Nel file ini, il valore booleano off sarà restituito come stringa vuota o "0", mentre il valore on sarà restituito come "1".
Richieste per le dimensioni della memoria: Diversi parametri attinenti alle dimensioni di memoria, tipo upload_max_filesize sono registrati nel php.ini in notazione abbreviata. La funzione ini_get() restituirà l'esatto valore presente nel php.ini, e NON l'intero equivalente. L'esecuzione delle normali funzioni aritmetiche su questi valori potrà dare risultati inattesi. L'esempio seguente illustra come si possa convertire la notazione breve in byte in modo molto simile a come fa il PHP.
Esempio 1. Qualche esempio di ini_get()
Lo script produrrà:
|
Vedere anche: get_cfg_var(), ini_get_all(), ini_restore() e ini_set().
Ripristina il valore della data opzione di configurazione allo stato originale.
Vedere anche ini_get(), ini_get_all() e ini_set().
Imposta il valore di una data opzione di configurazione. Se l'operazione riesce restituisce il vecchio valore, oppure FALSE se fallisce. Le opzioni di configurazione manterranno il nuovo valore durante l'esecuzione dello script, e saranno ripristinate al termine dello stesso.
Non tutte le opzioni disponibili possono essere modificate da ini_set(). Nell'appendix vi è un elenco di tutte le opzioni disponibili.
Vedere anche: get_cfg_var(), ini_get(), ini_get_all() e ini_restore()
Non esiste una funzione main() tranne che nel sorgente PHP. Dal PHP 4.3.0 è stata introdotta nel sorgente una nuova tipologia di errore gestibile (php_error_docref). Una caratteristica di questa è quella di fornire il link alla pagina del manuale nel messaggio di errore nel caso in cui la direttiva html_errors (on per default) e docref_root (on per default dal PHP 4.3.2) siano impostate.
Qualche volta gli errori fanno riferimento alla pagina del manuale per la funzione main() ed è per questo che esiste questa pagina. Si prega di aggiungere nei commenti sottostanti quale funzione PHP ha cusato l'errore che punta a main(), e questo sarà prontamente corretto e documentato.
Tabella 1. Errori noti che punatno a main()
Nome della funzione | Non punta più qui da |
---|---|
include() | 4.3.2 |
include_once() | 4.3.2 |
require() | 4.3.2 |
require_once() | 4.3.2 |
Vedere anche html_errors e display_errors.
Restituisce la quantità di memoria, in byte, allocata dal PHP per lo script.
memory_get_usage() sarà disponibile solo se il PHP viene compilato con la configurazione --enable-memory-limit
Vedere anche memory_limit.
(PHP 4 >= 4.3.0, PHP 5)
php_ini_scanned_files -- Restituisce l'elenco dei file .ini leti dalla directory ini aggiuntivaphp_ini_scanned_files() restituisce un elenco separato da virgola dei file di configurazione letti dopo il php.ini. Questi file sono cercati nella directory specificata dall'opzione --with-config-file-scan-dir impostata al momento della compila.
La funzione restituisce la lista separata da virgola se riesce. Al contrario, se l'impostazione --with-config-files-scan-dir non è configurata la funzione resttuisce FALSE. Se un file non è riconoscibile, questo sarà inserito nell'elenco restituito, ma il PHP darà errore. Questo errore sarà visualizzato sia al momento della compila sia utilizzando php_ini_scanned_files().
La lista restituita comprende anche il percorso di include specificato in --with-config-file-scan-dir. Ogni virgola è seguita da un carattere di a capo (newline).
Questa funzione restituisce l'ID che può essere utlizzato per visualizzar il logo PHP pre-inserito.
Vedere anche phpinfo(), phpversion(), phpcredits() e zend_logo_guid().
(PHP 4 >= 4.0.1, PHP 5)
php_sapi_name -- Restituisce il tipo di interfaccia tra il PHP ed il server webphp_sapi_name() restituisce un testo minuscolo che descrive il tipo di interfaccia tra il PHP ed il server web (Server API, SAPI). In caso di CGI PHP, la stringa è "cgi", nel caso si usi mod_php per Apache, il testo sarà "apache" e così via.
(PHP 4 >= 4.0.2, PHP 5)
php_uname -- Restituisce informazioni sul sistema operativo su cui gira il PHPphp_uname() restituisce una stringa con la descrizione del sistema operativo su cui gira PHP. Se si desidera semplicemente il nome del sistema operativo, si utilizzi la costante PHP_OS, ma si ricordi che questa costante contiene il nome del sistema operativo su cui il PHP è stato compilato.
Sui sistemi Unix, la funzione passa a visualizzare il sistema operativo su cui il PHP è stato compilato, se non è in grado di determinare le imformazioni del sistema operativo su cui il PHP gira.
mode definisce quali informazioni debbano essere restituite:
'a': Questo è il default. Contiene tutte le modalità nella sequenza "s n r v m".
's': Nome del sistema operativo. Es. FreeBSD.
'n': Nome del server. Es. localhost.example.com.
'r': Nome del rilascio. Es. 5.1.2-RELEASE.
'v': Informazioni sulla versione. Varia molto in base al sistema operativo.
'm': Tipo di macchina. Es. i386.
Esempio 1. Alcuni esempi di php_uname()
|
Esistono alcune Costanti PHP predefinite che possono essere di aiuto, ad esempio:
Vedere anche phpversion(), php_sapi_name() e phpinfo().
Questa funzione visualizza la lista dei riconoscimenti per gli sviluppatori del PHP, dei vari moduli, eccetera. Genera il codice HTML appropriato per inserire l'informazine in una pagina. IL parametro opzionale flag, per default vale CREDITS_ALL, permette di selezionare di personalizzare la lista. Ad esempio per stampare l'elenco generale, utilizzare:
Se si vuole stampare l'elenco degli sviluppatori principali e del grupo di documentazione, in una pagina proprio conto, utilizzare:
E se si desidera inserire l'elenco completo nella propria pagina, utilizzare un codice simile al seguente:
<html> <head> <title>My credits page</title> </head> <body> <?php // some code of your own phpcredits(CREDITS_ALL - CREDITS_FULLPAGE); // some more code ?> </body> </html> |
Tabella 1. Flag pre-definiti phpcredits()
nome | descrizione |
---|---|
CREDITS_ALL | Tutta la lista dei meriti, equivale a CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_FULLPAGE. Genera una pagina HTML completa. |
CREDITS_DOCS | La lista del gruppo di documentazione |
CREDITS_FULLPAGE | Solitamente utilizzato in combinazione con altri flag. Indica che la pagina completa HTML deve essere stampata includendo le infomazioni di altri flag. |
CREDITS_GENERAL | Lista generale: design e progetto del linguaggio, autori del PHP 4.0 e del modulo SAPI. |
CREDITS_GROUP | Lista degli sviluppatori principali |
CREDITS_MODULES | Lista dei moduli e dei loro sviluppatori |
CREDITS_SAPI | Lista delle API server e dei loro sviluppatori |
Vedere anche phpinfo(), phpversion() e php_logo_guid().
Visualizza molte informazioni sullo stato corrente del PHP Queste includono informazioni sulle opzioni di compila del PHP, sui moduli, la versioen di PHP, informazioni sul server e sull'ambiente (se compilato come modulo), l'ambiente PHP, la versione di OS, percorsi, valori delle configurazioni base e attauli, intestazioni HTTP e la licenza del PHP.
Dato che ogni sistema ha una cofigurazione differente, phpinfo() viene comunemente utilizzato per verificare le impostazioni di configurazione e le variabili predefinite disponibili in un dato sistema. Inoltre, phpinfo() è utili come strumento di debug poichè visualizza tutti i dati EGPCS (Environment, GET, POST, Cookie, Server).
L'output può essere personalizzato passando una o più delle seguenti costanti sommate a livello di bit nel parametro opzionale what. Le costanti, o i rispettivi valori, possono essere combinati anche con l'operatore or.
Tabella 1. Opzioni di phpinfo()
Nome (constant) | Valore | Descrizione |
---|---|---|
INFO_GENERAL | 1 | La linea di configurazione, php.ini luogo, data di compila, Web Server, sistema e altro. |
INFO_CREDITS | 2 | PHP 4 Credits. Vedere anche phpcredits(). |
INFO_CONFIGURATION | 4 | Impostazioni correnti e di base delle opzioni PHP. Vedere anche ini_get(). |
INFO_MODULES | 8 | Moduli caricati e le loro impostazioni. Vedere anche get_loaded_extensions(). |
INFO_ENVIRONMENT | 16 | Variabili d'ambiente disponibili in $_ENV. |
INFO_VARIABLES | 32 | Visualizza tutte le variabili predefinite da EGPCS (Environment, GET, POST, Cookie, Server). |
INFO_LICENSE | 64 | Informazioni sulla licenza di PHP. Vedere anche faq sulla licenza. |
INFO_ALL | -1 | Visualizza tutto quanto descritto. Questo è il valore dei default. |
Nota: La visualizzazione di parte delle informazioni è disabilitata quando expose_php viene impostato a off. Queste includono i loghi PHP e Zend, e i credits.
Nota: La funzione phpinfo() produce un testo normale anzichè un file HTML quando è utilizzata in modalità CLI.
Vedere anche phpversion(), phpcredits(), php_logo_guid(), ini_get(), ini_set(), get_loaded_extensions() e la sezione sulle Variabili Predefinite.
Restituisce una stringa contenente la versione dell'interprete PHP.
Nota: Questa informazione è anche disponibile come costante predefinita PHP_VERSION.
Vedere anche version_compare(), phpinfo(), phpcredits(), php_logo_guid() e zend_version().
Imposta una variable nell'ambiente del server. La variabile d'ambiente esisterà solo per lòa durata dsello script Alla fine di questo l'ambiente sarà ripristinato allo stato originario.
L'impostazione di certe variabili d'ambiente può causare dei problemi di sicurezza. La direttiva safe_mode_allowed_env_vars contiene un'elenco separato da virgole di prefissi. In Mpodlità Sicura, l'utente può soltanto alterare le variabili d'ambiente il cui nome inizia con il prefisso indicato da questa direttiva. Per default, gli utenti sono abilitati ad impostare le variabili d'ambiente con inizino con PHP_ (ad esempio PHP_FOO=BAR). Nota: Se questa direttiva è vuota, il PHP permetterà all'utente di modificare QUALSIASI variabile d'ambiente!
La direttiva safe_mode_protected_env_vars contiene un elenco separato da virgola di variabili d'ambiente, che l'utente non può modificare tramite putenv(). Questa variabili saranno protette anche se safe_mode_allowed_env_vars autorizza la modifica a queste.
Avvertimento |
Queste impostazioni hanno effetto soltanto se safe-mode è impostato! |
Vedere anche getenv().
Ripristina il valore del parametro di configurazione include_path al valore impostato in php.ini
Esempio 1. Esempio di uso di restore_include_path()
|
Vedere anche ini_restore(), set_include_path(), get_include_path() e include().
Imposta il parametro di configurazione include_path per la durata dello script. La funzione restituisce la vecchia impostazione di include_path se ha successo, oppure FALSE se non riesce.
Vedere anche ini_set(), get_include_path(), restore_include_path() e include().
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
set_magic_quotes_runtime -- Imposta il valore attuale di magic_quotes_runtimeImposta il valore del parametro di configurazione magic_quotes_runtime (0 per off, 1 per on).
Vedere anche get_magic_quotes_gpc() e get_magic_quotes_runtime().
Imposta il limite massimo in secondi di durata dello script. Se si raggiunge questo limite, lo script viene interrotto con un errore fatale. Per default questo limite è impostato a 30 secondi o, se esiste, al valore di max_execution_time nel php.ini. Se il parametro seconds viene impostato a zero, non si impone alcun limite di tempo.
Quando viene eseguita la funzione set_time_limit(), questa re-imposta il il contatore del tempo di esecuzione a zero. In altre parole, se il timeout è impostato al default di 30 secondi, e dopo 25 secondi di esecuzione si richiama la funzione con set_time_limit(20), lo script potrà girare per 45 secondi.
Avvertimento |
La funzione set_time_limit() non ha effetto quando il PHP gira in modalità sicura. Non esistono soluzioni alternative se non quella di disabilitare la modalità sicura o modificare il limite nel php.ini. |
Nota: La funzione set_time_limit() e la configurazione max_execution_time agiscono solo sull'esecuzione dello script in cui sono. Qualsiasi tempo perso in attività esterno allo script, tipo le chiamate di sistema tramite system(), operazioni sugli stream, query di database, ecc non sono incluse nel conteggio del tempo massimo che ha lo script per girare.
Vedere anche max_execution_time e la direttiva max_input_time.
(PHP 4 >= 4.1.0, PHP 5)
version_compare -- Confronta due stringhe contenenti il numero di versione di "PHP-standardized"version_compare() confronta due numeri di versione "PHP-standardized" . Questa funzione è utile quando si desideri che funzioni solo con alcune versioni di PHP.
La funzione version_compare() restituisce -1 se la prima verisone è minore della seconda, 0 se sono uguali, +1 se la sceonda è inferiore.
Per prima cosa la funzione sostituisce nella strina di versione le lettere _, - e + con un puntot . ed inserisce un punto . prima e dopo ogni carattere non numerico, in modo che, ad esempio, '4.3.2RC1' diventi ''4.3.2.RC.1'. Quindi divite il testo come se usasse explode('.', $ver). Poi confronta le parti cominciando da sinistra verso destra Se una parte contiene versioni speciali queste sono gestite nel seguente modo: dev < alpha = a < beta = b < RC < pl. In quest modo possono essere confrontati non solo differenti livelli di versioni quali '4.1' e '4.1.2', ma anche versioni di PHP in fase di sviluppo.
Specificando il terzo parametro opzionale operator si possono testare particolari relazioni. I possibili operatori sono: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne. Utilizzando questi parametri, la funzione restituirà 1 se la relazione è una di quelle specificate dall'operatore, altrimenti 0.
Questa funzioen restituisce l'ID che può essere utilizzato per visualizzare il logo Zend usando l'immagine inserita nel PHP.
Vedere anche php_logo_guid().
Restituisce una stringa contenente il numero di versione dell'engine Zend.
Vedere anche phpinfo(), phpcredits(), php_logo_guid() e phpversion().
Questo modulo contiene un'interfaccia alle funzioni definite dallo standard IEEE 1003.1 (POSIX.1) che non sono accessibili in altro modo. Ad esempio lo standard POSIX.1 definisce le funzioni open(), read(), write() e close() che tradizionalmente sono parte di PHP 3 da lungo tempo. Altre funzioni più specifiche del sistema operativo non sono disponibili, e quindi con questo modulo si cerca di porre rimedio a questa mancanza dando un facile accesso a queste funzioni.
Avvertimento |
Con le funzioni POSIX si possono ricavare informazioni sensibili tipo posix_getpwnam() e simili. Nessuna delle funzioni POSIX esegue alcun tipo di controllo di accesso quando è abilitata la modalità sicura. Pertanto è vivamente consigliato di disabilitare l'estensione POSIX (impostare --disable-posix nella linea di configurazione) se si opera con la modalità sicura. |
Nota: Questo modulo non è disponibile su piattaforme Windows.
Le funzioni POSIX sono abilitate per default. Si possono disabilitare con --disable-posix.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Check whether the file exists.
Check whether the file exists and has read permissions.
Check whether the file exists and has write permissions.
Check whether the file exists and has execute permissions.
Block special file
Character special file
FIFO (named pipe) special file
Normal file
Socket
Nota: These constants are available since PHP 5.1.0. Please also note that some of them may not be available in your system.
posix_access() checks the user's permission of a file.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
The name of the file to be tested.
A mask consisting of one or more of POSIX_F_OK, POSIX_R_OK, POSIX_W_OK and POSIX_X_OK. Defaults to POSIX_F_OK.
POSIX_R_OK, POSIX_W_OK and POSIX_X_OK request checking whether the file exists and has read, write and execute permissions, respectively. POSIX_F_OK just requests checking for the existence of the file.
Esempio 1. posix_access() example This example will check if the $file is readable and writable, otherwise will print an error message.
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
posix_get_last_error -- Recupera il numero di errore dell'ultima funzione posix non riuscitaRestituisce il codice di errore impostato dall'ultima funzione posix che non è terminata correttamente. Se non vi sono errori la funzione restituisce 0. Se si desidera il messaggio corrispondente al codice utilizzare posix_strerror().
Vedere anche posix_strerror().
La funzione posix_getcwd() restituisce il percorso assoluto della corrente directory di lavoro.La funzioneposix_getcwd() restituisce FALSE se si verifica un errore.
(PHP 3 >= 3.0.10, PHP 4, PHP 5)
posix_getegid -- Restituisce l'ID del gruppo per il processo correnteLa funzione restituisce l'ID del gruppo per il processo corrente. Vedere anche posix_getgrgid() per dettagli su come convertire il numero nel nome effettivo del gruppo.
(PHP 3 >= 3.0.10, PHP 4, PHP 5)
posix_geteuid -- Restituisce l'ID dell'utente per il processo correnteRestituisce il valore numerico dell'ID dell'utente per il processo corrente. Vedere posix_getpwuid() per maggiori dettagli su come convertire il numero nel nome dell'utente.
(PHP 3 >= 3.0.10, PHP 4, PHP 5)
posix_getgid -- Restituisce il reale ID del gruppo per il processo correnteLa funzione restituisce il reale ID del gruppo del processo. Vedere anche posix_getgrgid() per dettagli su come convertire il numero nel nome effettivo del gruppo.
(PHP 3 >= 3.0.13, PHP 4, PHP 5)
posix_getgrgid -- Restituisce informazioni su un gruppo dato il suo IDRestituisce un array con le informazioni del gruppo, oppure FALSE se si verifica un errore. Se gid non è un numero la funzione restituisce NULL e genera un errore di tipo E_WARNING.
Nota: A partire da PHP 4.2.0, la funzione restituisce l'elenco dei membri del gruppo in un array ordinato per nome. Precedentemente si restituiva un intero (il numero dei membri del gruppo) ed i nomi dei membri doveva essere recuperato tramite l'indice numerico.
Vedere anche posix_getegid(), filegroup(), stat() e safe_mode_gid.
(PHP 3 >= 3.0.13, PHP 4, PHP 5)
posix_getgrnam -- Restituisce le informazioni di un gruppo dato il nome
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione restituisce una matrcie di interi contenente gli ID dei gruppi per il processo corrente. Vedere anche posix_getgrgid() per informazioni su come convertire questo numero nel nome del gruppo.
Restituisce il nome dell'utente proprietario del processo corrente. Vedere posix_getpwnam() per dettagli su come ottenere maggiori informazioni sull'utente.
(PHP 3 >= 3.0.10, PHP 4, PHP 5)
posix_getpgid -- Restituisce l'id del gruppo del processo per il controllo dei jobLa funzione restituisce l'id del gruppo per il processo indicato da pid.
Questa non è una funzione POSIX, ma è comune sui sistemi BSD e System V. Se il vostro sistema non supporta questa funzione, la funzione PHP restituirà sempre FALSE.
(PHP 3 >= 3.0.10, PHP 4, PHP 5)
posix_getpgrp -- Restituisce l'identificatore di gruppo per il processo correnteRestituisce l'identificatore del gruppo di processo per il processo corrente. Vedere le pagine del manuale del vostro sistema POSIX relativamente a POSIX.1 e getpgrp(2) per avere maggiori dettagli sui gruppi di processo.
Restituisce l'ID del processo genitore per il processo corrente.
La funzione restituisce un array associativo contenente le informazioni sull'utente con nome specificato nel parametro username.
Gli elementi dell'array sono:
Tabella 1. Array delle informazioni utente
Elemento | Descrizione |
---|---|
name | L'elemento name solitamente contiene il nome dell'utente. Questo è un nome corto, di solito meno di 16 caratteri, non il nome reale, completo, dell'utente. Questo dovrebbe essere uguale al parametro username passato alla funzione e quindi ridondante. |
passwd | L'elemento passwd contiene la password dell'utente in formato criptato. Spesso, ad esempio nei sistemi utilizzano password "shadow", vengono restituiti degli asterischi. |
uid | ID dell'utente in formato numerico. |
gid | ID del gruppo a cui appartiene l'utente. Utilizzare la funzione posix_getgrgid() per ottenere il nome del gruppo e l'elenco dei suoi membri. |
gecos | GECOS è un termine obsoleto che si riferisce a campi del comando finger su sistemi Honeywell. Tuttavia il campo è sopravvissuto ed il suo contenuto è stato formalizzato in POSIX. Il campo contiene le informazioni separate da virgola relative a nome completo dell'utente, numero telefonico dell'ufficio, numero dell'ufficio, numero telefonico di casa. In molti sistemi è disponibile solo il nome completo dell'utente. |
dir | Questo elemento contiene il percorso assoluto alla home directory dell'utente. |
shell | L'elemento shell contiene il percorso assoluto alla shell di default per l'utente. |
(PHP 3 >= 3.0.13, PHP 4, PHP 5)
posix_getpwuid -- Restituisce le informazioni di un utente dato il suo IDLa funzione restituisce un array associativo contenente le informazioni sull'utente il cui ID è stato fornito nel parametro uid.
Gli elementi dell'array sono:
Tabella 1. Array delle informazioni utente
Elemento | Descrizione |
---|---|
name | L'elemento name solitamente contiene il nome dell'utente. Questo è un nome corto, di solito meno di 16 caratteri, non il nome reale, completo, dell'utente. Questo dovrebbe essere uguale al parametro username passato alla funzione e quindi ridondante. |
passwd | L'elemento passwd contiene la password dell'utente in formato criptato. Spesso, ad esempio nei sistemi utilizzano password "shadow", vengono restituiti degli asterischi. |
uid | ID dell'utente in formato numerico. |
gid | ID del gruppo a cui appartiene l'utente. Utilizzare la funzione posix_getgrgid() per ottenere il nome del gruppo e l'elenco dei suoi membri. |
gecos | GECOS è un termine obsoleto che si riferisce a campi del comando finger su sistemi Honeywell. Tuttavia il campo è sopravvissuto ed il suo contenuto è stato formalizzato in POSIX. Il campo contiene le informazioni separate da virgola relative a nome completo dell'utente, numero telefonico dell'ufficio, numero dell'ufficio, numero telefonico di casa. In molti sistemi è disponibile solo il nome completo dell'utente. |
dir | Questo elemento contiene il percorso assoluto alla home directory dell'utente. |
shell | L'elemento shell contiene il percorso assoluto alla shell di default per l'utente. |
(PHP 3 >= 3.0.10, PHP 4, PHP 5)
posix_getrlimit -- Restituisce informazioni sui limiti delle risorse del sistema
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione restituisce il sid per il processo indicato in pid. Se pid è impostato a 0, la funzione restituisce il sid del processo corrente.
Questa non è una funzione POSIX, ma è comune sui sistemi System V. Se il vostro sistema non supporta questa funzione, la funzione PHP restituirà sempre FALSE.
(PHP 3 >= 3.0.10, PHP 4, PHP 5)
posix_getuid -- Restituisce il reale ID dell'utente per il processo correnteLa funzione restituisce il reale ID dell'utente per il processo corrente. Vedere anche posix_getpwuid() per dettagli su come convertire questo nel nome dell'utente.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione invia il segnale sig al processo il cui identificatore è pid. La funzione restituisce FALSE, se non riesce ad inviare il segnale, TRUE altrimenti.
Vedere anche anche kill(2) nel manuale del vostro sistema POSIX per avere informazioni sui processi con identificatore negativo, lo speciale pid 0, -1 ed il segnale 0.
(PHP 3 >= 3.0.13, PHP 4, PHP 5)
posix_mkfifo -- Crea un file speciale di tipo fifo (una pipe nominata)La funzione posix_mkfifo() un file speciale FIFO che esiste nel file system e agisce come teminale per comunicazioni bidirezionali tra processi.
Il secondo parametro, mode deve essere passato con notazione ottale (ad esempio 0644). I permessi della nuova FIFO dipendono anche dall'impostazione corrente di umask(). I permessi del file creato sono (mode & ~umask).
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Quando safe-mode è abilitato, PHP controlla che la directory nella quale si sta lavorando, abbia lo stesso UID dello script che è in esecuzione.
posix_mknod() creates a special or ordinary file.
The file to create
This parameter is constructed by a bitwise OR between file type (one of the following constants: POSIX_S_IFREG, POSIX_S_IFCHR, POSIX_S_IFBLK, POSIX_S_IFIFO or POSIX_S_IFSOCK) and permissions.
The major device kernel identifier
The minor device kernel identifier
La funzione imposta l'effettivo ID di gruppo per il processo. Poichè questa è una funzione privilegiata occorre avere gli opportuni privilegi (solitamente di root) per poterla eseguire.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
Imposta lo user ID per il processo corrente. Poichè questa è una funzione privilegiata occorre avere gli opportuni privilegi (solitamente di root) per poterla eseguire.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche posix_setgid().
La funzione imposta il reale ID di gruppo per il processo. Poichè questa è una funzione privilegiata occorre avere gli opportuni privilegi (solitamente di root) per poterla eseguire. L'ordine corretto per richiamare la funzione è: posix_setgid() prima, posix_setuid() poi.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione permette al processo identificato da pid di unirsi al gruppo di processi identificati da pgid. Vedere POSIX.1 e setsid(2) nel manuale del vostro sistema POSIX per avere maggiori dettagli sui gruppi di processi e sul controllo dei job. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione rende il processo corrente leader di sessione. Vedere POSIX.1 e setsid(2) nelle pagine del manuale del vostro sistema POSIX per maggiori dettagli sui gruppi di processi e sul controllo dei job. La funzione restituisce l'id di sessione.
La funzione imposta il reale ID di utente per il processo corrente. Questa è una funzione privilegiata e pertanto richiede gli opportuni privilegi (di solito root) per potere essere eseguita.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche posix_setgid().
(PHP 4 >= 4.2.0, PHP 5)
posix_strerror -- Recupera il messaggio di errore di un dato codice di erroreLa funzione restiruisce il messaggio di erore POSIX associato aa un dato codice di errore. Se il parametro errno è impostato a 0, viene restituita la stringa "Success". Utilizzare la funzione posix_get_last_error() per ottenere il codice di errore.
Vedere anche posix_get_last_error().
Restituisce una serie di stringhe con le imformazioni sull'utilizzo di CPU del processo. L'indice della matrice è:
ticks - il numero di ticks dall'ultimo rebbot.
utime - user time utilizzato dal processo.
stime - system time utilizzato dal processo.
cutime - user time uutilizzato dal processo e dai suoi figli.
cstime - system time uutilizzato dal processo e dai suoi figli.
Avvertimento |
Questa funzione non è affidabile nell'uso, può restituire valori negativi per tempi molto elevati. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione restituisce un array con informazioni sul sistema. Le chiavi dell'array sono:
sysname - nome del sistema operativo (es. Linux)
nodename - nome del sistema (es. valiant)
release - release del sistema operativo (es. 2.2.10)
version - versione del sistema operativo (es. #4 Tue Jul 20 17:01:36 MEST 1999)
machine - architettura del sistema (es. i586)
domainname - nome del dominio DNS (es. example.com)
La chiave domainname è una estensione GNU e non è parte di POSIX.1, quindi questo campo è disponibile soltanto su sistemi GNU o quando si utilizza la libc di GNU.
Lo standard POSIX richiede di non fare affidamento sul formato dei valori restituiti, ad esempio non aspettarsi di avere sempre tre cifre nel numero di versione.
Suggerimento: Il PHP, utilizzando le funzioni PCRE, supporta anche le espressioni regolari con una sintassi compatibile con Perl. Queste funzioni supportano riconoscimenti "pigliatutto", asserzioni, criteri condizionali, e diverse altre caratteristiche che non sono supportate dalla sintassi POSIX estesa.
Avvertimento |
Queste funzioni per l'espressioni regolari non sono binary-safe. Le funzioni PCRE lo sono. |
In PHP, le espressioni regolari sono utilizzate per complesse manipolazioni di stringhe. Le espressioni regolari utilizzate da PHP sono di tipo POSIX esteso così come definito in POSIX 1003.2. Per una descrizione completa delle espressione regolari POSIX, vedere la pagina del manuale di regex inclusa nella directory di regex nella distribuzione di PHP. Questa è in formato man, pertanto per poterle leggere occorre eseguire man /usr/local/src/regex/regex.7.
Avvertimento |
Non variare TYPE se non si sa cosa si sta facendo. |
Per abilitare il supporto a regex occorre configurare il PHP con --with-regex[=TYPE]. TYPE può essere: system, apache, php. Per default si usa php.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Esempio 1. Esempi di espressione regolare
|
Per maggiori dettagli sulle espressioni regolari compatibili con Perl vedere il capitolo sulle funzioni PCRE. La funzione fnmatch() fornisce il riconoscimento dei caratteri jolly tipici della linea di comando.
La funzione ricerca all'interno del parametro stringa sottostringhe che incrocino con le condizioni specificate in espressione_regolare. Quando sono trovate, queste vengono sostituite con il testo specificato in testo_sostitutivo.
La funzione restituisce la stringa modificata. (Ciò implica che se non ci sono sottostringhe che soddisfino l' espressione regolare, la funzione restituisce la stringa originaria).
Se in espressione_regolare si specificano delle sottostringhe utilizzando le parentesi, anche nel campo testo_sostitutivo si possono specificare delle sottostringhe di formato \\digit , che saranno sostituite dalle stringhe soddisfacenti la digit'esima condizione posta tra parentesi; \\0 indica l'intera stringa. La funzione prevede che si possano utlizzare fino a nove sottostringhe. E' previsto che le parentesi siano nidificate, in questo caso il conteggio si basa sulle parentesi aperte.
Se nessuna parte di stringa viene riconosciuta, il parametro viene restituito invariato.
Come esempio il seguente frammento di codice visualizzerà la frase "Questo fu un test" tre volte:
Un aspetto a cui occorre prestare attenzione riguarda l'uso di numero intero per il parametro testo_sostitutivo, si potrebbero ottenere risultati diversi da quanto atteso. Questo accade perchè la funzione ereg_replace() interpreta il numero come posizione ordinale di un carattere comportandosi di conseguenza. Ad esempio:
Esempio 2. ereg_replace() esempio
|
Suggerimento: Poichè utilizza espressioni regolari con sintassi compatibile con Perl, preg_replace(), è spesso una alternativa più veloce a ereg_replace().
Vedere anche ereg(), eregi(), eregi_replace(), str_replace() e preg_match().
Nota: Poichè utilizza espressioni regolari con sintassi compatibile con PERL, preg_match(), è spesso una alternativa più veloce a ereg().
Ricerca in stringa testi che possano incrociarsi con l'espressione regolare indicata in espressione_regolare distinguendo tra lettere minuscole e maiuscole.
Se le parti di testo poste tra parentesi nel campo espressione_regolare sono incontrate nella stringa e la funzione viene chiamata utilizzando il terzo parametro regs, il testo riconosciuto sarà memorizzato nella matrice regs. L'indice 1, $regs[1], conterrà la sottostringa che parte dalla prima parentesi sinistra; $regs[2] conterrà la sottostringa a partire dalla seconda e così via. L'indice 0, $regs[0], conterrà la copia completa della stringa riconosciuta.
Nota: Fino alla versione di PHP 4.1.0 compresa, $regs conterrà esattamente 10 elementi, anche se il numero delle stringhe riconosciute sia maggiore o minore di 10. Ciò non limita ereg() nella ricerca di più sottostringhe. Se non si riconoscono testi, $regs non sarà modificato da ereg().
La funzione ritorna la lunghezza della stringa riconosciuta se le ricerche previste da espressione_regolare sono riscontrate in stringa. Viene restituito FALSE se non si hanno riscontri, oppure si verificano degli errori. Se non si fornisce il parametro opzionale regs oppure la lunghezza della stringa riconosciuta è 0, questa funzione restituisce 1.
Nel seguente frammento di codice, una data in formato ISO (YYYY-MM-DD) verrà visualizzata nel formato DD.MM.YYYY:
Vedere anche eregi(), ereg_replace(), eregi_replace(), preg_match(), strpos() e strstr().
(PHP 3, PHP 4, PHP 5)
eregi_replace -- Sostituzioni con espressioni regolari senza distinzione tra maiuscole e minuscoleQuesta funzione è identica a ereg_replace(), tranne che per il fatto che non distingue tra lettere maiuscole e lettere minuscole.
Vedere anche ereg(), eregi() e ereg_replace().
(PHP 3, PHP 4, PHP 5)
eregi -- Riconoscimento di espressioni regolari senza distinzione tra maiuscole e minuscoleQuesta funzione è identica a ereg(), tranne che per il fatto che non distingue tra lettere maiuscole e lettere minuscole.
Vedere anche ereg(), ereg_replace(), eregi_replace(), stripos() e stristr().
(PHP 3, PHP 4, PHP 5)
split -- Suddivide una stringa in una matrice utilizzando le espressioni regolariSuggerimento: Poichè utilizza espressioni regolari con sintassi compatibile con Perl, preg_split(), è spesso una alternativa più veloce a split(). Se non si ha necessità delle capacità delle espressioni regolari, è più veloce l'utilizzo di explode(), che non richiede l'overhead del motore delle espressioni regolari.
La funzione restituisce una matrice di stringhe che sono delle sottostringhe del parametro stringa. Queste sono ottenute suddividendo il parametro secondo i limiti indicati dal parametro sensibile alle maiuscole espressione_regolare. Se viene specificato il parametro limite, la funzione restituisce una matrice con un numero di elementi al massimo pari a limite. L'ultimo elemento della matrice contiene la parte restante del parametro stringa fornito. Se si verificano errori la funzione split() restituisce FALSE.
Esempio di come estrapolare i primi 4 campi da una linea del file /etc/passwd:
Se nella stringa passata vi sono n occorrenze del parametro espressione_regolare, la matrice restituita conterrà n+1 elementi. Invece, nel caso in cui non vi siano occorrenze della espressione_regolare, la matrice restituita conterrà un solo elemento. Ovviamente questo è valido anche nel caso in cui il parametro stringa è vuoto.
Nell'esempio che segue, si vedrà come analizzare una data il cui testo può contenere barre, punti o trattini:
Gli utenti che cercano un modo di emulare il comportamento di Perl @chars = split('', $str), sono rimandati agli esempi di preg_split().
Occorre fare attenzione al fatto che il parametro espressione_regolare è una espressione regolare e, pertanto, se si devono riconoscere caratteri che sono considerati speciali per le espressioni regolari, occorre codificarli con i caratteri di escape. Se si ritiene che la funzione split () ( o anche le altre funzioni derivate da regex ) si comportino in modo anomalo, è opportuno leggere il file regex.7, incluso nella cartella regex/ della distribuzione di PHP. Questo file è nel formato del manuale di unix (man), pertanto per visualizzarlo occorre eseguire il comando man /usr/local/src/regex/regex.7.
Vedere anche: preg_split(), spliti(), explode(), implode(), chunk_split() e wordwrap().
(PHP 4 >= 4.0.1, PHP 5)
spliti -- Suddivide una stringa in una matrice usando le espressioni regolari senza distinguere tra maiuscole e minuscoleQuesta funzione ha un comportamento identico a split() tranne che per il fatto di non distinguere tra lettere maiuscole e minuscole. characters.
Il seguente esempio suddivide una stringa utilizzando la lettera 'a' come separatore:
Vedere anche preg_split(), split(), explode(), e implode().
(PHP 3, PHP 4, PHP 5)
sql_regcase -- Genera una espressione regolare per riconoscimenti senza distinguere tra maiuscole e minuscoleLa funzione restituisce una espressione regolare che sia in grado di riconoscere il parametro stringa, a prescindere dalle lettere maiuscole minuscole. L'espressione regolare restituita corrisponde a stringa con ciascun carattere alfabetico riportato tra parentesi. Ogni parentesi contiene il singolo carattere in maiuscolo ed in minuscolo. I rimanenti caratteri sono riportati immutati.
Questa funzione torna utile quando si devono ottenere espressioni regolari non distinguono tra lettere maiuscole e minuscole da passare a prodotti che supportano espressioni regolari che distinguono il tipo di lettera.
Il database PostgreSQL è un prodotto OpenSource ed è disponibile gratuitamente. Postgres, sviluppato originariamente nel Dipartimento di Informatica dell'Università di Berkeley, ha anticipato molti dei concetti su oggetti e relazioni che ora stanno diventando disponibili in alcuni database commerciali. Postgres fornisce supporto per il linguaggio SQL/92/SQL99, transazioni, integrità referenziale, stored procedures ed estensibilità dei tipi. PostgreSQL è un discendente open source dell'originario codice di Berkeley.
Per utilizzare il supporto a PostgreSQL, occorre PostgreSQL 6.5 o versioni più recenti. PostgreSQL 7.0 o successivi permettono di abilitare tutte le funzionalità di questo modulo. PostgreSQL ammette molte codifiche di carattere, tra cui la codifica multibyte. La versione corrente e maggiori informazioni su PostgreSQL sono disponibili su http://www.postgresql.org/ e http://techdocs.postgresql.org/.
In order to enable PostgreSQL support, --with-pgsql[=DIR] is required when you compile PHP. DIR is the PostgreSQL base install directory, defaults to /usr/local/pgsql. If shared object module is available, PostgreSQL module may be loaded using extension directive in php.ini or dl() function.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. PostgreSQL configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
pgsql.allow_persistent | "1" | PHP_INI_SYSTEM | |
pgsql.max_persistent | "-1" | PHP_INI_SYSTEM | |
pgsql.max_links | "-1" | PHP_INI_SYSTEM | |
pgsql.auto_reset_persistent | "0" | PHP_INI_SYSTEM | Available since PHP 4.2.0. |
pgsql.ignore_notice | "0" | PHP_INI_ALL | Available since PHP 4.3.0. |
pgsql.log_notice | "0" | PHP_INI_ALL | Available since PHP 4.3.0. |
Breve descrizione dei parametri di configurazione.
Whether to allow persistent Postgres connections.
The maximum number of persistent Postgres connections per process.
The maximum number of Postgres connections per process, including persistent connections.
Detect broken persistent links with pg_pconnect(). Needs a little overhead.
Whether or not to ignore PostgreSQL backend notices.
Whether or not to log PostgreSQL backends notice messages. The PHP directive pgsql.ignore_notice must be off in order to log notice messages.
Avvertimento |
L'utilizzo del modulo PostgreSQL con PHP 4.0.6 non è raccomandato a causa di un bug nella gestione dei messaggi. Si usi PHP 4.1.0 o successivi. |
Avvertimento | ||||||||||||||||||||||||||||||||||||||||||||
I nomi delle funzioni relative a PostgreSQL verranno cambiate a partire dalla versione 4.2.0 per conformarsi agli standard di sviluppo attuali. La maggior parte dei nuovi nomi avrà underscore aggiuntivi, per esempio pg_lo_open(). Alcune funzioni verranno rinominate per dare consistenza. Per esempio pg_exec() diventerà pg_query(). I vecchi nomi potranno essere usati nella versione 4.2.0 e in alcune versioni successive alla 4.2.0, ma potranno essere cancellati in futuro. Tabella 2. Nomi di funzione cambiati
La vecchia sintassi di pg_connect()/pg_pconnect() sarà deprecata per supportare, in futuro, connessioni asincrone. Si usi una stringa di connessione con pg_connect() e pg_pconnect(). |
Non tutte le funzioni sono supportate su tutte le architetture. Dipende dalla versione di libpq (L'interfaccia Client C per PostgreSQL) e da come libpq è compilato. Se c'è una funzione mancante, libpq non supporta la feature richiesta per quella funzione.
È importante usare versioni di libpq più recenti rispetto al Server PostgreSQL al quale ci si vuole collegare. Se si usa una versione di libpq più vecchia rispetto al Server PostgreSQL al quale ci si vuole collegare, si andrà probabilmente incontro a problemi.
Fin dalla versione 6.3 (03/02/1998) PostgreSQL usa gli unix domain socket di default. La porta TCP, di default, NON verrà aperta. La tabella sottostante descrive queste nuove possibilità di connessione. Questo socket può essere trovato in /tmp/.s.PGSQL.5432. Questa opzione può venire abilitata con la flag '-i' da postmaster e il suo significato è: "ascolta i socket TCP/IP così come gli Unix domain socket".
Tabella 3. Postmaster e PHP
Postmaster | PHP | Status |
---|---|---|
postmaster & | pg_connect("dbname=NomeMioDatabase"); | OK |
postmaster -i & | pg_connect("dbname=NomeMioDatabase"); | OK |
postmaster & | pg_connect("host=localhost dbname=NomeMioDatabase"); | Unable to connect to PostgreSQL server: connectDB() failed: Is the postmaster running and accepting TCP/IP (with -i) connection at 'localhost' on port '5432'? in /path/to/file.php on line 20. |
postmaster -i & | pg_connect("host=localhost dbname=NomeMioDatabase"); | OK |
Si può stabilire una connessione al server PostgreSQL usando le seguenti coppie di valori impostate nella stringa di comando: $conn = pg_connect("host=IlMioHost port=LaMiaPorta tty=myTTY options=LeMieOpzioni dbname=IlMioDB user=IlMioUtente password=LaMiaPassword ");
L'uso della sintassi in uso precedentemente: $conn = pg_connect ("host", "port", "options", "tty", "dbname") è deprecato.
Le variabili d'ambiente modificano il comportamento server/client di PostgreSQL. Per esempio, il modulo PostgreSQL si baserà sulla variabile PGHOST quando il nome dell'host è omesso nella stringa di connessione. Le variabili d'ambiente riconosciute sono diverse da versione a versione. Consultare il Manuale del Programmatore PostgreSQL (libpq - Variabili d'Ambiente) per ulteriori dettagli.
Assicurarsi di aver impostato le variabili d'ambiente per l'utente appropriato. Usare $_ENV o getenv() per controllare quali variabili d'ambiente sono disponibili al processo corrente.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Passed to pg_fetch_array(). Return an associative array of field names and values.
Passed to pg_fetch_array(). Return a numerically indexed array of field numbers and values.
Passed to pg_fetch_array(). Return an array of field values that is both numerically indexed (by field number) and associated (by field name).
Passed to pg_connect() to force the creation of a new connection, rather then re-using an existing identical connection.
Returned by pg_connection_status() indicating that the database connection is in an invalid state.
Returned by pg_connection_status() indicating that the database connection is in a valid state.
Passed to pg_lo_seek(). Seek operation is to begin from the start of the object.
Passed to pg_lo_seek(). Seek operation is to begin from the current position.
Passed to pg_lo_seek(). Seek operation is to begin from the end of the object.
Returned by pg_result_status(). The string sent to the server was empty.
Returned by pg_result_status(). Successful completion of a command returning no data.
Returned by pg_result_status(). Successful completion of a command returning data (such as a SELECT or SHOW).
Returned by pg_result_status(). Copy Out (from server) data transfer started.
Returned by pg_result_status(). Copy In (to server) data transfer started.
Returned by pg_result_status(). The server's response was not understood.
Returned by pg_result_status(). A nonfatal error (a notice or warning) occurred.
Returned by pg_result_status(). A fatal error occurred.
Returned by pg_transaction_status(). Connection is currently idle, not in a transaction.
Returned by pg_transaction_status(). A command is in progress on the connection. A query has been sent via the connection and not yet completed.
Returned by pg_transaction_status(). The connection is idle, in a transaction block.
Returned by pg_transaction_status(). The connection is idle, in a failed transaction block.
Returned by pg_transaction_status(). The connection is bad.
Passed to pg_result_error_field(). The severity; the field contents are ERROR, FATAL, or PANIC (in an error message), or WARNING, NOTICE, DEBUG, INFO, or LOG (in a notice message), or a localized translation of one of these. Always present.
Passed to pg_result_error_field(). The SQLSTATE code for the error. The SQLSTATE code identifies the type of error that has occurred; it can be used by front-end applications to perform specific operations (such as error handling) in response to a particular database error. This field is not localizable, and is always present.
Passed to pg_result_error_field(). The primary human-readable error message (typically one line). Always present.
Passed to pg_result_error_field(). Detail: an optional secondary error message carrying more detail about the problem. May run to multiple lines.
Passed to pg_result_error_field(). Hint: an optional suggestion what to do about the problem. This is intended to differ from detail in that it offers advice (potentially inappropriate) rather than hard facts. May run to multiple lines.
Passed to pg_result_error_field(). A string containing a decimal integer indicating an error cursor position as an index into the original statement string. The first character has index 1, and positions are measured in characters not bytes.
Passed to pg_result_error_field(). This is defined the same as the PG_DIAG_STATEMENT_POSITION field, but it is used when the cursor position refers to an internally generated command rather than the one submitted by the client. The PG_DIAG_INTERNAL_QUERY field will always appear when this field appears.
Passed to pg_result_error_field(). The text of a failed internally-generated command. This could be, for example, a SQL query issued by a PL/pgSQL function.
Passed to pg_result_error_field(). An indication of the context in which the error occurred. Presently this includes a call stack traceback of active procedural language functions and internally-generated queries. The trace is one entry per line, most recent first.
Passed to pg_result_error_field(). The file name of the PostgreSQL source-code location where the error was reported.
Passed to pg_result_error_field(). The line number of the PostgreSQL source-code location where the error was reported.
Passed to pg_result_error_field(). The name of the PostgreSQL source-code function reporting the error.
Passed to pg_set_error_verbosity(). Specified that returned messages include severity, primary text, and position only; this will normally fit on a single line.
Passed to pg_set_error_verbosity(). The default mode produces messages that include the above plus any detail, hint, or context fields (these may span multiple lines).
Passed to pg_set_error_verbosity(). The verbose mode includes all available fields.
Passed to pg_result_status(). Indicates that numerical result code is desired.
Passed to pg_result_status(). Indicates that textual result command tag is desired.
Passed to pg_convert(). Ignore default values in the table during conversion.
Passed to pg_convert(). Use SQL NULL in place of an empty string.
Passed to pg_convert(). Ignore conversion of NULL into SQL NOT NULL columns.
A partire da PostgreSQL 7.1.0, il tipo di dato text ha 1GB come dimensione massima. Nelle versioni più vecchie di PostgreSQL il tipo di dato text è limitato dalla dimensione del block. (Default 8KB. Massimo 32KB, specificato al momento della compilazione)
Per usare l'interfaccia large object (lo), è necessario includerla entro un blocco di una transazione. Un blocco di transazione inizia con un comando SQL BEGIN e se la transazione è stata valida, termina con COMMIT o END. Se la transazione fallisce, essa deve venire chiusa con ROLLBACK o ABORT.
Esempio 2. Utilizzare Large Objects
|
(PHP 4 >= 4.2.0, PHP 5)
pg_affected_rows -- Restituisce il numero delle tuple coinvolte dall'ultimo comandopg_affected_rows() restituisce il numero di tuple (istanze/record/righe) coinvolte dalle query INSERT, UPDATE, e DELETE eseguite da pg_query(). Se nessuna tupla è stata modificata da questa funzione, restituisce 0.
Nota: Questa funzione si chiamava pg_cmdtuples().
Vedere anche pg_query() e pg_num_rows().
pg_cancel_query() annulla una query asincrona inviata da pg_send_query(). Non è possibile annullare query eseguite attraverso pg_query().
Vedere anche pg_send_query() e pg_connection_busy()
(PHP 3 CVS only, PHP 4 >= 4.0.3, PHP 5)
pg_client_encoding -- Restituisce la codifica caratteri del clientpg_client_encoding() restituisce la codifica carattere del client sotto forma di stringa. La stringa può essere : SQL_ASCII, EUC_JP, EUC_CN, EUC_KR, EUC_TW, UNICODE, MULE_INTERNAL, LATINX (X=1...9), KOI8, WIN, ALT, SJIS, BIG5, WIN1250.
Nota: Questa funzione richiede PHP-4.0.3 o successivi e PostgreSQL-7.0 o successivi. Se libpq è compilata senza il supporto per la codifica multibyte, pg_set_client_encoding() restituisce sempre "SQL_ASCII". Le codifiche supportate dipendono dalla versione di PostgreSQL. Consultare il manuale di PostgreSQL per i dettagli sull'abilitazione del supporto della codifica multibyte e sulle codifiche riconosciute.
Questa funzione si chiamava pg_clientencoding().
Vedere anche pg_set_client_encoding().
pg_close() chiude la connessione non persistente verso un database PostgreSQL, identificata dalla risorsa connessione. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: iL'uso di pg_close() non è normalmente necessario, dal momento che le connessioni non persistenti vengono chiuse automaticamente alla fine dell'esecuzione dello script.
Se c'è una risorsa large object aperta sulla connessione, non chiudere quest'ultima finché la risorsa non è stata chiusa a sua volta.
pg_connect() restituisce una risorsa di connessione necessaria per l'utilizzo delle altre funzioni PostgreSQL.
pg_connect() stabilisce una connessione a un database PostgreSQL specificato da stringa_connessione. Restituisce una risorsa di connessione in caso di successo. Restituisce FALSE, se la connessione non può essere stabilita. stringa_connessione dovrebbe essere una stringa racchiusa tra apici.
Esempio 1. Uso di pg_connect
|
Se viene eseguita una seconda chiamata a pg_connect() con stessi argomenti nella stringa_connessione, non viene stabilita una nuova connessione, bensì viene restituita la risorsa che punta alla connessione già aperta. Si possono avere connessioni multiple allo stesso database se si usano stringhe di connessione differenti.
La sintassi a parametri multipli: $conn = pg_connect ("host", "port", "options", "tty", "dbname") è deprecata.
Vedere anche pg_pconnect(), pg_close(), pg_host(), pg_port(), pg_tty(), pg_options() e pg_dbname().
pg_connection_busy() restituisce TRUE se la connessione è occupata. In questo caso, la query precedentamente inviata è ancora in esecuzione. Se pg_get_result() viene chiamata, verrà bloccata.
Vedere anche pg_connection_status() e pg_get_result()
pg_connection_reset() ripristina la connessione. È utile per la gestione degli errori. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pg_connect(), pg_pconnect() e pg_connection_status()
pg_connection_status() restituisce lo stato di una connessione. I possibili valori sono PGSQL_CONNECTION_OK e PGSQL_CONNECTION_BAD.
Vedere anche pg_connection_busy().
(PHP 4 >= 4.3.0, PHP 5)
pg_convert -- Converte i valori di un array associativo in una forma compatibile con i comandi SQL.pg_convert() controlla e converte arrayassoc rendendolo compatibile con i comandi SQL.
Nota: Questa funzione è sperimentale.
Vedere anche pg_meta_data()
pg_copy_from() inserisce le tuple in una tabella etraendole dall'array tuple. Utilizza internamente il comando OPY per inserire i record. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche pg_copy_to()
pg_copy_to() copia una tabella in un array. Internamente utilizza il comando SQL COPY TO per inserire le tuple. Restituisce l'array risultante. Restituisce FALSE in caso di errore.
Vedere anche pg_copy_from()
pg_dbname() restituisce il nome del database associato alla risorsa connessione Restituisce FALSE, if connessione non è una valida risorsa di connessione PostgreSQL.
pg_delete() cancella le tuple indicate dalle condizioni specificate da arrayassoc composto da campo=>valore. Se opzioni è specificato, pg_convert() viene applicata a arrayassoc con l'opzione data.
Esempio 1. pg_delete
|
Nota: Questa funzione è sperimentale.
Vedere anche pg_convert()
pg_end_copy() sincronizza il frontend PostgreSQL (normalmente un processo del server web) con il server PostgreSQL dopo aver eseguito una operazione di copia attraverso pg_put_line(). pg_end_copy() deve essere invocato, altrimenti il server PostgreSQL può rimanere fuori sincronizzazione con il frontend e restituire un errore. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Per ulteriori dettagli ed esempio, vedere anche pg_put_line().
(PHP 4 >= 4.2.0, PHP 5)
pg_escape_bytea -- Aggiunge le sequenze di escape ai dati binari nel tipo byteapg_escape_bytea() aggiunge le sequenze di escape nei dati di tipo bytea. Restituisce una stringa con le sequenze.
Nota: Quando si esegue una SELECT su un tipo bytea, PostgreSQL restituisce dei byte formattati in ottale e con il prefisso \ (es. \032). Agli utenti è lasciato il compito di convertire questi valori in formato binario.
Questa funzione richiede una versione di PostgreSQL pari o superiore alla 7.2. Con PostgreSQL 7.2.0 e 7.2.1, il tipo bytea richiede un cast quando si abilita il supporto multi-byte. Es. INSERT INTO tabella (immagine) VALUES ('$immagine_con_escape'::bytea); PostgreSQL 7.2.2 e successivi non necessitano del cast. L'eccezione è che quando le codifiche di carattere del client e del backend non corrispondono, ci possono essere errori del flusso multi-byte. L'utente deve effettuare un cast a bytea per evitare questo errore.
Le nuove versioni di PostgreSQL avranno il supporto per la funzione di unescape. Il supporto per la funzione unescape verrà aggiunto non appena disponibile.
See also pg_escape_string()
pg_escape_string() aggiunge le sequenze di escape alle stringhe di tipo text/char. Restituisce la stringa modificata con le sequenze per PostgreSQL. L'uso di questa funzione è raccomandato al posto di addslashes().
Nota: Questa funzione richiede PostgreSQL 7.2 o successivi.
Vedere anche pg_escape_bytea()
(PHP 5 >= 5.1.0RC1)
pg_execute -- Sends a request to execute a prepared statement with given parameters, and waits for the result.Sends a request to execute a prepared statement with given parameters, and waits for the result.
pg_execute() is like pg_query_params(), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. The statement must have been prepared previously in the current session. pg_execute() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.
The parameters are identical to pg_query_params(), except that the name of a prepared statement is given instead of a query string.
PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().
The name of the prepared statement to execute. if "" is specified, then the unnamed statement is executed. The name must have been previously prepared using pg_prepare(), pg_send_prepare() or a PREPARE SQL command.
An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.
Esempio 1. Using pg_execute()
|
(PHP 5 >= 5.1.0RC1)
pg_fetch_all_columns -- Fetches all rows in a particular result column as an arraypg_fetch_all_columns() returns an array that contains all rows (records) in a particular column of the result resource.
Nota: This function sets NULL fields to PHP NULL value.
PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
Column number, zero-based, to be retrieved from the result resource. Defaults to the first column if not specified.
An array with all values in the result column.
FALSE is returned if column is larger than the number of columns in the result, or on any other error.
Esempio 1. pg_fetch_all_columns() example
|
pg_fetch_all() restituisce un array che contiene tutte le tuple (righe/record) contenuti nella risorsa risultato. Restituisce FALSE se non ci sono tuple.
Vedere anche pg_fetch_row(), pg_fetch_array(), pg_fetch_object() e pg_fetch_result().
Esempio 1. PostgreSQL fetch array
|
pg_fetch_array() restituisce un array che corrisponde alla riga caricata (tuple/record). Restituisce FALSE se non ci sono più righe.
pg_fetch_array() è una versione estesa di pg_fetch_row(). Oltre a salvare i dati in un array con indici numerici, li salva pure in un array associativo, utilizzando i nomi dei campi come chiave.
tupla è il numero della riga (record) che deve essere caricata. La prima riga è la 0.
tipo_risultato è un parametro opzionale che controlla come il risultato viene restituito. result_type è una costante e può assumere i seguenti valori: PGSQL_ASSOC, PGSQL_NUM, e PGSQL_BOTH. pg_fetch_array() restituisce un array associativo con il nome del campo come chiave con PGSQL_ASSOC, oppure l'indice del campo con PGSQL_NUM o entrambi con PGSQL_BOTH. Il default è PGSQL_BOTH.
Nota: tipo_risultato è stato aggiunto nel PHP 4.0.
pg_fetch_array() NON è più lento di pg_fetch_row(), inoltre è più facile da usare.
Esempio 1. PostgreSQL fetch array
|
Vedere anche pg_fetch_row(), pg_fetch_object() e pg_fetch_result().
Nota: Dalla versione 4.1.0, tupla è opzionale. La chiamata a pg_fetch_array() incrementa di 1 il puntatore alle tuple.
pg_fetch_assoc() returns an associative array that corresponds to the fetched row (tuples/records). It returns FALSE, if there are no more rows.
pg_fetch_assoc() is an extended version of pg_fetch_row(). In addition to storing the data in the numeric indices (field index) to the result array, it also stores the data in associative indices (field name) by default.
row is row (record) number to be retrieved. First row is 0.
pg_fetch_assoc() is NOT significantly slower than using pg_fetch_row(), while it provides a significant ease of use.
See also pg_fetch_row(), pg_fetch_array(), pg_fetch_assoc(), pg_fetch_object() and pg_fetch_result().
Esempio 1. PostgreSQL fetch array
|
pg_fetch_object() restituisce un oggetto avente le proprietà che corrispondono alla tupla scaricata. Restituisce FALSE se non ci sono più tuple o in caso di errore.
pg_fetch_object() è simile a pg_fetch_array(), con una differenza - viene restituito un oggetto invece che un array. Indirettamente, questo significa che si può accedere ai dati solo attraverso i nomi dei campi, e non attraverso i loro indici numerici (i nomi delle proprietà non possono essere numeri).
tupla è il numero della riga (record) da caricare. La prima tupla è la numero 0.
Per quanto riguarda la velocità di esecuzione, questa funzione è identica a pg_fetch_array(), ed è veloce quasi quanto pg_fetch_row() (la differenza è trascurabile).
Nota: Dalla versione 4.1.0, tupla è opzionale.
Dalla versione 4.3.0, tipo_risultato è di default a PGSQL_ASSOC mentre il default delle versioni precedenti era PGSQL_BOTH. La proprietà numerica è inutile, dal momento che un nome di proprietà numerico non è valido in PHP.
tipo_risultato potrebbe essere abbandonato nelle versioni future.
Esempio 1. Postgres fetch object
|
Vedere anche pg_query(), pg_fetch_array(), pg_fetch_row() e pg_fetch_result().
Nota: Dalla versione 4.1.0, row è diventato opzionale. La chiamata alla pg_fetch_object() incrementa di 1 il contatore di riga interno.
pg_fetch_result() restituisce i valori da una risorsa risultato ottenuta mediante pg_query(). tupla è un intero. campo è il nome del campo (stringa) o l'indice del campo (intero). I parametri tupla e campo indicano quale cella nella tabella risultante va restituita. La numerazione delle tuple parte da 0. Invece di indicare il nome del campo, si può usare l'indice del campo sotto forma di numero senza virgolette. Gli indici dei campo partono da 0.
PostgreSQL ha molti tipi di dato e solo quelli più usati sono supportati direttamente da questa funzione. Tutti gli integer, sono restituiti come valori integer. Tutti i float, e i tipi real sono restituiti come valori float. Boolean è restituito come "t" o "f". Tutti gli altri tipi, compresi gli array, sono restituiti come stringhe formattate nello stesso modo di default che si puo vedere nel programma psql.
pg_fetch_row() carica un record dal risultato della query associato alla risorsa identificata da result. La riga (record) è restituia sotto form di array. Ogni campo è identificato da un indice numerico, che inizia da 0.
Restituisce un array che corrisponde alla riga caricata, oppure FALSE se non ci sono altre tuple.
Esempio 1. Postgres fetch row
|
Vedere anche pg_query(), pg_fetch_array(), pg_fetch_object() e pg_fetch_result().
Nota: Dalla versione 4.1.0, row è opzionale. La chiamata a pg_fetch_row() incrementa il puntatore alle tuple di 1.
pg_field_is_null() controlla se un campo è NULL o meno. Restituisce se il campo nella tupla data è NULL. Restituisce 0 se il campo nella tupla NON è NULL. Il campo può essere specificato con un indice di colonna (numero) o come un nome di campo (stringa). La numerazione comincia da 0.
Nota: Questa funzione si chiamava g_fieldisnull().
pg_field_name() restituisce il nome del campo che occupa la posizione indicata da numero_campo, rispetto alla risorsa risultato. La numerazione dei campi parte da 0.
Nota: Questa funzione si chiamava pg_fieldname().
Vedere anche pg_field_num().
pg_field_num() restituisce il numero della colonna che corrisponde al campo nome_campo nella risorsa PostgreSQL risultato spacificata. La numerazione dei campi parte da 0. Questa funzione restituisce -1 in caso di errore.
Nota: Questa funzione si chiamava pg_fieldnum().
Vedere anche pg_field_name().
pg_field_prtlen() restituisce la reale lunghezza (numero di caratteri) di uno specifico valore in un risultato di PostgreSQL. La numerazione delle tuple parte da 0. Questa funzione restituisce -1 in caso di errore.
Nota: Questa funzione si chiamava pg_field_prtlen().
Vedere anche pg_field_size().
pg_field_size() restituisce la dimensione di memorizzazione (in bytes) del campo indicato all'interno di risultato. La numerazione dei campi comincia da 0. Una dimension del campo di -1 indica un campo a lunghezza variabile. Questa funzione restituisce FALSE in caso di errore.
Nota: Questa funzione si chiamava pg_fieldsize().
Vedere anche pg_field_prtlen() e pg_field_type().
(PHP 5 >= 5.1.0RC1)
pg_field_type_oid -- Returns the type ID (OID) for the corresponding field numberpg_field_type_oid() returns an integer containing the OID of the base type of the given field_number in the given PostgreSQL result resource.
You can get more information about the field type by querying PostgreSQL's pg_type system table using the OID obtained with this function. The PostgreSQL format_type() function will convert a type OID into an SQL standard type name.
Nota: If the field uses a PostgreSQL domain (rather than a basic type), it is the OID of the domain's underlying type that is returned, rather than the OID of the domain itself.
PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
Field number, starting from 0.
Esempio 1. Getting information about fields
Il precedente esempio visualizzerà:
|
pg_field_type() restituisce una stringa contenente il nome del tipo del campo specificato da numero_campo nella risorsa PostgreSQL specificata da risultato. La numerazione dei campi comincia da 0.
Nota: Questa funzione si chiamava pg_fieldtype().
Vedere anche pg_field_prtlen() e pg_field_name().
pg_free_result() deve essere chiamata solo se si è preoccupati di aver usato troppa memoria durante l'esecuzione dello script. Normalmente tutte le aree di memoria allocate per i risultati sono automaticamente deallocate alla fine dell'esecuzione. Se invece si è sicuri di non dover più utilizzare i dati del risultato, è possibile chiamare pg_free_result() con la risorsa result come argomento e la memoria associata verrà liberata. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Questa funzione si chiamava pg_freeresult().
See also pg_query().
pg_get_notify() gets notify message sent by NOTIFY SQL command. To recieve nofigy messages, LISTEN SQL command must be issued. If there is notify message on the connection, array contains message name and backend PID is returned. If there is no message, FALSE is returned.
See also pg_get_pid()
Esempio 1. PostgreSQL NOTIFY message
|
pg_get_pid() gets backend (database server process) PID. PID is useful to check if NOTIFY message is sent from other process or not.
See also pg_get_notify()
pg_get_result() estrae la risorsa risultato dalle query asincrone eseguite da pg_send_query(). pg_send_query() può inviare query multiple al server PostgreSQL server e pg_get_result() è utilizzat per recuperare i risultati uno ad uno. Restituisce la risorsa risultato. Se non ci sono più risultati, restituisce FALSE.
pg_host() restituisce il nome dell'host a cui la risorsa PostgreSQL connessione è connessa.
Vedere anche pg_connect() e pg_pconnect().
pg_insert() inserisce array_assoc composto da campo=>valore nella tabella specificata da nome_tabella. Se opzioni è specificato, pg_convert() è eseguita su array_assoc con le opzioni date.
Nota: Questa funzione è sperimentale.
Vedere anche pg_convert()
pg_last_error() restituisce l'ultimo messaggio di errore della connessione specificata.
I messaggi di errore possono essere sovrascritti da chiamate a funzioni interne a PostgreSQL(libpq). Quindi questa funzione potrebbe non restituire il messaggio di errore corretto, se più errori si sono verificati in una funzione interna di PostgreSQL.
Utilizzare pg_result_error(), pg_result_status() e pg_connection_status() per una migliore gestione degli errori.
Nota: Questa funzione si chiamava pg_errormessage().
Vedere anche pg_result_error().
(PHP 4 >= 4.0.6, PHP 5)
pg_last_notice -- Restituisce l'ultimo messaggio di notifica dal server PostgreSQLpg_last_notice() restituisce l'ultimo messaggio di notifica emesso dal server PostgreSQL specificato dal parametro connessione. Il server PostgreSQL invia messaggi di notifica in parecchi case, per esempio se le transazioni non possono essere continuate. Con pg_last_notice() è possibile evitare di eseguire query inutili, controllando se la notifica è relativa alla transazione o meno.
Avvertimento |
Questa funzione è SPERIMENTALE e non è completamente implementata allo stato attuale. pg_last_notice() è stato aggiunta nel PHP 4.0.6. Comunque, il PHP 4.0.6 ha dei problemi con la manipolazione dei messaggi di notifica. L'uso del modulo PostgreSQL con il PHP 4.0.6 non è raccomandato anche se non si fa uso di pg_last_notice(). Questa funzione è completamente implementata in PP 4.3.0. Le versioni di PHP precedenti alla 4.3.0 ignorano il parametro di connessione al database. |
Il tracciamento dei messaggi di notifica può essere reso opzionale impostando a 1 la variabile pgsql.ignore_notice nel file php.ini a partire dal PHP 4.3.0.
Il log dei messaggi di notifica può essere reso opzionale impostando a 0 la variabile pgsql.log_notice nel file php.ini a partire dal PHP 4.3.0. A meno che pgsql.ignore_notice sia impostato a 0, i messaggi di notifica non possono essere registrati.
See also pg_query() e pg_last_error().
pg_last_oid() è utilizzato per recuperare l'oid assegnato ad una tupla inserita (record), se la risorsa risultato deriva dall'ultimo comando inviato attraverso pg_query(), e se quest'ultimo è un SQL INSERT. Restituisce un intero positivo se esiste un oid valido. Restituisce invece FALSE in caso di errore o se l'ultimo comnado inviato da pg_query() non era un INSERT, oppure se l'INSERT ha fallito.
Il campo OID è diventato opzionale dal PostgreSQL 7.2. Quando il campo OID non è definito in una tabella, il programmatore deve utilizzare pg_result_status() per controllare se il record è stato inserito con successo.
Nota: Questa funzione si chiamava pg_getlastoid().
Vedere anche pg_query() e pg_result_status()
pg_lo_close() chiude un Large Object. large_object è una risorsa large object ottenuta attraverso pg_lo_open().
Per utilizzare l'interfaccia large object (lo), è necessario includere la chiamata in un blocco di transazione.
Nota: Questa funzione si chiamava pg_loclose().
Vedere anche pg_lo_open(), pg_lo_create() e pg_lo_import().
pg_lo_create() crea un Large Object e restituisce l'oid dello stesso. connessione specifica una connessione valida al database aperta da pg_connect() o pg_pconnect(). I modi di accesso di PostgreSQL INV_READ, INV_WRITE e INV_ARCHIVE non sono supportati, l'oggetto è sempre creato con accesso sia in lettura che in scrittura. INV_ARCHIVE è stato rimosso da PostgreSQL (versioni 6.3 e successive). La funzione restituisce l'oid del large object, altrimenti restituisce FALSE in caso di errore.
Per utilizzare l'interfaccia large object (lo) è necessario includerla in un blocco di transazione.
Nota: Questa funzione si chiamava pg_locreate().
L'argomento oid specifica l'oid del large object da salvare e l'argomento percorso specifica il percorso del file. Restituisce FALSE in caso di errore, TRUE altrimenti.
Per utilizzare l'interfaccia large object (lo), occorre includere il comando in un blocco di transazione.
Nota: Questa funzione si chiamava pg_loexport().
Vedere anche pg_lo_import().
Nelle versioni precedenti al PHP 4.2.0 la sintassi di questa funzione era differente, come nella seguente definizione:
int pg_lo_import ( string percorso [, resource connessione] )Il parametro percorso specifica il percorso del file che deve essere importato nel large object. Restituisce FALSE in caso di errore, altrimenti l'oid del large object appena creato.
Per utilizzare l'interfaccia large object (lo), occorre includere il comando in un blocco di transazione.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Nota: Questa fuinzione si chiamava pg_loimport().
Vedere anche pg_lo_export() e pg_lo_open().
pg_lo_open() apre un Large Object e restituisce una risorsa (riferimento) large object. La risorsa incapsula le informazioni sulla connessione. oid specifica un oid valido di un large object e modo può essere "r", "w", o "rw". Restituisce FALSE se avviene un errore.
Avvertimento |
Non chiudere la connessione al database prima di aver chiuso il large object. |
Per utilizzare l'interfaccia large object (lo), occorre includere il comando in un blocco di transazione.
Nota: Questa funzione si chiamava pg_loopen().
Vedere anche pg_lo_close() e pg_lo_create().
(PHP 4 >= 4.2.0, PHP 5)
pg_lo_read_all -- Legge interamente un large object e lo manda direttamente al browserpg_lo_read_all() legge un large object e lo passa direttamente al browser dopo aver inviato tutti gli header in attesa. È pensata principalmente per inviare dati binari, come immagini o suoni. Restituisce il numero di byte letti. Restituisce FALSE in caso di errore.
Per utilizzare l'interfaccia large object (lo), occorre includere il comando in un blocco di transazione.
Nota: Questa funzione si chiamava pg_loreadall().
Vedere anche pg_lo_read().
pg_lo_read() legge al massimo lung byte da un large object e li restituisce sotto forma di stringa. large_object specifica una risorsa large object valida e lung specifica la lunghezza massima accettabile del segmento del large object. Restituisce FALSE in caso di errore.
Per utilizzare l'interfaccia large object (lo), occorre includere il comando in un blocco di transazione.
Nota: Questa funzione si chiamava pg_loread().
Vedere anche pg_lo_read_all().
pg_lo_seek() ricerca la posizione di un large object. whence è PGSQL_SEEK_SET, PGSQL_SEEK_CUR o PGSQL_SEEK_END.
Vedere anche pg_lo_tell().
pg_lo_tell() restituisce la posizione attuale (offset dall'inizio di un large object).
Vedere anche pg_lo_seek().
pg_lo_unlink() cancella un large object identificato da oid. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Per utilizzare l'interfaccia large object (lo), occorre includere il comando in un blocco di transazione.
Nota: Questa funzione si chiamava pg_lo_unlink().
Vedere anche pg_lo_create() e pg_lo_import().
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.
Looks up a current parameter setting of the server.
Certain parameter values are reported by the server automatically at connection startup or whenever their values change. pg_parameter_status() can be used to interrogate these settings. It returns the current value of a parameter if known, or FALSE if the parameter is not known.
Parameters reported as of PostgreSQL 8.0 include server_version, server_encoding, client_encoding, is_superuser, session_authorization, DateStyle, TimeZone, and integer_datetimes. (server_encoding, TimeZone, and integer_datetimes were not reported by releases before 8.0.) Note that server_version, server_encoding and integer_datetimes cannot change after PostgreSQL startup.
PostgreSQL 7.3 or lower servers do not report parameter settings, pg_parameter_status() includes logic to obtain values for server_version and client_encoding anyway. Applications are encouraged to use pg_parameter_status() rather than ad hoc code to determine these values.
Attenzione |
On a pre-7.4 PostgreSQL server, changing client_encoding via SET after connection startup will not be reflected by pg_parameter_status(). |
PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().
Possible param_name values include server_version, server_encoding, client_encoding, is_superuser, session_authorization, DateStyle, TimeZone, and integer_datetimes.
A string containing the value of the parameter, FALSE on failure or invalid param_name.
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.
(PHP 5 >= 5.1.0RC1)
pg_prepare -- Submits a request to create a prepared statement with the given parameters, and waits for completion.pg_prepare() creates a prepared statement for later execution with pg_execute() or pg_send_execute(). This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. pg_prepare() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.
The function creates a prepared statement named stmtname from the query string, which must contain a single SQL command. stmtname may be "" to create an unnamed statement, in which case any pre-existing unnamed statement is automatically replaced; otherwise it is an error if the statement name is already defined in the current session. If any parameters are used, they are referred to in the query as $1, $2, etc.
Prepared statements for use with pg_prepare() can also be created by executing SQL PREPARE statements. (But pg_prepare() is more flexible since it does not require parameter types to be pre-specified.) Also, although there is no PHP function for deleting a prepared statement, the SQL DEALLOCATE statement can be used for that purpose.
PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().
The name to give the prepared statement. Must be unique per-connection. If "" is specified, then an unnamed statement is created, overwriting any previously defined unnamed statement.
The parameterised SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.
Esempio 1. Using pg_prepare()
|
pg_put_line() invia una stringa terminata da NULL al backend PostgreSQL. Ciò è utile, per esempio, per l'inserimento ad alta velocità di dati in una tabella, iniziato mediante l'invocazione di una operazione di copia. Il carattere NULL finale è aggiunto automaticamente. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: L'applicazione deve explicitamente inviare i due caratteri "\." sull'ultima riga, ad indicare al backend il termine dell'invio dei dati.
Vedere anche pg_end_copy().
Esempio 1. Inserimento ad alta velocità dai dati in una tabella
|
(PHP 5 >= 5.1.0RC1)
pg_query_params -- Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.
pg_query_params() is like pg_query(), but offers additional functionality: parameter values can be specified separately from the command string proper. pg_query_params() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.
If parameters are used, they are referred to in the query string as $1, $2, etc. params specifies the actual values of the parameters. A NULL value in this array means the corresponding parameter is SQL NULL.
The primary advantage of pg_query_params() over pg_query() is that parameter values may be separated from the query string, thus avoiding the need for tedious and error-prone quoting and escaping. Unlike pg_query(), pg_query_params() allows at most one SQL command in the given string. (There can be semicolons in it, but not more than one nonempty command.)
PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().
The parameterised SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.
An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.
Esempio 1. Using pg_query_params()
|
pg_query() restituisce un risorsa risultato della query se è stato possibile eseguire quest'ultima. Retituisce FALSE in caso di errore o se la connessione non è valida. I dettagli dell'errore si possono recuperare utilizzando la funzione pg_last_error() se la connessione è valida. pg_last_error() invia un comando SQL al database PostgreSQL specificato dalla risorsa connessione. Il parametro connessione deve essere una connessione valida restituita da pg_connect() o pg_pconnect(). Il valore di ritorno di questa funzione è una risorsa risultato che si può usare per accedere ai dati attraverso altre funzioni PostgreSQL come pg_fetch_array().
Nota: connessione è un parametro opzionale di pg_query(). Se connessione non è impostato, viene utilizzata la connessione di default, ovvero l'ultima connessione effettuata con pg_connect() o pg_pconnect().
Anche se connessione può essere omessa, ciò non è raccomandato, dal momento che questo può essere fonte di errori difficili da trovare nello script.
Nota: Questa funzione si chiamava pg_exec(). pg_exec() è ancora disponibile, per ragioni di compatibilità, ma si consiglia agli utenti di usare il nuovo nome.
Vedere anche pg_connect(), pg_pconnect(), pg_fetch_array(), pg_fetch_object(), pg_num_rows() e pg_affected_rows().
pg_result_error_field() returns one of the detailed error message fields associated with result resource. It is only available against a PostgreSQL 7.4 or above server. The error field is specified by the fieldcode.
Because pg_query() and pg_query_params() return FALSE if the query fails, you must use pg_send_query() and pg_get_result() to get the result handle.
If you need to get additional error information from failed pg_query() queries, use pg_set_error_verbosity() and pg_last_error() and then parse the result.
A PostgreSQL query result resource from a previously executed statement.
Possible fieldcode values are: PGSQL_DIAG_SEVERITY, PGSQL_DIAG_SQLSTATE, PGSQL_DIAG_MESSAGE_PRIMARY, PGSQL_DIAG_MESSAGE_DETAIL, PGSQL_DIAG_MESSAGE_HINT, PGSQL_DIAG_STATEMENT_POSITION, PGSQL_DIAG_INTERNAL_POSITION (PostgreSQL 8.0+ only), PGSQL_DIAG_INTERNAL_QUERY (PostgreSQL 8.0+ only), PGSQL_DIAG_CONTEXT, PGSQL_DIAG_SOURCE_FILE, PGSQL_DIAG_SOURCE_LINE or PGSQL_DIAG_SOURCE_FUNCTION.
A string containing the contents of the error field, NULL if the field does not exist or FALSE on failure.
Esempio 1. pg_result_error_field() example
|
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()
(PHP 5 >= 5.1.0RC1)
pg_send_execute -- Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).
This is similar to pg_send_query_params(), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. The function's parameters are handled identically to pg_execute(). Like pg_execute(), it will not work on pre-7.4 versions of PostgreSQL.
PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().
The name of the prepared statement to execute. if "" is specified, then the unnamed statement is executed. The name must have been previously prepared using pg_prepare(), pg_send_prepare() or a PREPARE SQL command.
An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.
Returns TRUE on success, FALSE on failure. Use pg_get_result() to determine the query result.
Esempio 1. Using pg_send_execute()
|
(PHP 5 >= 5.1.0RC1)
pg_send_prepare -- Sends a request to create a prepared statement with the given parameters, without waiting for completion.Sends a request to create a prepared statement with the given parameters, without waiting for completion.
This is an asynchronous version of pg_prepare(): it returns TRUE if it was able to dispatch the request, and FALSE if not. After a successful call, call pg_get_result() to determine whether the server successfully created the prepared statement. The function's parameters are handled identically to pg_prepare(). Like pg_prepare(), it will not work on pre-7.4 versions of PostgreSQL.
PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().
The name to give the prepared statement. Must be unique per-connection. If "" is specified, then an unnamed statement is created, overwriting any previously defined unnamed statement.
The parameterised SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.
Returns TRUE on success, FALSE on failure. Use pg_get_result() to determine the query result.
Esempio 1. Using pg_send_prepare()
|
(PHP 5 >= 5.1.0RC1)
pg_send_query_params -- Submits a command and separate parameters to the server without waiting for the result(s).Submits a command and separate parameters to the server without waiting for the result(s).
This is equivalent to pg_send_query() except that query parameters can be specified separately from the query string. The function's parameters are handled identically to pg_query_params(). Like pg_query_params(), it will not work on pre-7.4 PostgreSQL connections, and it allows only one command in the query string.
PostgreSQL database connection resource.
The parameterised SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.
An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Use pg_get_result() to determine the query result.
Esempio 1. Using pg_send_query_params()
|
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().
(PHP 5 >= 5.1.0RC1)
pg_set_error_verbosity -- Determines the verbosity of messages returned by pg_last_error() and pg_result_error().Determines the verbosity of messages returned by pg_last_error() and pg_result_error().
pg_set_error_verbosity() sets the verbosity mode, returning the connection's previous setting. In PGSQL_ERRORS_TERSE mode, returned messages include severity, primary text, and position only; this will normally fit on a single line. The default mode (PGSQL_ERRORS_DEFAULT) produces messages that include the above plus any detail, hint, or context fields (these may span multiple lines). The PGSQL_ERRORS_VERBOSE mode includes all available fields. Changing the verbosity does not affect the messages available from already-existing result objects, only subsequently-created ones.
PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().
The required verbosity: PGSQL_ERRORS_TERSE, PGSQL_ERRORS_DEFAULT or PGSQL_ERRORS_VERBOSE.
The previous verbosity level: PGSQL_ERRORS_TERSE, PGSQL_ERRORS_DEFAULT or PGSQL_ERRORS_VERBOSE.
Esempio 1. pg_set_error_verbosity() example
|
pg_trace() abilita il tracciamento di una comunicazione frontend/backend PostgreSQL verso un file di debug specificato da percorsofile. Per riuscire a capire i risultati, occorre conoscere bene i dettagli del protocollo di comunicazione di PostgreSQL. Per chi non ne è a conoscenza, può sempre essere utile per tracciare gli errori nelle query mandate al server; ad esempio si può eseguire grep '^To backend' trace.log e vedere quale query è stata realmente inviata al server PostgreSQL. Per ulteriori informazioni, consultare il manuale di PostgreSQL.
percorsofile e modo sono gli stessi parametri di fopen() (mode ha come default 'w'), connession specifica la connessione da tracciare ed ha come default l'ultima aperta.
pg_trace() rRestituisce TRUE se percorsofile è stato apertoo in scrittura per il log, altrimenti FALSE.
(PHP 5 >= 5.1.0RC1)
pg_transaction_status -- Returns the current in-transaction status of the server.Returns the current in-transaction status of the server.
Attenzione |
pg_transaction_status() will give incorrect results when using a PostgreSQL 7.3 server that has the parameter autocommit set to off. The server-side autocommit feature has been deprecated and does not exist in later server versions. |
The status can be PGSQL_TRANSACTION_IDLE (currently idle), PGSQL_TRANSACTION_ACTIVE (a command is in progress), PGSQL_TRANSACTION_INTRANS (idle, in a valid transaction block), or PGSQL_TRANSACTION_INERROR (idle, in a failed transaction block). PGSQL_TRANSACTION_UNKNOWN is reported if the connection is bad. PGSQL_TRANSACTION_ACTIVE is reported only when a query has been sent to the server and not yet completed.
Esempio 1. pg_transaction_status() example
|
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()
pg_version() returns an array with the client, protocol and server version. Protocol and server versions are only avaliable if PHP was compiled with PostgreSQL 7.4 or later.
For more detailed server information, use pg_parameter_status().
PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().
Returns an array with client, protocol and server_version keys and values (if available). Returns FALSE on error or invalid connection.
PDO_PGSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to PostgreSQL databases.
The PDO_PGSQL Data Source Name (DSN) is composed of the following elements, delimited by spaces:
The DSN prefix is pgsql:.
The hostname on which the database server resides.
The port on which the database server is running.
The name of the database.
The name of the user for the connection. If you specify the user name in the DSN, PDO ignores the value of the user name argument in the PDO constructor.
The password of the user for the connection. If you specify the password in the DSN, PDO ignores the value of the password argument in the PDO constructor.
Queste funzioni sono disponibili solo nei sistemi Windows 9.x, ME, NT4 e 2000. Sono state aggiunte in PHP 4.0.4.
Questo modulo PECL non viene incluso nel rilascio di PHP.
Per potere utilizzare queste funzioni, gli utenti Windows dovranno abilitare php_printer.dll nel php.ini. You may obtain this unbundled PECL extension from the various PECL snaps pages (select the appropriate repository for your version of PHP): PECL for PHP 4.3.x, PECL for PHP 5.0.x or PECL Unstable.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Parametri di configurazione per il modulo stampante
Nome | Default | Modificabile | Variazioni |
---|---|---|---|
printer.default_printer | "" | PHP_INI_ALL |
La funzione cancella lo spool di stampa dalla stampante.
Il parametro handle deve indicare un handle valido di stampante.
Questa funzione chiude la connessione verso una stampante. Inoltre, la funzione printer_close() chiude il device context attivo.
Il parametro handle deve indicare un handle valido di stampante.
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()
|
La funzione traccia un rettangolo con gli angoli arrotondati.
Il parametro handle deve indicare un handle valido di stampante.
ul_x indica la coordinata x dell'angolo in alto a sinistra del rettangolo.
ul_y indica la coordinata y dell'angolo in alto a sinistra del rettangolo.
lr_x indica la coordinata x dell'angolo in basso a destra del rettangolo.
lr_y indica la coordinata y dell'angolo in basso a destra del rettangolo.
width indica la larghezza dell'ellisse.
height indica l'altezza dell'ellisse.
Esempio 1. Esempio di utilizzo di printer_draw_roundrect()
|
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.
La funzione recupera il valore di configurazione per il parametro opzione. Il parametro handle deve indicare un handle valido di stampante. Vedere la funzione printer_set_option() per avere l'elenco dei parametri che sono disponibili; in aggiunta possono essere recuperate le informazioni sui parametri:
PRINTER_DEVICENAME restituisce il nome della device della stampante.
PRINTER_DRIVERVERSION restituisce la versione del driver della stampante.
La funzione elenca le stampanti disponibili e le loro capacità. Il parametro livello indica il livello delle informazioni richieste. I livelli possono essere 1,2,4 o 5. Il parametro enumtype deve essere valorizzato con una delle seguenti costanti:
PRINTER_ENUM_LOCAL: elenca le stampanti installate localmente.
PRINTER_ENUM_NAME: elenca le stampanti installate su nome, che può indicare un server, un dominio, un printer server.
PRINTER_ENUM_SHARED: questo parametro non può essere utilizzato da solo, è necessario aggiungerlo in OR ad uno degli altri, ad esempio PRINTER_ENUM_LOCAL per rilevare le stampanti locali condivise.
PRINTER_ENUM_DEFAULT: (solo Win9.x) elenca la stampante di default.
PRINTER_ENUM_CONNECTIONS: (solo WinNT/2000) elenca le stampanti che l'utente può utilizzare.
PRINTER_ENUM_NETWORK: (solo WinNT/2000) elenca le stampanti presenti nel dominio del computer. Opzione valida solo se livello è valorizzato a 1.
PRINTER_ENUM_REMOTE: (solo WinNT/2000) elenca le stampanti di rete ed i printer server presenti nel dominio del computer. Opzione valida solo se livello è valorizzato a 1.
La 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()
|
La funzione valorizza le seguenti opzioni per la connessione corrente. Il parametro handle deve indicare un handle valido di stampante. Per il parametro opzione si può utilizzare una delle seguenti costanti:
PRINTER_COPIES: indica quante copie si debbano stampare, valore deve essere un intero.
PRINTER_MODE: specifica il tipo di dati (text, raw or emf), valore deve essere una stringa.
PRINTER_TITLE: specifica il nome del documento, valore deve essere una stringa.
PRINTER_ORIENTATION: specifica l'orientamento del foglio, valore può essere o PRINTER_ORIENTATION_PORTRAIT o PRINTER_ORIENTATION_LANDSCAPE
PRINTER_RESOLUTION_Y: specifica la risoluzione y in DPI, valore deve essere un intero.
PRINTER_RESOLUTION_X: specifica la risoluzione x in DPI, valore deve essere un intero.
PRINTER_PAPER_FORMAT: specifica il formato predefinito della carta, impostare valore a PRINTER_FORMAT_CUSTOM se si vuole impostare un formato personalizzato con PRINTER_PAPER_WIDTH e PRINTER_PAPER_LENGTH. Il parametro valore può essere una delle seguenti costanti.
PRINTER_FORMAT_CUSTOM: specifica un formato personalizzato.
PRINTER_FORMAT_LETTER: specifica il formato letter (8 1/2- per 11-pollici).
PRINTER_FORMAT_LETTER: specifica il formato legal (8 1/2- per 14-pollici).
PRINTER_FORMAT_A3: specifica il formato A3 (297- per 420-millimetri).
PRINTER_FORMAT_A4: specifica il formato A4 (210- per 297-millimetri).
PRINTER_FORMAT_A5: specifica il formato A5 (148- per 210-millimetri).
PRINTER_FORMAT_B4: specifica il formato B4 (250- per 354-millimetri).
PRINTER_FORMAT_B5: specifica il formato B5 (182- per 257-millimetri).
PRINTER_FORMAT_FOLIO: specifica il formato FOLIO (8 1/2- per 13-pollici).
PRINTER_PAPER_LENGTH: se PRINTER_PAPER_FORMAT è impostato a PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_LENGTH specifica la lunghezza personalizzata in mm, valore deve essere un intero.
PRINTER_PAPER_WIDTH: se PRINTER_PAPER_FORMAT è impostato a PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_WIDTH specifica la larghezza personalizzata in mm, valore deve essere un intero.
PRINTER_SCALE: specifica il fattore per il quale l'output della stampante deve essere dimensionato. La dimensione dalle pagine viene modificata dalla dimensione fisica di un fattore pari a scala/100. Ad esempio se simposta scala a 50, l'output sarà la metà della dimensione originale. Valore deve essere un intero.
PRINTER_BACKGROUND_COLOR: specifica il colore di background per il device context corrente, valore deve essere una stringa contenente il colore in formato RGB esadecimale, ad esempio "005533".
PRINTER_TEXT_COLOR: specifica il colore del testo per il device context corrente, valore deve essere una stringa contenente il colore in formato RGB esadecimale, ad esempio "005533".
PRINTER_TEXT_ALIGN: specifica l'allineamento del testo per il device context corrente, valore può essere la combinazione tramite OR delle seguenti costanti:
PRINTER_TA_BASELINE: il testo sarà allineato alla linea base.
PRINTER_TA_BOTTOM: il testo sarà allineato in basso.
PRINTER_TA_TOP: il testo sarà allineato in alto.
PRINTER_TA_CENTER: il testo sarà centrato.
PRINTER_TA_LEFT: il testo sarà allineato a sinistra.
PRINTER_TA_RIGHT: il testo sarà allineato a destra.
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.
Queste funzioni permettono l'esecuzione di comandi sul sistema stesso, e rendono sicuri tali comandi.
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 funzioni sono anche strettamente correlate al operatore backtick. Inoltre, in modalità sicura occorre tenere conto anche della direttiva safe_mode_exec_dir.
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 escapeshellcmd(), 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:
<?php $e = escapeshellcmd($userinput); // qui non ci preoccupiamo se $e contiene spazi system("echo $e"); $f = escapeshellcmd($filename); // e qui lo facciamo, usando le virgolette system("touch \"/tmp/$f\"; ls -l \"/tmp/$f\""); ?> |
Vedere anche escapeshellarg(), exec(), popen(), system() e l'operatore backtick.
exec() esegue il comando passato da command, la funzione non invia nessun output. Restituisce semplicemente l'ultima linea dal risultato del comando. Se si ha bisogno di eseguire un comando ed avere tutti i dati passati direttamente indietro senza alcuna interferenza, usare la funzione passthru().
Se l'argomento output è presente, allora tale vettore specificato verrà riempito con ogni linea del output del comando. I fine riga, come \nnon sono inclusi in questo array. Notare che se il vettore contiene già degli elementi, exec() li aggiungerà in coda al vettore. Se non si vuole che la funzione aggiunga elementi, eseguire un unset() sul vettore prima di passarlo ad exec().
Se viene passato l'argomento return_var assieme all'argomento output, allora lo stato del comando eseguito verrà scritto in questa variabile.
Avvertimento |
Se si permette di passare a questa funzione i dati provenineti dagli input utente, si dovrebbe utilizzare la funzione escapeshellarg() oppure escapeshellcmd() in modo da essere sicuri che gli utenti non possano compromettere il sistema eseguendo comandi arbitrari. |
Nota: Se si vuole avviare un programma tramite questa funzione e lasciarlo girare in background, occorre essere certi che l output del programma sia rediretto su un file o qualche altro flusso di output altrimenti il PHP sarà sospenderà fino a quando il programma non termina.
Nota: Quando si abilita la modalità sicura, si può eseguire soltanto gli eseguibili presenti nella directory safe_mode_exec_dir. Per motivi pratici, attualmente, non ` permesso avere .. come componente del percorso di un eseguibile.
Avvertimento |
Con la modalità sicura attivata, tutte le parole che seguono il comando iniziale sono trattate come argomenti. Quindi, echo y | echo x diventa echo "y | echo x". |
Vedere anche system(), passthru(), popen(), escapeshellcmd() pcntl_exec() e l'operatore backtick.
La funzione passthru() è simile alla funzione exec() inquanto esegue command. Se il parametro return_var è specificato, lo stato ritornato dal comando Unix verrà posto lì. Questa funzione deve essere usata al posto di exec() o di system() quando l'output del comando Unix consiste in dati binari da passare direttamente al browser. Un suo uso frequente consiste nel eseguire, ad esempio, le utility pbmplus che possono restituire un flusso diretto all'immagine. Impostado il tipo di contenuto a image/gif e successivamente chiamando un programma pbmplus per generare una gif puoi realizzare uno script PHP che genera direttamente immagini.
Avvertimento |
Se si permette di passare a questa funzione i dati provenineti dagli input utente, si dovrebbe utilizzare la funzione escapeshellarg() oppure escapeshellcmd() in modo da essere sicuri che gli utenti non possano compromettere il sistema eseguendo comandi arbitrari. |
Nota: Se si vuole avviare un programma tramite questa funzione e lasciarlo girare in background, occorre essere certi che l output del programma sia rediretto su un file o qualche altro flusso di output altrimenti il PHP sarà sospenderà fino a quando il programma non termina.
Nota: Quando si abilita la modalità sicura, si può eseguire soltanto gli eseguibili presenti nella directory safe_mode_exec_dir. Per motivi pratici, attualmente, non ` permesso avere .. come componente del percorso di un eseguibile.
Avvertimento |
Con la modalità sicura attivata, tutte le parole che seguono il comando iniziale sono trattate come argomenti. Quindi, echo y | echo x diventa echo "y | echo x". |
Vedere anche exec(), system(), popen(), escapeshellcmd(), e l'operatore backtick.
(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().
An array of collected information on success, and FALSE on failure. The returned array contains 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) |
proc_nice() changes the priority of the current process by the amount specified in increment. A positive increment will lower the priority of the current process, whereas a negative increment will raise the priority.
proc_nice() is not related to proc_open() and its associated functions in any way.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. If an error occurs, like the user lacks permission to change the priority, an error of level E_WARNING is also generated.
Availability: proc_nice() will only exist if your system has 'nice' capabilities. 'nice' conforms to: SVr4, SVID EXT, AT&T, X/OPEN, BSD 4.3. This means that proc_nice() is not available on Windows.
proc_open() is similar to popen() but provides a much greater degree of control over the program execution.
PHP 5 introduces pty support for systems with Unix98 ptys. This allows your script to interact with applications that expect to be talking to a terminal. A pty works like a pipe, but is bi-directional, so there is no need to specify a read/write mode. The example below shows how to use a pty; note that you don't have to have all descriptors talking to a pty. Also note that only one pty is created, even though pty is specified 3 times. In a future version of PHP, it might be possible to do more than just read and write to the pty.
The command to execute
An indexed array where the key represents the descriptor number and the value represents how PHP will pass that descriptor to the child process. 0 is stdin, 1 is stdout, while 2 is stderr.
The currently supported pipe types are file, pipe and pty.
The file descriptor numbers are not limited to 0, 1 and 2 - you may specify any valid file descriptor number and it will be passed to the child process. This allows your script to interoperate with other scripts that run as "co-processes". In particular, this is useful for passing passphrases to programs like PGP, GPG and openssl in a more secure manner. It is also useful for reading status information provided by those programs on auxiliary file descriptors.
Will be set to an indexed array of file pointers that correspond to PHP's end of any pipes that are created.
The initial working dir for the command. This must be an absolute directory path, or NULL if you want to use the default value (the working dir of the current PHP process)
An array with the environment variables for the command that will be run, or NULL to use the same environment as the current PHP process
Allows you to specify additional options. Currently only suppress_errors is supported, which suppresses errors generated by this function when it's set to TRUE
Returns a resource representing the process, which should be freed using proc_close() when you are finished with it. On failure returns FALSE.
Esempio 1. A proc_open() example
Il precedente esempio visualizzerà qualcosa simile a:
|
Esempio 2. ptys usage
|
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.
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.
(PHP 4, PHP 5)
shell_exec -- Esegue un comando attraverso la shell e restituisce l'output completo come stringaQuesta funzione è identica all'operatore backtick.
Nota: Questa funzione è disabilitata nella modalitàsafe-mode
Vedere anche exec() e escapeshellcmd().
system() è semplicemente come la versione C della funzione che esegue il command dato e restituisce in uscita il risultato. Se viene fornita una variabile come secondo argomento, allora il codice di stato ritornato dal comando eseguito verrà scritto in tale variabile.
Avvertimento |
Se si permette di passare a questa funzione i dati provenineti dagli input utente, si dovrebbe utilizzare la funzione escapeshellarg() oppure escapeshellcmd() in modo da essere sicuri che gli utenti non possano compromettere il sistema eseguendo comandi arbitrari. |
Nota: Se si vuole avviare un programma tramite questa funzione e lasciarlo girare in background, occorre essere certi che l output del programma sia rediretto su un file o qualche altro flusso di output altrimenti il PHP sarà sospenderà fino a quando il programma non termina.
La chiamata a system() tenta anche di ripulire automaticamente il buffer di output del web server dopo ogni linea di output se PHP gira come un modulo server.
Restituisce l'ultima linea del output del comando se ha successo e FALSE se fallisce.
Se devi eseguire un comando ottenendo tutti i dati restituiti dal comando direttamente senza alcuna interferenza, usa la funzione passthru().
Esempio 1. system() example
|
Nota: Quando si abilita la modalità sicura, si può eseguire soltanto gli eseguibili presenti nella directory safe_mode_exec_dir. Per motivi pratici, attualmente, non ` permesso avere .. come componente del percorso di un eseguibile.
Avvertimento |
Con la modalità sicura attivata, tutte le parole che seguono il comando iniziale sono trattate come argomenti. Quindi, echo y | echo x diventa echo "y | echo x". |
Vedere anche exec(), passthru(), popen(), escapeshellcmd(), pcntl_exec(), e l'operatore backtick.
This module allows to create PostScript documents. It has many similarities with the pdf extension. Actually the API is almost identical and one can in many cases just replace the prefix of each function from pdf_ to ps_. This also works for functions which has no meaning in the PostScript document (like adding hyperlinks) but will have an effect if the document is converted to PDF.
Documents created by this extension are sometimes even superior to documents created with the pdf extension, because pslib's text rendering functions can handle kerning, hyphenation and ligatures which results in much better output of boxed text.
You need at least PHP 4.3.0 and pslib >= 0.1.12. The ps library (pslib) is available at http://pslib.sourceforge.net/.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
The following two tables lists all constants defined by the ps extension.
If you have comments, bugfixes, enhancements for either this extension or pslib then please drop me a mail steinm@php.net. Any help is very welcome.
Adds a bookmark for the current page. Bookmarks usually appear in PDF-Viewers left of the page in a hierarchical tree. Clicking on a bookmark will jump to the given page.
The bookmark has no meaning if the document is printed or viewed but it will be used if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.
The parameter parent is another bookmark which is used as the parent of the new bookmark.
If open is unequal to zero the bookmark will be shown open by the pdf viewer.
The returned value is a reference for the bookmark. It is only used if the bookmark shall be used as a parent.
Returns the identifier of the bookmark or zero in case of an error. The identifier is a positive number.
Places a hyperlink at the given position pointing to a file program which is being started when clicked on. The hyperlink start is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.
The hyperlink will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.
Places a hyperlink at the given position pointing to a page in the same document. Clicking on the link will jump to the given page. The first page in a document has number 1.
The hyperlink start is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.
The hyperlink will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.
The parameter dest determines how the document is being viewed. It can be fitpage, fitwidth, fitheight, or fitbbox.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Places a hyperlink at the given position pointing to a second pdf document. Clicking on the link will branch to the document at the given page. The first page in a document has number 1.
The hyperlink start is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.
The hyperlink will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.
The parameter dest determines how the document is being viewed. It can be fitpage, fitwidth, fitheight, or fitbbox.
Places a hyperlink at the given position pointing to a web page. The hyperlink start is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.
The hyperlink will not be visible if the document is printed or viewed but it will show up if the document is converted to pdf by either Acrobat Distiller™ or Ghostview.
Draws a portion of a circle with at middle point at (x, y). The arc starts at an angle of alpha and ends at an angle of beta. It is drawn counterclockwise. The subpath added to the current path starts on the arc at angle alpha and ends on the arc at angle beta.
Draws a portion of a circle with at middle point at (x, y). The arc starts at an angle of alpha and ends at an angle of beta. It is drawn clockwise. The subpath added to the current path starts on the arc at angle beta and ends on the arc at angle alpha.
Starts a new page. Although the parameters width and height imply a different page size for each page, this is not possible in PostScript. The first call of ps_begin_page() will set the page size for the whole document. Consecutive calls will have no effect, except for creating a new page. The situation is different if you intent to convert the PostScript document into PDF. This function places pdfmarks into the document which can set the size for each page indiviually. The resulting PDF document will have different page sizes.
Each page is encapsulated into save/restore. This means, that most of the settings made on one page will not be retained on the next page.
If there is up to the first call of ps_begin_page() no call of ps_findfont(), then the header of the PostScript document will be output and the bounding box will be set to the size of the first page. If ps_findfont() was called before the header has been output already, the document will not have a valid bounding box. In order to prevent this, one should call ps_set_info() to set the info field BoundingBox and possibly Orientation before any ps_findfont() or ps_begin_page() calls.
Starts a new pattern.
Starts a new template.
Draws a circle with its middle point at (x, y). The circle starts and ends at position (x+radius, y). If this function is called outside a path it will start a new path. If it is called within a path it will add the circle as a subpath. If the last drawing operation does not end in point (x+radius, y) then there will be a gap in the path.
Takes the current path and uses it to define the border of a clipping area.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Closes the PostScript document.
This function outputs a last line into the PostScript document, which is a PostScript comment containing the number of pages. It also writes the bookmark tree.
Connects the last point with first point of a path and draws the resulting closed line.
Output a text one line below the last outputted line. The line spacing is taken from the value "leading" which must be set with ps_set_value() in points. The actual position of the text is determined by the values "textx" and "texty" which can be requested with ps_get_value()
Draws a curve described by the three given points.
Mainly frees memory used by the document. Also closes a file, if it was not closed before with ps_close(). You should in any case close the file with ps_close() before, because ps_close() not just closes the file but also outputs a last line containing the PostScript comment with the number of pages in the document. Without this comment, a PostScript viewer may not show the number of pages properly.
Ends a pattern which was started with ps_begin_pattern().
Ends a template which was started with ps_begin_template().
Fills and draws the path constructed with previously called drawing functions like ps_lineto().
Fills the path constructed with previously called drawing functions like ps_lineto().
Loads a font for later use. Before text is output with a loaded font it must be set with ps_setfont(). This function needs the adobe font metric file in order to calculate the space used up by the characters. A font which is loaded within a page will only be available on that page. Fonts which are to be used in the complete document have to be loaded before the first call of ps_begin_page(). Calling ps_findfont() between pages will make that font available for all following pages.
ps_findfont() will try to load the file passed in the parameter encoding. Encoding files are of the same syntax as those used by dvips(1). They contain a font encoding vector (which is currently not used but must be present) and a list of extra ligatures to extend the list of ligatures derived from the afm file.
encoding can be NULL or the empty string if the default encoding (TeXBase1) shall be used.
If the encoding is set to builtin then there will be no reencoding and the font specific encoding will be used. This is very useful with symbol fonts.
Returns the identifier of the font or zero in case of an error. The identifier is a positive number.
Not yet implemented
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Gets several parameters which were set by ps_set_parameter(). Parameters are by definition string values. This function cannot be used to retrieve resources which were also set by ps_set_parameter().
Gets several values which were set by ps_set_value(). Parameters are by definition float values.
The parameter modifier specifies the resource for which the value is to be retrieved. This can be the id of a font or an image. It must be 0.0 if not used.
Hyphenates the passed word. ps_hyphenate() evaluates the value hyphenminchars and the parameter hyphendict. hyphendict must be set before calling this function.
This function requires the locale category LC_CTYPE to be set properly. This is done when the extension is initialized by using the environment variables. On Unix systems read the man page of locale.
text should not contain any non alpha characters. Possible positions for breaks are returned in an array of interger numbers. Each number is the position of the char in text after which a hyphenation can take place.
Adds a straight line from the current point to the given coordinates to the current path. Use ps_moveto() to set the starting point of the line.
Creates a spot color from the current fill color. The fill color must be defined in rgb, cmyk or gray colorspace. The spot color name can be an arbitrary name. A spot color can be set as any color with ps_setcolor().
Sets the current point to new coordinates. If this is the first call of ps_moveto() after a previous path has been ended then it will start a new path. If this function is called in the middle of a path it will just set the current point and start a subpath.
Creates a new document instance. It does not create the file on disk or in memory. It just sets up everything.
Creates a new file on disk and writes the PostScript document into it. The file will be closed when ps_close() is called.
If filename is not passed the document will be created in memory and all output will go straight to the browser.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Returns identifier of image or zero in case of an error. The identifier is a positive number greater than 0.
Reads an image which is already available in memory. The parameter source is currently not evaluated and assumed to be memory.
Returns identifier of image or zero in case of an error. The identifier is a positive number greater than 0.
Places a formerly loaded image on the page. The image can be scaled.
Draws a rectangle with its lower left corner at (x, y). The rectangle starts and ends in its lower left corner. If this function is called outside a path it will start a new path. If it is called within a path it will add the rectangle as a subpath. If the last drawing operation does not end in the lower left corner then there will be a gap in the path.
Restores a previously saved graphics context. Any call of ps_save() must be accompanied by a call to ps_restore().
Saves the current graphics context, containing colors, translation and rotation settings and some more. A save context can be restored with ps_restore().
Sets horizontal and vertical scaling of the coordinate system.
Annotations like the starting points of links are surrounded by a rectangle. This function sets the color of the border line.
Annotations like the starting points of links are surrounded by a rectangle. This function sets the black and white portion of a dashed border line.
Annotations like the starting points of links are surrounded by a rectangle. This function sets the appearance and width of the border line.
Sets certain information fields of the document. This fields will be shown as a comment in the header of the PostScript file. The values which can be set are Keywords, Subject, Title, Creator, Author, BoundingBox, and Orientation. Be aware that some of them has a meaning to PostScript viewers.
The BoundingBox is usually set to the value given to the first page. This only works if ps_findfont() has not been called before. In such cases the BoundingBox would be left unset unless you set it explicitly with this function.
Sets several parameters which are used by many functions. Parameters are by definition string values.
Set the position for the next text output. You may alternatively set the x and y value separately by calling ps_set_value() and choosing textx respectively texty as the value name.
Sets several values which are used by many functions. Parameters are by definition float values.
The name can be one of the following:
The way how text is shown.
The x coordinate for text output.
The y coordinate for text output.
The distance between words relative to the width of a space.
The distance between lines in pixels.
Sets the color for drawing, filling, or both.
The parameter type can be both, fill, or fillstroke.
The colorspace should be one of gray, rgb, cmyk, spot, pattern. Depending on the colorspace either only the first, the first three or all parameters will be used.
The second parameter is currently not always evaluated. The color is sometimes set for filling and drawing just as if fillstroke were passed.
Sets the length of the black and white portions of a dashed line.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Sets a font, which has to be loaded before with ps_findfont(). Outputting text without setting a font before results in an error.
Sets the gray value for all following drawing operations.
Sets the line width for all following drawing operations.
If two lines join in a small angle and the line join is set to miter, then the resulting spike will be very long. The miter limit is the maximum ratio of the miter length (the length of the spike) and the line width.
Sets the length of the black and white portions of a dashed line. ps_setpolydash() is used to set more complicated dash patterns.
arr is a list of length elements alternately for the black and white portion.
Creates a pattern based on a shading, which has to be created before with ps_shading(). Shading patterns can be used like regular patterns.
Creates a shading, which can be used by ps_shfill() or ps_shading_pattern().
The color of the shading can be in any color space except for pattern.
The type of shading can be either radial or axial. Each shading starts with the current fill color and ends with the given color values passed in the parameters c1 to c4 (see ps_setcolor() for their meaning).
The coordinates x0, y0, x1, y1 are the start and end point of the shading.
See ps_setcolor() for their meaning.
If the shading is of type radial the optlist must also contain the parameters r0 and r1 with the radius of the start and end circle.
Fills an area with a shading, which has to be created before with ps_shading().
Outputs a text in a given box. The lower left corner of the box is at (left, bottom). Line breaks will be inserted where needed. Multiple spaces are treated as one. Tabulators are treated as spaces.
The text will be hyphenated if the parameter "hyphenation" is set to "true" and the parameter "hyphendict" contains a valid filename for a hyphenation file. The line spacing is taken from the value "leading". Paragraphs can be separated by an empty line just like in TeX. If the value "parindent" is set to value > 0.0 then the first n lines will be indented. The number n of lines is set by the parameter "numindentlines". In order to prevent indenting of the first m paragraphs set the value "parindentskip" to a positive number.
The output of ps_show_boxed() can be configured with several parameters and values which must be set with either ps_set_parameter() or ps_set_value(). Beside the parameters and values which affect text output the following parameters and values are evaluated.
Distance between baselines of two consecutive lines.
Set to "true" if you want a carriage return to start a new line instead of treating it as a space. Defaults to "false".
Set to "true" if you want a carriage return on a single line to start a new paragraph instead of treating it as a space. Defaults to "true".
Set to "true" in order to turn hyphenation on. This requires a dictionary to be set with the parameter "hyphendict". Defaults to "false".
Filename of the dictionary used for hyphenation pattern (see below).
The number of chars which must at least be left over before or after the hyphen. This implies that only words of at least two times this value will be hyphenated. The default value is three. Setting a value of zero will result in the default value.
Set the amount of space in pixel for indenting the first m lines of a paragraph. m can be set with the value "numindentlines".
Set the amount of extra space in pixel between paragraphs. Defaults to 0 which will result in a normal line distance.
Number of lines from the start of the paragraph which will be indented. Defaults to 1.
Number of paragraphs in the box whose first lines will not be indented. This defaults to 0. This is useful for paragraphs right after a section heading or text being continued in a second box. In both case one would set this to 1.
Set how lines are to be numbered. Possible values are "box" for numbering lines in the whole box or "paragraph" to number lines within each paragraph.
The space for the column left of the numbered line containing the line number. The line number will be right justified into this column. Defaults to 20.
The space between the column with line numbers and the line itself. Defaults to 5.
Text is hyphenated if the parameter hyphenation is set to true and a valid hyphenation dictionary is set. pslib does not ship its own hyphenation dictionary but uses one from openoffice, scribus or koffice. You can find their dictionaries for different languages in one of the following directories if the software is installed:
/usr/share/apps/koffice/hyphdicts/ |
/usr/lib/scribus/dicts/ |
/usr/lib/openoffice/share/dict/ooo/ |
The parameter hmode can be "justify", "fulljustify", "right", "left", or "center". The difference of "justify" and "fulljustify" just affects the last line of the box. In fulljustify mode the last line will be left and right justified unless this is also the last line of paragraph. In justify mode it will always be left justified.
Output a text at the given text position.
Output a text at the current text position. The function will issue an error if no font was set before with ps_setfont().
ps_show() evaluates the following parameters and values as set by ps_set_parameter() and ps_set_value().
Distance between two consecutive glyphs. If this value is unequal to zero then all ligatures will be resolved. Values less than zero are allowed.
Setting this parameter to "false" will turn off kerning. Kerning is turned on by default.
Setting this parameter to "false" will turn off the use of ligatures. Ligatures are turned on by default.
Setting this parameter to "true" will turn on underlining. Underlining is turned off by default.
Setting this parameter to "true" will turn on overlining. Overlining is turned off by default.
Setting this parameter to "true" will turn on striking out. Striking out is turned off by default.
This function is similar to ps_stringwidth() but returns an array of dimensions.
An array of the dimensions of a string. The element 'width' contains the width of the string as returned by ps_stringwidth(). The element 'descender' contains the maximum descender and 'ascender' the maximum ascender of the string.
Calculates the width of a string in points if it was output in the given font and font size. This function needs an Adobe font metrics file to calculate the precise width. If kerning is turned on, it will be taken into account.
Draws the path constructed with previously called drawing functions like ps_lineto().
This function needs an Adobe font metrics file to know which glyphs are available.
The parameter ord is the position of the glyph in the font encoding vector.
Calculates the width of a glyph in points if it was output in the given font and font size. This function needs an Adobe font metrics file to calculate the precise width.
The parameter ord is the position of the glyph in the font encoding vector.
Its description
Output the glyph at position ord in the font encoding vector of the current font. The font encoding for a font can be set when loading the font with ps_findfont().
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 spell checker. Words less than 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 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()
|
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
Nota: Questo modulo non è disponibile su piattaforme Windows.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.0.0.
(PHP 4 >= 4.0.5, PECL)
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. |
This package is based on the libradius of FreeBSD. This PECL adds full support for Radius Authentication (RFC 2865) and Radius Accounting (RFC 2866). This package is available for Unix (tested on FreeBSD and Linux) and for Windows.
Howto install the package?
untar the package (usually into php4/ext)
rename radius-x.x to radius
run ./buildconf in php4
run ./configure --enable-radius
make; make install
untar the package
run phpize in the radius-x.x directory
run ./configure in the radius-x.x directory
make; make install
For windows I recommend to use the php_radius.dll from http://snaps.php.net/. You may obtain this unbundled PECL extension from the various PECL snaps pages (select the appropriate repository for your version of PHP): PECL for PHP 4.3.x, PECL for PHP 5.0.x or PECL Unstable.
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.
Authentication Request
Access accepted
Access rejected
Accounting request
Accounting response
Accsess challenge
Username
Password
Chap Password: chappass = md5(ident + plaintextpass + challenge)
NAS IP-Adress
NAS Port
Type of Service, one of:
RADIUS_LOGIN |
RADIUS_FRAMED |
RADIUS_CALLBACK_LOGIN |
RADIUS_CALLBACK_FRAMED |
RADIUS_OUTBOUND |
RADIUS_ADMINISTRATIVE |
RADIUS_NAS_PROMPT |
RADIUS_AUTHENTICATE_ONLY |
RADIUS_CALLBACK_NAS_PROMPT |
Framed Protocol, one of:
RADIUS_PPP |
RADIUS_SLIP |
RADIUS_ARAP |
RADIUS_GANDALF |
RADIUS_XYLOGICS |
IP-Address
Netmask
Routing
Filter ID
MTU
Compression, one of:
RADIUS_COMP_NONE |
RADIUS_COMP_VJ |
RADIUS_COMP_IPXHDR |
Login IP Host
Login Service
Login TCP Port
Reply Message
Callback Number
Callback ID
Framed Route
Framed IPX Network
State
Class
Vendor specific attribute
Session timeout
Idle timeout
Termination action
Called Station Id
Calling Station Id
NAS ID
Proxy State
Login LAT Service
Login LAT Node
Login LAT Group
Framed Appletalk Link
Framed Appletalk Network
Framed Appletalk Zone
Challenge
NAS port type, one of:
RADIUS_ASYNC |
RADIUS_SYNC |
RADIUS_ISDN_SYNC |
RADIUS_ISDN_ASYNC_V120 |
RADIUS_ISDN_ASYNC_V110 |
RADIUS_VIRTUAL |
RADIUS_PIAFS |
RADIUS_HDLC_CLEAR_CHANNEL |
RADIUS_X_25 |
RADIUS_X_75 |
RADIUS_G_3_FAX |
RADIUS_SDSL |
RADIUS_ADSL_CAP |
RADIUS_ADSL_DMT |
RADIUS_IDSL |
RADIUS_ETHERNET |
RADIUS_XDSL |
RADIUS_CABLE |
RADIUS_WIRELESS_OTHER |
RADIUS_WIRELESS_IEEE_802_11 |
Port Limit
Login LAT Port
Connect info
Accounting status type, one of:
RADIUS_START |
RADIUS_STOP |
RADIUS_ACCOUNTING_ON |
RADIUS_ACCOUNTING_OFF |
Accounting delay time
Accounting input bytes
Accounting output bytes
Accounting session ID
Accounting authentic, one of:
RADIUS_AUTH_RADIUS |
RADIUS_AUTH_LOCAL |
RADIUS_AUTH_REMOTE |
Accounting session time
Accounting input packets
Accounting output packets
Accounting terminate cause, one of:
RADIUS_TERM_USER_REQUEST |
RADIUS_TERM_LOST_CARRIER |
RADIUS_TERM_LOST_SERVICE |
RADIUS_TERM_IDLE_TIMEOUT |
RADIUS_TERM_SESSION_TIMEOUT |
RADIUS_TERM_ADMIN_RESET |
RADIUS_TERM_ADMIN_REBOOT |
RADIUS_TERM_PORT_ERROR |
RADIUS_TERM_NAS_ERROR |
RADIUS_TERM_NAS_REQUEST |
RADIUS_TERM_NAS_REBOOT |
RADIUS_TERM_PORT_UNNEEDED |
RADIUS_TERM_PORT_PREEMPTED |
RADIUS_TERM_PORT_SUSPENDED |
RADIUS_TERM_SERVICE_UNAVAILABLE |
RADIUS_TERM_CALLBACK |
RADIUS_TERM_USER_ERROR |
RADIUS_TERM_HOST_REQUEST |
Accounting multi session ID
Accounting link count
Microsoft specific vendor attributes (RFC 2548), one of:
RADIUS_MICROSOFT_MS_CHAP_RESPONSE |
RADIUS_MICROSOFT_MS_CHAP_ERROR |
RADIUS_MICROSOFT_MS_CHAP_PW_1 |
RADIUS_MICROSOFT_MS_CHAP_PW_2 |
RADIUS_MICROSOFT_MS_CHAP_LM_ENC_PW |
RADIUS_MICROSOFT_MS_CHAP_NT_ENC_PW |
RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_POLICY |
RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_TYPES |
RADIUS_MICROSOFT_MS_RAS_VENDOR |
RADIUS_MICROSOFT_MS_CHAP_DOMAIN |
RADIUS_MICROSOFT_MS_CHAP_CHALLENGE |
RADIUS_MICROSOFT_MS_CHAP_MPPE_KEYS |
RADIUS_MICROSOFT_MS_BAP_USAGE |
RADIUS_MICROSOFT_MS_LINK_UTILIZATION_THRESHOLD |
RADIUS_MICROSOFT_MS_LINK_DROP_TIME_LIMIT |
RADIUS_MICROSOFT_MS_MPPE_SEND_KEY |
RADIUS_MICROSOFT_MS_MPPE_RECV_KEY |
RADIUS_MICROSOFT_MS_RAS_VERSION |
RADIUS_MICROSOFT_MS_OLD_ARAP_PASSWORD |
RADIUS_MICROSOFT_MS_NEW_ARAP_PASSWORD |
RADIUS_MICROSOFT_MS_ARAP_PASSWORD_CHANGE_REASON |
RADIUS_MICROSOFT_MS_FILTER |
RADIUS_MICROSOFT_MS_ACCT_AUTH_TYPE |
RADIUS_MICROSOFT_MS_ACCT_EAP_TYPE |
RADIUS_MICROSOFT_MS_CHAP2_RESPONSE |
RADIUS_MICROSOFT_MS_CHAP2_SUCCESS |
RADIUS_MICROSOFT_MS_CHAP2_PW |
RADIUS_MICROSOFT_MS_PRIMARY_DNS_SERVER |
RADIUS_MICROSOFT_MS_SECONDARY_DNS_SERVER |
RADIUS_MICROSOFT_MS_PRIMARY_NBNS_SERVER |
RADIUS_MICROSOFT_MS_SECONDARY_NBNS_SERVER |
RADIUS_MICROSOFT_MS_ARAP_CHALLENGE |
Howto start?
get a radius resource
configure the library
create the request
put attributes
send the request
receive attributes
close the radius resource (optional)
The package contains an example php script. This script demonstrates howto authenticate with radius using PAP or CHAP (md5). If you authenticate with Microsoft Radius servers then its not possible to use CHAP (md5). If you would like to authenticate with Microsoft Servers you have to use MS-CHAPv1 or MS-CHAPv2, but its more complicated, because you need md4, sha1 and des to generate the right data. The enclosed examples demonstrate all authentication-methods, including MS-CHAPv1 and MS-CHAPv2. To get the MS-CHAP to work you need the mcrypt and the mhash extension, starting with version 1.2 of the package, the mcrypt extension is no longer needed.
If you have comments, bugfixes, enhancements or want to help to develop this you can send me a mail at mbretter@php.net. Binaries for Windows can be downloaded from here.
Returns a handle on success, FALSE on error. This function only fails if insufficient memory is available.
radius_add_server() may be called multiple times, and it may be used together with radius_config(). At most 10 servers may be specified. When multiple servers are given, they are tried in round-robin fashion until a valid response is received, or until each server's max_tries limit has been reached.
The hostname parameter specifies the server host, either as a fully qualified domain name or as a dotted-quad IP address in text form.
The port specifies the UDP port to contact on the server. If port is given as 0, the library looks up the radius/udp or radacct/udp service in the network services database, and uses the port found there. If no entry is found, the library uses the standard Radius ports, 1812 for authentication and 1813 for accounting.
The shared secret for the server host is passed to the secret parameter. The Radius protocol ignores all but the leading 128 bytes of the shared secret.
The timeout for receiving replies from the server is passed to the timeout parameter, in units of seconds.
The maximum number of repeated requests to make before giving up is passed into the max_tries.
Returns a handle on success, FALSE on error. This function only fails if insufficient memory is available.
It is not needed to call this function because php frees all resources at the end of each request.
Before issuing any Radius requests, the library must be made aware of the servers it can contact. The easiest way to configure the library is to call radius_config(). radius_config() causes the library to read a configuration file whose format is described in radius.conf.
The pathname of the configuration file is passed as the file argument to radius_config(). The library can also be configured programmatically by calls to radius_add_server().
A Radius request consists of a code specifying the kind of request, and zero or more attributes which provide additional information. To begin constructing a new request, call radius_create_request().
Nota: Attention: You must call this function, before you can put any attribute!
Type is RADIUS_ACCESS_REQUEST or RADIUS_ACCOUNTING_REQUEST.
Its description
Esempio 1. radius_cvt_addr() example
|
Esempio 1. radius_cvt_int() example
|
Esempio 1. radius_cvt_string() example
|
When using MPPE with MS-CHAPv2, the send- and recv-keys are mangled (see RFC 2548), however this function is useless, because I don't think that there is or will be a PPTP-MPPE implementation in PHP.
Some data (Passwords, MS-CHAPv1 MPPE-Keys) is mangled for security reasons, and must be demangled before you can use them.
Like Radius requests, each response may contain zero or more attributes. After a response has been received successfully by radius_send_request(), its attributes can be extracted one by one using radius_get_attr(). Each time radius_get_attr() is called, it gets the next attribute from the current response.
Returns an associative array containing the attribute-type and the data, or error number <= 0.
Esempio 1. radius_get_attr() example
|
radius_put_attr() |
radius_get_vendor_attr() |
radius_put_vendor_attr() |
radius_send_request() |
If radius_get_attr() returns RADIUS_VENDOR_SPECIFIC, radius_get_vendor_attr() may be called to determine the vendor.
Returns an associative array containing the attribute-type, vendor and the data, or FALSE on error.
Esempio 1. radius_get_vendor_attr() example
|
Avvertimento |
Questa 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. |
The request authenticator is needed for demangling mangled data like passwords and encryption-keys.
After the Radius request has been constructed, it is sent by radius_send_request().
The radius_send_request() function sends the request and waits for a valid reply, retrying the defined servers in round-robin fashion as necessary.
If a valid response is received, radius_send_request() returns the Radius code which specifies the type of the response. This will typically be RADIUS_ACCESS_ACCEPT, RADIUS_ACCESS_REJECT, or RADIUS_ACCESS_CHALLENGE. If no valid response is received, radius_send_request() returns FALSE.
The shared secret is needed as salt for demangling mangled data like passwords and encryption-keys.
Rar is a powerful and effective archiver created by Eugene Roshal. This extension gives you possibility to read Rar archives but doesn't support writing Rar archives, because this is not supported by UnRar library and is directly prohibited by it's license.
More information about Rar and UnRar can be found at http://www.rarlabs.com/.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Rar is currently available through PECL http://pecl.php.net/package/rar.
Also you can use the pear installer to install the Rar extension, using the following command: pear -v install rar.
You can always download the tar.gz package and install Rar by hand:
Windows users can download the extension dll php_rar.dll here: http://snaps.php.net/win32/PECL_STABLE/.
There is one resource used in Rar extension: a file descriptor returned by rar_open().
Esempio 2. Rar extension overview example
|
This example opens a Rar file archive and extracts each entry to the specified directory.
Close Rar archive and free all allocated resources.
rar_close() returns FALSE on error.
(no version information, might be only in CVS)
rar_entry_get -- Get entry object from the Rar archiveGet entry object from the Rar archive.
rar_get_entry() returns entry object or FALSE on error.
Rar::extract() extracts entry's data to the dir. It will create new file in the specified dir with the name identical to the entry's name. If parameter filepath is specified instead dir, Rar::extract() will extract entry's data to the specified file.
Esempio 1. Rar::extract() example
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Rar::getAttr() returns attributes of the archive entry.
Esempio 1. Rar::getAttr() example
|
Rar::getAttr() returns FALSE on error.
See also Rar::getHostOs().
Rar::getCrc() returns CRC of the archive entry.
Rar::getCrc() returns FALSE on error.
Rar::getFileTime() returns entry last modification time as string in format YYYY-MM-DD HH:II:SS.
Rar::getFileTime() returns FALSE on error.
Rar::getHostOs() return code of the host OS of the archive entry.
Esempio 1. Rar::getHostOs() example
|
Rar::getHostOs() returns FALSE on error.
Rar::getMethod() returns number of the method used when adding current archive entry.
Rar::getMethod() returns FALSE on error.
Rar::getName() returns full name of the archive entry.
Rar::getName() returns FALSE on error.
Get packed size of the archive entry.
Rar::getPackedSize() returns FALSE on error.
(no version information, might be only in CVS)
Rar::getUnpackedSize -- Get unpacked size of the entryGet unpacked size of the archive entry.
Esempio 1. Rar::getUnpackedSize() example
|
Rar::getUnpackedSize() returns FALSE on error.
(no version information, might be only in CVS)
Rar::getVersion -- Get version of the archiver used to add the entryGet version of the archiver used to add the archive entry.
Rar::getVersion() returns FALSE on error.
Get entries list from the Rar archive.
rar_list() returns array of entries or FALSE on error.
The readline() functions implement an interface to the GNU Readline library. These are functions that provide editable command lines. An example being the way Bash allows you to use the arrow keys to insert characters or scroll through command history. Because of the interactive nature of this library, it will be of little use for writing Web applications, but may be useful when writing scripts used from a command line.
Nota: Questo modulo non è disponibile su piattaforme Windows.
To use the readline functions, you need to install libreadline. You can find libreadline on the home page of the GNU Readline project, at http://cnswww.cns.cwru.edu/~chet/readline/rltop.html. It's maintained by Chet Ramey, who's also the author of Bash.
You can also use these functions with the libedit library, a non-GPL replacement for the readline library. The libedit library is BSD licensed and available for download from http://sourceforge.net/projects/libedit/.
To use these functions you must compile the CGI or CLI version of PHP with readline support. You need to configure PHP --with-readline[=DIR]. In order you want to use the libedit readline replacement, configure PHP --with-libedit[=DIR].
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
This function adds a line to the command line history.
(PHP 5 >= 5.1.0RC1)
readline_callback_handler_install -- Initializes the readline callback interface and terminal, prints the prompt and returns immediatelySets up a readline callback interface then prints prompt and immediately returns. The callback function takes one parameter; the user input returned. Calling this function twice without removing the previous callback interface will automatically and conveniently overwrite the old interface.
The callback feature is useful when combined with stream_select() as it allows interleaving of IO and user input, unlike readline().
Esempio 1. Readline Callback Interface Example
|
(PHP 5 >= 5.1.0RC1)
readline_callback_handler_remove -- Removes a previously installed callback handler and restores terminal settingsRemoves a previously installed callback handler and restores terminal settings.
See readline_callback_handler_install() for an example of how to use the readline callback interface.
Returns TRUE if a previously installed callback handler was removed, or FALSE if one could not be found.
(PHP 5 >= 5.1.0RC1)
readline_callback_read_char -- Reads a character and informs the readline callback interface when a line is receivedReads a character of user input. When a line is received, this function informs the readline callback interface installed using readline_callback_handler_install() that a line is ready for input.
See readline_callback_handler_install() for an example of how to use the readline callback interface.
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.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
This function reads a command history from a file.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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://directory.fsf.org/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.
This module allows you to read the meta information stored in the headers of a RedHat Package Manager (RPM) file.
RPMReader is not bundled with PHP. It is a PECL extension and can be located here: http://pecl.php.net/package/rpmreader.
To enable extname support, configure PHP with --with-rpmreader
There is one resource type used by the RPMReader module. The resource is a file pointer which identifies the RPM file with which to work.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
The following list of constants are used to obtain information using the rpm_get_tag() function. These constants represent the tag number to be retrieved from the RPM file's header section. Descriptions are given below as to what data the tag number constants reference.
The minimum valid value of any RPM tag number.
The name of the RPM package.
The version of the RPM package.
The release of the RPM package.
The summary text of the RPM package.
The full description text of the RPM package.
The date and time when the RPM package was built.
The name of the host on which the RPM package was built.
The size of the RPM package.
The list of files in an RPM package (deprecated format). The correct way is now to use a combination of 3 tags (RPMREADER_BASENAMES, RPMREADER_DIRINDEXES, RPMREADER_DIRNAMES) in what RPM now calls "CompressedFileNames". This tag is still used in older RPM files that did not use the "CompressedFileNames" method and is maintained for backward compatibility.
The list of dates from changelog entries.
The list of changelog entry names.
The list of the text from changelog entries.
The list of indices that relate directory names to files in the RPM package. This tag is used in conjunction with RPMREADER_BASENAMES and RPMREADER_DIRNAMES to reconstruct filenames in the RPM package stored with the new "CompressedFileNames" method in RPM.
The list of the names of files in the RPM package without path information. This tag is used in conjunction with RPMREADER_DIRINDEXES and RPMREADER_DIRNAMES to reconstruct filenames in the RPM package stored with the new "CompressedFileNames" method in RPM.
The list of directory names used by files in the RPM package. This tag is used in conjunction with RPMREADER_BASENAMES and RPMREADER_DIRINDEXES to reconstruct filenames in the RPM package stored with the new "CompressedFileNames" method in RPM.
The maximum valid value of any RPM tag number.
This example will open an RPM file and read the name, version, and release from the RPM file, echo the results, and close the RPM file.
Esempio 1. Basic RPMReader Example
|
(no version information, might be only in CVS)
rpm_get_tag -- Retrieves a header tag from an RPM filerpm_get_tag() will retrieve a given tag from the RPM file's header and return it.
A file pointer resource successfully opened by rpm_open().
The tag number to retrieve from the RPM header. This value can be specified using the list of constants defined by this module.
The return value can be of various types depending on the tagnum supplied to the function.
(no version information, might be only in CVS)
rpm_is_valid -- Tests a filename for validity as an RPM filerpm_is_valid() will test an RPM file for validity as an RPM file. This is not the same as rpm_open() as it only checks the file for validity but does not return a file pointer to be used by further functions.
rpm_open() will open an RPM file and will determine if the file is a valid RPM file.
If the open succeeds, then rpm_open() will return a file pointer resource to the newly opened file. On error, the function will return FALSE.
The runkit extension provides means to modify constants, user-defined functions, and user-defined classes. It also provides for custom superglobal variables and embeddable sub-interpreters via sandboxing.
Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/runkit.
This package is meant as a feature added replacement for the classkit package. When compiled with the --enable-runkit=classkit option to ./configure, it will export classkit compatible function definitions and constants.
Modifying Constants, Functions, Classes, and Methods works with all releases of PHP 4 and PHP 5. No special requirements are necessary.
Custom Superglobals are only available in PHP 4.2.0 or later.
Sandboxing requires PHP 5.1.0 or later, or PHP 5.0.0 with a special TSRM patch applied. Regardless of which version of PHP is in use it must be compiled with the --enable-maintainer-zts option. See the README file in the runkit package for additional information.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Runkit Configuration Options
Name | Default | Changeable | Changelog |
---|---|---|---|
runkit.superglobal | PHP_INI_PERDIR | ||
runkit.internal_override | PHP_INI_SYSTEM |
Breve descrizione dei parametri di configurazione.
Comma-separated list of variable names to be treated as superglobals. This value should be set in the systemwide php.ini file, but may work in perdir configuration contexts depending on your SAPI.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
runkit_import() flag indicating that normal functions should be imported from the specified file.
runkit_import() flag indicating that class methods should be imported from the specified file.
runkit_import() flag indicating that class constants should be imported from the specified file. Note that this flag is only meaningful in PHP versions 5.1.0 and above.
runkit_import() flag indicating that class standard properties should be imported from the specified file.
runkit_import() flag representing a bitwise OR of the RUNKIT_IMPORT_CLASS_* constants.
runkit_import() flag indicating that if any of the imported functions, methods, constants, or properties already exist, they should be replaced with the new definitions. If this flag is not set, then any imported definitions which already exist will be discarded.
PHP5 specific flag to runkit_method_add()
PHP5 specific flag to runkit_method_add()
PHP5 specific flag to runkit_method_add()
PHP5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.
PHP5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.
PHP5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.
PHP5 specific flag to classkit_import() Only defined when classkit compatibility is enabled.
Defined to the current version of the runkit package.
Defined to the current version of the runkit package. Only defined when classkit compatibility is enabled.
(no version information, might be only in CVS)
Runkit_Sandbox -- Runkit Sandbox Class -- PHP Virtual MachineInstantiating the Runkit_Sandbox class creates a new thread with its own scope and program stack. Using a set of options passed to the constructor, this environment may be restricted to a subset of what the primary interpreter can do and provide a safer environment for executing user supplied code.
Nota: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available with PHP 5.1 or specially patched versions of PHP 5.0 and requires that thread safety be enabled. See the README file included in the runkit package for more information.
options is an associative array containing any combination of the special ini options listed below.
If the outer script which is instantiating the Runkit_Sandbox class is configured with safe_mode = off, then safe_mode may be turned on for the sandbox environment. This setting can not be used to disable safe_mode when it's already enabled in the outer script.
If the outer script which is instantiating the Runkit_Sandbox class is configured with safe_mode_gid = on, then safe_mode_gid may be turned off for the sandbox environment. This setting can not be used to enable safe_mode_gid when it's already disabled in the outer script.
If the outer script which is instantiating the Runkit_Sandbox class is configured with a safe_mode_include_dir, then a new safe_mode_include_dir may be set for sandbox environments below the currently defined value. safe_mode_include_dir may also be cleared to indicate that the bypass feature is disabled. If safe_mode_include_dir was blank in the outer script, but safe_mode was not enabled, then any arbitrary safe_mode_include_dir may be set while turning safe_mode on.
open_basedir may be set to any path below the current setting of open_basedir. If open_basedir is not set within the global scope, then it is assumed to be the root directory and may be set to any location.
Like safe_mode, this setting can only be made more restrictive, in this case by setting it to FALSE when it is previously set to TRUE
Comma separated list of functions to disable within the sandbox sub-interpreter. This list need not contain the names of the currently disabled functions, they will remain disabled whether listed here or not.
Comma separated list of classes to disable within the sandbox sub-interpreter. This list need not contain the names of the currently disabled classes, they will remain disabled whether listed here or not.
Comma separated list of variables to be treated as superglobals within the sandbox sub-interpreter. These variables will be used in addition to any variables defined internally or through the global runkit.superglobal setting.
Ini option runkit.internal_override may be disabled (but not re-enabled) within sandboxes.
Esempio 1. Instantiating a restricted sandbox
|
All variables in the global scope of the sandbox environment are accessible as properties of the sandbox object. The first thing to note is that because of the way memory between these two threads is managed, object and resource variables can not currently be exchanged between interpreters. Additionally, all arrays are deep copied and any references will be lost. This also means that references between interpreters are not possible.
Il precedente esempio visualizzerà:
bar barbaz bool(false) |
Any function defined within the sandbox may be called as a method on the sandbox object. This also includes a few pseudo-function language constructs: eval(), include(), include_once(), require(), require_once(), echo(), print(), die(), and exit().
Il precedente esempio visualizzerà:
fbc |
When passing arguments to a sandbox function, the arguments are taken from the outer instance of PHP. If you wish to pass arguments from the sandbox's scope, be sure to access them as properties of the sandbox object as illustrated above.
Il precedente esempio visualizzerà:
bar baz |
As of runkit version 0.5, certain Sandbox settings may be modified on the fly using ArrayAccess syntax. Some settings, such as active are read-only and meant to provide status information. Other settings, such as output_handler may be set and read much like a normal array offset. Future settings may be write-only, however no such settings currently exist.
Tabella 1. Sandbox Settings / Status Indicators
Setting | Type | Purpose | Default |
---|---|---|---|
active | Boolean (Read Only) | TRUE if the Sandbox is still in a usable state, FALSE if the request is in bailout due to a call to die(), exit(), or because of a fatal error condition. | TRUE (Initial) |
output_handler | Callback | When set to a valid callback, all output generated by the Sandbox instance will be processed through the named function. Sandbox output handlers follow the same calling conventions as the system-wide output handler. | None |
parent_access | Boolean | May the sandbox use instances of the Runkit_Sandbox_Parent class? Must be enabled for other Runkit_Sandbox_Parent related settings to work. | FALSE |
parent_read | Boolean | May the sandbox read variables in its parent's context? | FALSE |
parent_write | Boolean | May the sandbox modify variables in its parent's context? | FALSE |
parent_eval | Boolean | May the sandbox evaluate arbitrary code in its parent's context? DANGEROUS | FALSE |
parent_include | Boolean | May the sandbox include php code files in its parent's context? DANGEROUS | FALSE |
parent_echo | Boolean | May the sandbox echo data in its parent's context effectively bypassing its own output_handler? | FALSE |
parent_call | Boolean | May the sandbox call functions in its parent's context? | FALSE |
parent_die | Boolean | May the sandbox kill its own parent? (And thus itself) | FALSE |
parent_scope | Integer | What scope will parental property access look at? 0 == Global scope, 1 == Calling scope, 2 == Scope preceeding calling scope, 3 == The scope before that, etc..., etc... | 0 (Global) |
Instantiating the Runkit_Sandbox_Parent class from within a sandbox environment created from the Runkit_Sandbox class provides some (controlled) means for a sandbox child to access its parent.
Nota: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available with PHP 5.1 or specially patched versions of PHP 5.0 and requires that thread safety be enabled. See the README file included in the runkit package for more information.
In order for any of the Runkit_Sandbox_Parent features to function. Support must be enabled on a per-sandbox basis by enabling the parent_access flag from the parent's context.
Just as with sandbox variable access, a sandbox parent's variables may be read from and written to as properties of the Runkit_Sandbox_Parent class. Read access to parental variables may be enabled with the parent_read setting (in addition to the base parent_access setting). Write access, in turn, is enabled through the parent_write setting.
Unlike sandbox child variable access, the variable scope is not limited to globals only. By setting the parent_scope setting to an appropriate integer value, other scopes in the active call stack may be inspected instead. A value of 0 (Default) will direct variable access at the global scope. 1 will point variable access at whatever variable scope was active at the time the current block of sandbox code was executed. Higher values progress back through the functions that called the functions that led to the sandbox executing code that tried to access its own parent's variables.
Esempio 2. Accessing parental variables
|
Il precedente esempio visualizzerà:
string(6) "Global" string(7) "three()" string(5) "two()" string(5) "one()" string(6) "Global" string(6) "Global" |
Just as with sandbox access, a sandbox may access its parents functions providing that the proper settings have been enabled. Enabling parent_call will allow the sandbox to call all functions available to the parent scope. Language constructs are each controlled by their own setting: print() and echo() are enabled with parent_echo. die() and exit() are enabled with parent_die. eval() is enabled with parent_eval while include(), include_once(), require(), and require_once() are enabled through parent_include.
(PECL)
runkit_class_adopt -- Convert a base class to an inherited class, add ancestral methods when appropriate
Name of class to be adopted
Parent class which child class is extending
(PECL)
runkit_class_emancipate -- Convert an inherited class to a base class, removes any method whose scope is ancestral
Esempio 1. A runkit_class_emancipate() example
Il precedente esempio visualizzerà:
|
Name of constant to declare. Either a string to indicate a global constant, or classname::constname to indicate a class constant.
NULL, Bool, Long, Double, String, or Resource value to store in the new constant.
Constant to redefine. Either string indicating global constant, or classname::constname indicating class constant.
New value to assign to constant.
Name of constant to remove. Either a string indicating a global constant, or classname::constname indicating a class constant.
Name of function to be created
Comma separated argument list
Code making up the function
create_function() |
runkit_function_redefine() |
runkit_function_copy() |
runkit_function_rename() |
runkit_function_remove() |
runkit_method_add() |
Name of existing function
Name of new function to copy definition to
runkit_function_add() |
runkit_function_redefine() |
runkit_function_rename() |
runkit_function_remove() |
Name of function to redefine
New list of arguments to be accepted by function
New code implementation
Esempio 1. A runkit_function_redefine() example
Il precedente esempio visualizzerà:
|
runkit_function_add() |
runkit_function_copy() |
runkit_function_rename() |
runkit_function_remove() |
runkit_function_add() |
runkit_function_copy() |
runkit_function_redefine() |
runkit_function_rename() |
runkit_function_add() |
runkit_function_copy() |
runkit_function_redefine() |
runkit_function_remove() |
(PECL)
runkit_import -- Process a PHP file importing function and class definitions, overwriting where appropriateSimilar to include() however any code residing outside of a function or class is simply ignored. Additionally, depending on the value of flags, any functions or classes which already exist in the currently running environment will be automatically overwritten by their new definitions.
Filename to import function and class definitions from
Bitwise OR of the RUNKIT_IMPORT_* family of constants.
The runkit_lint_file() function performs a syntax (lint) check on the specified filename testing for scripting errors. This is similar to using php -l from the commandline.
Nota: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available with PHP 5.1 or specially patched versions of PHP 5.0 and requires that thread safety be enabled. See the README file included in the runkit package for more information.
The runkit_lint() function performs a syntax (lint) check on the specified php code testing for scripting errors. This is similar to using php -l from the commandline except runkit_lint() accepts actual code rather than a filename.
Nota: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available with PHP 5.1 or specially patched versions of PHP 5.0 and requires that thread safety be enabled. See the README file included in the runkit package for more information.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The class to which this method will be added
The name of the method to add
Comma-delimited list of arguments for the newly-created method
The code to be evaluated when methodname is called
The type of method to create, can be RUNKIT_ACC_PUBLIC, RUNKIT_ACC_PROTECTED or RUNKIT_ACC_PRIVATE
Nota: This parameter is only used as of PHP 5, because, prior to this, all methods were public.
Esempio 1. runkit_method_add() example
Il precedente esempio visualizzerà:
|
runkit_method_copy() |
runkit_method_redefine() |
runkit_method_remove() |
runkit_method_rename() |
runkit_function_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. |
Destination class for copied method
Destination method name
Source class of the method to copy
Name of the method to copy from the source class. If this parameter is omitted, the value of dMethod is assumed.
Esempio 1. runkit_method_copy() example
Il precedente esempio visualizzerà:
|
runkit_method_add() |
runkit_method_redefine() |
runkit_method_remove() |
runkit_method_rename() |
runkit_function_copy() |
Nota: This function cannot be used to manipulate the currently running (or chained) method.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The class in which to redefine the method
The name of the method to redefine
Comma-delimited list of arguments for the redefined method
The new code to be evaluated when methodname is called
The redefined method can be RUNKIT_ACC_PUBLIC, RUNKIT_ACC_PROTECTED or RUNKIT_ACC_PRIVATE
Nota: This parameter is only used as of PHP 5, because, prior to this, all methods were public.
Esempio 1. runkit_method_redefine() example
Il precedente esempio visualizzerà:
|
runkit_method_add() |
runkit_method_copy() |
runkit_method_remove() |
runkit_method_rename() |
runkit_function_redefine() |
Nota: This function cannot be used to manipulate the currently running (or chained) method.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The class in which to remove the method
The name of the method to remove
runkit_method_add() |
runkit_method_copy() |
runkit_method_redefine() |
runkit_method_rename() |
runkit_function_remove() |
Nota: This function cannot be used to manipulate the currently running (or chained) method.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The class in which to rename the method
The name of the method to rename
The new name to give to the renamed method
runkit_method_add() |
runkit_method_copy() |
runkit_method_redefine() |
runkit_method_remove() |
runkit_function_rename() |
(PECL)
runkit_sandbox_output_handler -- Specify a function to capture and/or process output from a runkit sandboxOrdinarily, anything output (such as with echo() or print()) will be output as though it were printed from the parent's scope. Using runkit_sandbox_output_handler() however, output generated by the sandbox (including errors), can be captured by a function outside of the sandbox.
Nota: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available with PHP 5.1 or specially patched versions of PHP 5.0 and requires that thread safety be enabled. See the README file included in the runkit package for more information.
Deprecated: As of runkit version 0.5, this function is deprecated and is scheduled to be removed from the package prior to a 1.0 release. The output handler for a given Runkit_Sandbox instance may be read/set using the array offset syntax shown on the Runkit_Sandbox class definition page.
Object instance of Runkit_Sandbox class on which to set output handling.
Name of a function which expects one parameter. Output generated by sandbox will be passed to this callback. Anything returned by the callback will be displayed normally. If this parameter is not passed then output handling will not be changed. If a non-truth value is passed, output handling will be disabled and will revert to direct display.
Returns the name of the previously defined output handler callback, or FALSE if no handler was previously defined.
Esempio 1. Feeding output to a variable
Il precedente esempio visualizzerà:
|
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
Nota: Questo modulo non è disponibile su piattaforme Windows.
Satellite is deprecated. It is suggested that you use Universe (http://universe-phpext.sourceforge.net/) and not Satellite.
The Satellite extension is used for accessing CORBA objects. You will need to set the idl_directory= entry in php.ini to a path where you store all IDL files you use.
See the Satellite README file for details about installing Satellite.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
This class represents the enumeration identified with the id parameter.
Can be either the name of the enumeration (e.g "MyEnum"), or the full repository id (e.g. "IDL:MyEnum:1.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. |
This class provides access to a CORBA object.
Should be a string containing the IOR (Interoperable Object Reference) that identifies the remote 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. |
This class represents the structure identified with the id parameter.
Can be either the name of the struct (e.g "MyStruct"), or the full repository id (e.g. "IDL:MyStruct:1.0").
Esempio 2. PHP code for accessing MyStruct
|
(4.0.3 - 4.1.2 only, PECL)
satellite_caught_exception -- See if an exception was caught from the previous functionAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è 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. |
For example usage see satellite_caught_exception().
(4.0.3 - 4.1.2 only, PECL)
satellite_exception_value -- Get the exception struct for the latest exceptionAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Return an exception struct. For example usage see satellite_caught_exception().
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
Service Data Objects (SDOs) enable PHP applications to work with data from different sources (like a database query, an XML file, and a spreadsheet) using a single interface.
Each different kind of data source requires a Data Access Service (DAS) to provide access to the data in the data source. In your PHP application, you use a DAS to create an SDO instance that represents some data in the data source. You can then set and get values in the SDO instance using the standard SDO interface. Finally, you use a DAS to write the modified data back to a data source (typically the same one).
See the list of Data Access Services for details on those currently available. In addition to the provided DASs, SDO also provides interfaces to enable others to be implemented (see the section on SDO Data Access Services Interface for more details).
This extension is derived from concepts taken from the Service Data Objects specification
A Service Data Object instance is made up of a tree of data objects. The tree is defined by containment references between the data objects. For example, a Company data object might consist of a number of Department data objects and therefore the Company would have a containment reference to the Departments. Deleting a data object which has a containment reference to another data object will delete the referenced data object. For example, deleting the Company data object will also delete the Departments.
An SDO may also have non-containment references between data objects in the tree. For example, one Employee data object might reference another Employee to identify a career mentor. Deleting a data object which has a non-containment reference to another data object does not delete the referenced data object.
As well as data objects referencing each other, they can also have primitive properties. For example, the Company data object might have a property called "name" of type string, for holding the name of the company (for example, "Acme").
The SDO extension requires PHP 5.1 or higher.
SDO XML Data Access Service, which is built as part of this extension, requires libxml2 (Tested with libxml2 2.6.19) which can be downloaded from http://www.xmlsoft.org/.
There are several options, depending on whether you are installing on Windows or Linux, and depending on whether you are installing a released version (a .tgz file from the PECL site) or the latest from CVS. The Relational DAS also needs special attention as it is written in PHP.
The instructions are likely to change as PHP 5.1 progresses in status from beta to stable release. The instructions here were correct on 6th October 2005, when PHP 5.1.0RC1 was the current release candidate for PHP, and 0.5.2 was the current beta release of SDO.
The options are summarised in the following table:
latest/Release | Windows | Linux |
---|---|---|
latest CVS |
|
|
Release |
|
|
Regardless of which platform or which level of the code you have installed you will need add the two extension libraries to your php.ini file. On Windows, add:
extension=php_sdo.dll extension=php_sdo_das_xml.dll |
extension=sdo.so extension=sdo_das_xml.so |
The Relational DAS is written in PHP. You may need to update your include_path in php.ini to point to the directory that contains sdo/DAS/Relational .
This section describes how to build the SDO core and XML DAS on Linux. Currently you would only need to know how to do this if you wish to build a recent version that you have checked out of CVS.
Change to the main extension directory: cd < wherever your sdo code is >
Run phpize, which will set up the environment to compile both SDO and the XML Data Access Service.
Next, run ./configure; make; make install. Please note, you may need to login as root to install the extension.
Make sure that these modules are loaded by PHP, by adding extension=sdo.so and extension=sdo_das_xml.so to your php.ini file in the same order.
The table below lists the currently provided SDO Data Access Services:
DAS Name | Description |
---|---|
SDO_DAS_XML | An XML Data Access Service supporting reading/writing SDOs as XML documents or via a Web URL to supporting things like RSS feeds. |
SDO_DAS_Relational | A PDO-based Data Access Service supporting reading/writing SDO to relational data sources. Implements an optimistic concurrency policy for updates. |
The following are limitations in the current SDO implementation:
There is no support for multi-byte character sets.
The following SDO 2.0 concepts are not supported in the current PHP implementation. It is not necessarily the case that these will all be added over time. Their inclusion will depend on community requirements.
Abstract types and type derivation.
Open types.
Bi-directional relationships.
Type and property alias names.
Read-only properties.
Model introspection.
XMLHelper/XSDHelper (the XML DAS provide a lot of this functionality)
TypeHelper (the SDO_DAS_DataFactory provides this functionality)
The examples below assume an SDO created with the schema and instance information shown below, using the XML Data Access Service.
The schema describes a company data object. The company contains department data objects, and each department contains employee data objects. Each data object has a number of primitive properties to describe things like name, serial number, etc. Finally, the company data object also has a non-containment reference to one of the employee data objects to identify them as the 'employeeOfTheMonth'.
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:sdo="commonj.sdo" xmlns:sdoxml="commonj.sdo/xml" xmlns:company="companyNS" targetNamespace="companyNS"> <xsd:element name="company" type="company:CompanyType"/> <xsd:complexType name="CompanyType"> <xsd:sequence> <xsd:element name="departments" type="company:DepartmentType" maxOccurs="unbounded"/> </xsd:sequence> <xsd:attribute name="name" type="xsd:string"/> <xsd:attribute name="employeeOfTheMonth" type="xsd:IDREF" sdoxml:propertyType="company:EmployeeType"/> </xsd:complexType> <xsd:complexType name="DepartmentType"> <xsd:sequence> <xsd:element name="employees" type="company:EmployeeType" maxOccurs="unbounded"/> </xsd:sequence> <xsd:attribute name="name" type="xsd:string"/> <xsd:attribute name="location" type="xsd:string"/> <xsd:attribute name="number" type="xsd:int"/> </xsd:complexType> <xsd:complexType name="EmployeeType"> <xsd:attribute name="name" type="xsd:string"/> <xsd:attribute name="SN" type="xsd:ID"/> <xsd:attribute name="manager" type="xsd:boolean"/> </xsd:complexType> </xsd:schema> |
The instance document below describes a single company, called 'MegaCorp', which contains a single department, called 'Advanced Technologies'. The Advanced Technologies department contains three employees. The company employeeOfTheMonth is referencing the second employee, 'Jane Doe'.
<?xml version="1.0" encoding="UTF-8" ?> <company xmlns="companyNS" name="MegaCorp" employeeOfTheMonth="#/departments.0/employees.1"> <departments name="Advanced Technologies" location="NY" number="123"> <employees name="John Jones" SN="E0001"/> <employees name="Jane Doe" SN="E0003"/> <employees name="Al Smith" SN="E0004" manager="true"/> </departments> </company> |
The following examples assume $company is a data object created from the schema and instance document shown above.
Esempio 1. Access via Property names Data object properties can be accessed using the object property access syntax. The following gets the list of departments (containing a single department), and sets the company name to 'Acme'.
|
Esempio 2. Access via Property index Data object properties can be accessed via their property index using array syntax. The property index is the position at which the property's definition appears in the model (in this case the xml schema). We can see from the schema listing above that the departments element is the first company property defined and the company name attribute is the second company property (the SDO interface makes no distinction between XML attributes and elements). The following gets the list of departments (containing a single department), and sets the company name to 'Acme'.
|
Esempio 3. Data Object Iteration We can iterate over the properties of a data object using foreach. The following iterates over the company properties; name, departments and employeeOfTheMonth.
For the first iteration, $name will be 'name' and $value will be 'Acme'. For the second iteration, $name will be 'departments' and $value will be an SDO_List (because departments is a many-valued property (stated maxOccurs="unbouded" in the schema)) containing a single data object of type DepartmentType. For the third iteration, $name will be 'employeeOfTheMonth' and $value will be a data object of type EmployeeType. |
Esempio 4. Many-valued Property Iteration Many-valued properties can also be iterated over using foreach. The following iterates over the company's departments.
Each iteration will assign the next department in the list to the variable $department. |
Esempio 7. Simple XPath support We can access properties using XPath-like (an augmented sub-set of XPath) expressions, the simplest form of which is the property name. The following sets the company name and gets the employeeOfTheMonth.
|
Esempio 9. XPath Navigation We can use XPath expressions to navigate the data object instance structure. Two forms of indexing into many-valued properties are supported. The first is the standard XPath array syntax with the indexing starting at one, the second is an SDO extension to XPath with an index starting at zero. The following both get the second employee from the first department.
|
Esempio 10. XPath Querying We can use XPath to query and identify parts of a data object based on instance data. The following retrieves the manager from the 'Advanced Technologies' department.
|
Esempio 11. Creating child data object A data object can be a factory for its child data objects. A child data object is automatically part of the data graph. The following add a new employee to the 'Advanced Technologies' department.
|
Esempio 12. Unset referenced data object We can use the isset() and unset() functions to test and remove items from the data object. The following removes the 'employeeOfTheMonth' from the company. If this were a containment reference then the employee would be removed from the company (probably not a good idea to sack your best employee each month!), but since this is a non-containment reference, the employee being referenced will remain in the department in the company, but will no longer be accessible via the employeeOfTheMonth property.
|
Sequenced data objects are SDOs which can track property ordering across the properties of a data object. They can also contain unstructured text elements (text element which do not belong to any of the SDO's properties). Sequenced data objects are useful for working with XML documents which allow unstructured text (i.e. mixed=true) or if the elements can be interleaved ( <A/><B/><A/>). This can occur for example when the schema defines maxOccurs>1 on a element which is a complexType with a choice order indicator.
The examples below assume an SDO created with the following schema and instance information, using the XML Data Access Service.
The schema below describes the format of a letter. The letter can optionally contain three properties; date, firstName, and lastName. The schema states mixed="true" which means that unstructured text can be interspersed between the three properties.
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:letter="http://letterSchema" targetNamespace="http://letterSchema"> <xsd:element name="letters" type="letter:FormLetter"/> <xsd:complexType name="FormLetter" mixed="true"> <xsd:sequence> <xsd:element name="date" minOccurs="0" type="xsd:string"/> <xsd:element name="firstName" minOccurs="0" type="xsd:string"/> <xsd:element name="lastName" minOccurs="0" type="xsd:string"/> </xsd:sequence> </xsd:complexType> </xsd:schema> |
The following is an instance letter document. It contains the three letter properties; date, firstName and lastName, and has unstructured text elements for the address and letter body.
<letter:letters xmlns:letter="http://letterSchema"> <date>March 1, 2005</date> Mutual of Omaha Wild Kingdom, USA Dear <firstName>Casy</firstName> <lastName>Crocodile</lastName> Please buy more shark repellent. Your premium is past due. </letter:letters> |
When loaded, the letter data object will have the sequence and property indices shown in the table below:
Sequence Index | Property Index:Name | Value |
---|---|---|
0 | 0:date | March 1, 2005 |
1 | - | Mutual of Omaha |
2 | - | Wild Kingdom, USA |
3 | - | Dear |
4 | 1:firstName | Casy |
5 | 2:lastName | Crocodile |
6 | - | Please buy more shark repellent. |
7 | - | Your premium is past due. |
To ensure sequence indices are maintained, sequenced data objects should be manipulated through the SDO_Sequence interface. This allows the data object's instance data to be manipulated in terms of the sequence index as opposed to the property index (shown in the table above). The following examples assume the letter instance has been loaded into a data object referenced by the variable $letter.
All subsequent examples assume that the $letter_seq variable has been assigned the sequence for the letter data object.
Esempio 14. Get/set sequence values We can get and set individual values (including unstructured text) using the sequence index. The following sets the firstName to 'Snappy' and gets the last sequence values (the unstructured text, 'Your premium is past due.').
|
Esempio 16. Sequence versus Data Object Setting values through the data object interface may result in the value not being part of the sequence. A value set through the data object will only be accessible through the sequence if the property was already part of the sequence. The following example sets the lastName through the data object and gets it through the sequence. This is fine because lastName already exists in the sequence. If it had not previously been set, then lastName would be set to 'Smith', but would not be part of the sequence.
|
Esempio 17. Adding to a sequence We can add new values to a sequence using the SDO_Sequence::insert() method. The following examples assume that the 'firstName' and 'lastName' properties are initially unset.
|
Esempio 18. Removing from a sequence We can use the isset() and unset() functions to test and remove items from the sequence (Note: unset() currently leaves the values in the data object, but this behaviour is likely to change to also remove the data from the data object). A sequence behaves like a contiguous list; therefore, removing items from the middle will shift entries at higher indices down. The following example tests to see if the first sequence element is set and unsets it if is.
|
SDO consists of two sets of interfaces. The first set covers those interfaces for use by SDO client applications. These are identified by the package prefix 'SDO_'. The second set is those for use by Data Access Service implementations and are identified by the package prefix 'SDO_DAS_'. The majority of SDO users will not need to use or understand the 'SDO_DAS_' interfaces.
The main interface through which data objects are manipulated. In addition to the methods below, SDO_DataObject extends the ArrayAccess, SDO_PropertyAccess (defines __get() / __set() methods for property access overloading), Iterator, and Countable interfaces.
getType - get the type of a data object
getSequence - get the sequence for the data object
createDataObject - create a child data object
clear - unset the properties of a data object
getContainer - get the container (also known as 'parent') of this data object
getContainmentPropertyName - get the name by which the parent refers to this data object
The interface through which sequenced data objects can be accessed to preserve ordering across a data object's properties and to allow unstructured text. SDO_Sequence preserves contiguous indices and therefore inserting or removing elements may shift other elements up or down. In addition to the methods below, SDO_Sequence extends the ArrayAccess, Iterator and Countable interface.
getPropertyIndex - get the property index for a given sequence index
getPropertyName - get the property name for a given sequence index
move - move an element from one property index to another
insert - insert a new value into the sequence
The interface through which many-valued properties are manipulated. In addition to the method defined below, SDO_List extends ArrayAccess, Iterator and Countable. SDO_List preserves contiguous indices and therefore inserting or removing elements may shift other elements up or down.
The interface through which data objects can be created. A Data Access Service is responsible for populating the model (i.e. configuring the data factory with the type and structure information for the data objects it can create.) for the factory and can then optionally return an instance of, or implement, the SDO_DataFactory interface.
The interface through which a Data Access Service can access a data object's SDO_DAS_ChangeSummary . The change summary is used by the Data Access Service to check for conflicts when applying changes back to a data source.
The interface through which the change history of a data object is accessed. The change summary holds information for any modifications on a data object which occurred since logging was activated. In the case of deletions and modifications, the old values are also held in the change summary.
If logging is no longer active then the change summary only holds changes made up to the point when logging was deactivated. Reactivating logging clears the change summary. This is useful when a set of changes have been written out by a DAS and the data object is to be reused.
beginLogging - begin logging changes made to a data object
endLogging - end logging changes made to a data object
isLogging - test to see if change logging is on
getChangedDataObjects - get a list of the data objects which have been changed
getChangeType - get the type of change which has been made to a data object
getOldValues - get a list of old values for a data object
getOldContainer - get the old container data object for a deleted data object
The interface through which the old value for a property is accessed. A list of settings is returned by the change summary method getOldValues() .
getPropertyIndex - get the property index for the changed property
getPropertyName - get the property name for the changed property
getValue - get the old value for the changed property
getListIndex - get the list index for the old value if it was part of a many-valued property
isSet - test to see if the property was set prior to being modified
The interface for constructing the model for an SDO_DataObject. The SDO_DAS_DataFactory is an abstract class providing a static method which returns a concrete data factory implementation. The implementation is used by Data Access Services to create an SDO model from their model. For example, a Relational Data Access Service might create and populate an SDO_DAS_DataFactory model based on a schema for a relational database.
getDataFactory - static methods for getting a concrete data factory instance
addType - add a new type to the SDO model
addPropertyToType - add a new property to a type definition in the SDO model
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.
Represents a change type of 'none'.
Represents a change type of 'modification'.
Represents a change type of 'addition'.
Represents a change type of 'deletion'.
(no version information, might be only in CVS)
SDO_DAS_ChangeSummary::beginLogging -- Begin change logging.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Begin logging changes made to the SDO_DataObject.
(no version information, might be only in CVS)
SDO_DAS_ChangeSummary::endLogging -- End change logging.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
End logging changes made to an SDO_DataObject.
(no version information, might be only in CVS)
SDO_DAS_ChangeSummary::getChangeType -- Get the type of change made to an SDO_DataObject.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Get the type of change which has been made to the supplied SDO_DataObject.
The type of change which has been made. The change type is expressed as an enumeration and will be one of the following four values:
SDO_DAS_ChangeSummary::NONE
SDO_DAS_ChangeSummary::MODIFICATION
SDO_DAS_ChangeSummary::ADDITION
SDO_DAS_ChangeSummary::DELETION
(no version information, might be only in CVS)
SDO_DAS_ChangeSummary::getChangedDataObjects -- Get the changed data objects from a change summary.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Get an SDO_List of the SDO_DataObjects which have been changed. These data objects can then be used to identify the types of change made to each, along with the old values.
(no version information, might be only in CVS)
SDO_DAS_ChangeSummary::getOldContainer -- Get the old container for a deleted SDO_DataObject.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Get the old container (SDO_DataObject) for a deleted SDO_DataObject.
The SDO_DataObject which has been deleted and whose container we wish to identify.
(no version information, might be only in CVS)
SDO_DAS_ChangeSummary::getOldValues -- Get the old values for a given changed SDO_DataObject.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Get a list of the old values for a given changed SDO_DataObject. Returns a list of SDO_DAS_Settings describing the old values for the changed properties of the SDO_DataObject.
A list of SDO_DAS_Settings describing the old values for the changed properties of the SDO_DataObject
(no version information, might be only in CVS)
SDO_DAS_ChangeSummary::isLogging -- Test to see whether change logging is switched on.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Test to see whether change logging is switched on.
(no version information, might be only in CVS)
SDO_DAS_DataFactory::addPropertyToType -- Adds a property to a type.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Adds a property to a type. The type must already be known to the SDO_DAS_DataFactory (i.e. have been added using addType()). The property becomes a property of the type. This is how the graph model for the structure of an SDO_DataObject is built.
The namespace URI for the parent type.
The type name for the parent type.
The name by which the property will be known in the parent type.
The namespace URI for the type of the property.
The type name for the type of the property
This array holds one or more key=>value pairs to set attribute values for the property. The optional keywords are:
A flag to say whether the property is many-valued. A value of 'true' adds the property as a many-valued property (default is 'false').
A flag to say whether the property is read-only. A value of 'true' means the property value cannot be modified through the SDO application APIs (default is 'false').
A flag to say whether the property is contained by the parent. A value of 'true' means the property is contained by the parent. A value of 'false' results in a non-containment reference (default is 'true'). This flag is only interpreted when adding properties which are data object types, otherwise it is ignored.
A default value for the property. Omitting this key means that the property does not have a default value. A property can only have a default value if it is a single-valued data type (primitive).
Esempio 1. A SDO_DAS_DataFactory::addPropertyToType() example The following adds an 'addressline' property to a Person type. The person type is identified by its namespace, 'PersonNS', and type name, 'PersonType'. The type of the 'addressline' property is a many-valued SDO data type (primitive) with namespace 'commonj.sdo' and type name 'String'.
|
(no version information, might be only in CVS)
SDO_DAS_DataFactory::addType -- Add a new type to a model.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Add a new type to the SDO_DAS_DataFactory, defined by its namespace and type name. The type becomes part of the model of data objects that the data factory can create.
(no version information, might be only in CVS)
SDO_DAS_DataFactory::getDataFactory -- Get a data factory instance.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Static method to get an instance of an SDO_DAS_DataFactory. This instance is initially only configured with the basic SDO types. A Data Access Service is responsible for populating the data factory model and then allowing PHP applications to create SDOs based on the model through the SDO_DataFactory interface. PHP applications should always obtain a data factory from a configured Data Access Service, not through this interface.
(no version information, might be only in CVS)
SDO_DAS_DataObject::getChangeSummary -- Get a data object's change summary.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Get the SDO_DAS_ChangeSummary for an SDO_DAS_DataObject, or NULL if it does not have one.
Returns the SDO_DAS_ChangeSummary for an SDO_DAS_DataObject, or NULL if it does not have one.
(no version information, might be only in CVS)
SDO_DAS_Setting::getListIndex -- Get the list index for a changed many-valued property.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Get the list index for a modification made to an element of a many-valued property. For example, if we modified the third element of a many-valued property we could obtain an SDO_DAS_Setting from the change summary corresponding to that modification. A call to getListIndex() on that setting would return the value 2 (lists are indexed from zero).
The list index for the element of the many-valued property which has been changed.
(no version information, might be only in CVS)
SDO_DAS_Setting::getPropertyIndex -- Get the property index for a changed property.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Returns the property index for the changed property. This index identifies the property which was modified in data object.
(no version information, might be only in CVS)
SDO_DAS_Setting::getPropertyName -- Get the property name for a changed property.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Returns the property name for the changed property. This name identifies the property which was modified in data object.
(no version information, might be only in CVS)
SDO_DAS_Setting::getValue -- Get the old value for the changed property.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Returns the old value for the changed property. This can be used by a Data Access Service when writing updates to a data source. The DAS uses the old value to detect conflicts by comparing it with the current value in the data source. If they do not match, then the data source has been updated since the data object was originally populated, and therefore writing any new updates risks compromising the integrity of the data.
(no version information, might be only in CVS)
SDO_DAS_Setting::isSet -- Test whether a property was set prior to being modified.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Test whether a property was set prior to being modified. If it was set prior to being modified then the SDO_DAS_Setting will also contain the old value.
Returns TRUE if the property was set prior to being modified, otherwise returns 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. |
Create a new SDO_DataObject given the data object's namespace URI and type name.
Thrown if the namespaceURI and typeName do not correspond to a type known to this data factory.
(no version information, might be only in CVS)
SDO_DataObject::clear -- Clear an SDO_DataObject's properties.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Clear an SDO_DataObject's properties. Read-only properties are unaffected. Subsequent calls to isset() for the data object will return FALSE.
(no version information, might be only in CVS)
SDO_DataObject::createDataObject -- Create a child SDO_DataObject.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Create a child SDO_DataObject of the default type for the property identified. The data object is automatically inserted into the tree and a reference to it is returned.
Identifies the property for the data object type to be created. Can be either a property name (string), or property index (int).
Thrown if the identifier does not correspond to a property of the data object.
(no version information, might be only in CVS)
SDO_DataObject::getContainer -- Get a data object's container.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Get the data object which contains this data object.
Returns the SDO_DataObject which contains this SDO_DataObject, or returns NULL if this is a root SDO_DataObject (i.e. it has no container).
(no version information, might be only in CVS)
SDO_DataObject::getContainmentPropertyName -- Get the container's property 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. |
Get the property name used to refer to this data object by its containing data object.
Returns the name of the container's property which references this SDO_DataObject, or returns NULL if this is a root SDO_DataObject (i.e. it has no container).
(no version information, might be only in CVS)
SDO_DataObject::getSequence -- Get the sequence for a data object.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Return the SDO_Sequence for this SDO_DataObject. Accessing the SDO_DataObject through the SDO_Sequence interface acts on the same SDO_DataObject instance data, but preserves ordering across properties.
The SDO_Sequence for this SDO_DataObject, or returns NULL if the SDO_DataObject is not of a type which can have a sequence.
(no version information, might be only in CVS)
SDO_DataObject::getType -- Get the type of a data object.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Return an array containing the type information for an SDO_DataObject. The first element contains the namespace URI string and the second contains the type name string.
An array containing the namespace URI string and the type name string for the data object.
Esempio 1. A SDO_DataObject::getType() example For example, if the SDO_DataObject were of type 'CompanyType' from the namespace 'CompanyNS', then getType() would return the equivalent to array('CompanyNS', 'CompanyType'):
Il precedente esempio visualizzerà:
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Insert a new element at a specified position in the list. All subsequent list items are moved up.
The new value to be inserted. This can be either a primitive or an SDO_DataObject.
The position at which to insert the new element. If this argument is not specified then the new value will be appended.
Thrown if the list index is less than zero or greater than the size of the list.
Thrown if the type of the new value does not match the type for the list (e.g. the type of the many-valued property that the list represents).
(no version information, might be only in CVS)
SDO_Sequence::getPropertyIndex -- Return the property index for the specified sequence index.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Return the property index for the specified sequence index. If the sequence item is unstructured text rather than a data object property, then a value of -1 is returned.
The sequence index for which we wish to determine the associated data object property index.
The corresponding property index. A value of -1 means the element does not belong to a property and must therefore be unstructured text.
Thrown if the sequence index is less than zero or greater than the size of the sequence.
(no version information, might be only in CVS)
SDO_Sequence::getPropertyName -- Return the property name for the specified sequence index.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Return the property name for the specified sequence index. If the sequence item is unstructured text rather than a data object property, then a value of NULL is returned.
The sequence index for which we wish to determine the associated data object property name.
The corresponding property name. A value of NULL means the element does not belong to a property and must therefore be unstructured text.
Thrown if the sequence index is less than zero or greater than the size of the sequence.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Insert a new element at a specified position in the sequence. All subsequent sequence items are moved up.
The new value to be inserted. This can be either a primitive or an SDO_DataObject.
The position at which to insert the new element. Default is NULL, which results in the new value being appended to the sequence.
Either a property index or property name, used to identify a property in the sequence's corresponding SDO_DataObject. A value of NULL signifies unstructured text.
Thrown if the sequence index is less than zero or greater than the size of the sequence.
Thrown if the type of the new value cannot be juggled to match the type for the specified data object property.
(no version information, might be only in CVS)
SDO_Sequence::move -- Move an item to another sequence 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. |
Modify the position of the item in the sequence, without altering the value of the property in the SDO_DataObject.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
In order to use the XML Data Access Service for Service Data Objects, you will need to understand some of the concepts behind SDO: the data graph, the data object, XPath and property expressions, and so on. If you are not familiar with these ideas, you might want to look first at the section on SDO .
The job of the XML DAS is to move data between the application and an XML data source, which can be either a file or a URL. In order to do this it needs to be told the location of the XML schema, which is passed as a parameter to the create method of the XML DAS. The schema is used to ensure conformance of XML being written out, and also to ensure that modifications made to an SDO originating from XML follow the model described by the XML schema.
The SDO XML Data Access Service requires PHP 5.1 or higher. It is packaged with the SDO extension and requires SDO to have been installed. See the SDO installation instructions for the details of how to do this.
The XML Data Access Service is packaged and installed as part of the SDO extension. Please Refer SDO installation instructions.
The SDO 2.0 specification defines the mapping between XML types and SDO types. With Java SDO, this mapping is implemented by the XMLHelper. With SDO for PHP, this mapping is implemented by the XML Data Access Services. The XML DAS implements the mapping described in the SDO 2.0 specification with the following restrictions:
Simple Type with abstract="true" - no PHP support for SDO abstract types.
Simple Type with sdoJava:instanceClass - no PHP equivalent provided.
Simple Type with sdoJava:extendedInstanceClass - no PHP equivalent provided.
Simple Type with list of itemType.
Simple Type with union.
Complex Type with abstract="true" - no PHP support for SDO abstract types.
Complex Type with sdo:aliasName - no PHP support for SDO Type aliases.
Complex Type with open content - no PHP support for SDO open types.
Complex Type with open attribute - no PHP support for SDO open types.
Attribute with sdo:aliasName - no PHP support for SDO property aliases.
Attribute with default value - no PHP support for SDO property defaults.
Attribute with fixed value - no PHP support for SDO read-only properties or default values.
Attribute reference.
Attribute with sdo:string - no support for sdo:string="true".
Attribute referencing a DataObject with sdo:propertyType - no support for sdo:propertyType="...".
Attribute with bi-directional property to a DataObject with sdo:oppositeProperty and sdo:propertyType - no PHP support for SDO opposite.
Element with sdo:aliasName - no PHP support for SDO property aliases.
Element reference.
Element with nillable.
Element with substitution group.
Element of SimpleType with default - no PHP support for SDO defaults
Element of SimpleType with fixed value - no PHP support for SDO read-only properties or default values.
Element of SimpleType with sdo:string - no support for sdo:string="true".
Element referencing a DataObject with sdo:propertyType - no support for sdo:propertyType="..."
Element with bi-directional reference to a DataObject with sdo:oppositeProperty and sdo:propertyType - no PHP support for SDO opposite.
The following examples are based on the letter example described in the SDO documentation. The examples assume the XML Schema for the letter is contained in a file letter.xsd and the letter instance is in the file letter.xml. These two files are reproduced here:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:letter="http://letterSchema" targetNamespace="http://letterSchema"> <xsd:element name="letters" type="letter:FormLetter"/> <xsd:complexType name="FormLetter" mixed="true"> <xsd:sequence> <xsd:element name="date" minOccurs="0" type="xsd:string"/> <xsd:element name="firstName" minOccurs="0" type="xsd:string"/> <xsd:element name="lastName" minOccurs="0" type="xsd:string"/> </xsd:sequence> </xsd:complexType> </xsd:schema> |
<letter:letters xmlns:letter="http://letterSchema"> <date>March 1, 2005</date> Mutual of Omaha Wild Kingdom, USA Dear <firstName>Casy</firstName> <lastName>Crocodile</lastName> Please buy more shark repellent. Your premium is past due. </letter:letters> |
Esempio 1. Loading, altering, and saving an XML document The following example shows how an XML document can be loaded from a file, altered, and written back.
An instance of the XML DAS is first obtained from the SDO_DAS_XML::create() method, which is a static method of the SDO_DAS_XML class. The location of the xsd is passed as a parameter. Once we have an instance of the XML DAS initialised with a given schema, we can use it to load the instance document using the loadFromFile() method. There is also a loadFromString() method if you want to load an XML instance document from a string. If the instance document loads successfully, you will be returned an object of type SDO_DAS_XML_Document, on which you can call the getRootDataObject() method to get the SDO data object which is the root of the SDO data graph. You can then use SDO operations to change the graph. In this example we alter the date, firstName, and lastName properties. Then we use the saveDocumentToFile() method to write the changed document back to the file system. This will write the following to letter-out.xml.
|
Esempio 2. Creating a new XML document The previous example loaded the document from a file. This example shows how to create an SDO data graph in memory. In this example it is then saved to an XML string. Furthermore, because the letter contains both structured and unstructured content, it uses the Sequence API as well assignments to properties to construct the data graph.
|
This will emit the following output (line breaks have been inserted for readability):
<?xml version="1.0" encoding="UTF-8"?> <FormLetter xmlns="http://letterSchema" xsi:type="FormLetter" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <date>April 09, 2005</date> Acme Inc. United Kingdom. Dear <firstName>Tarun</firstName> <lastName>Nayar</lastName> Please note that your order number 12345 has been dispatched today. Thanks for your business with us. </FormLetter> |
Esempio 3. Setting XML document properties This third example shows you how to use the SDO_DAS_XML_Document class. SDO_DAS_XML_Document class is provided to get and set properties of the XML declaration such as version, schema location, encoding and so on.
The first three lines of output show how the encoding and XML version has been obtained from the document, and how the XML version has been set in the XML header.
|
The XML DAS provides three classes. The SDO_DAS_XML which is the main class used to fetch the data from the XML source and also can used to write the data back. The next one is SDO_DAS_XML_Document class, which is basically useful to get/set the XML declarations such as encoding, version etc. And the last class is SDO_DAS_XML_ParserException which will be thrown for any parser exceptions while loading xsd/xml file.
This is the main class of XML DAS, which is used fetch the data from the xml source and also used to write the data back. Other than the methods to load and save xml files, it also has a method called createDataObject which can be used to create an empty DataObject of a given type.
create This is the only static method available in SDO_DAS_XML class. Used to construct SDO_DAS_XML object.
createDataObject Can be used to construct the DataObject of a given type.
loadFromFile Loads the xml instance document from a file. This file can be at local file system or it can be on a remote host.
loadFromString same as the above method. Loads the xml instance which is available as string.
saveDataObjectToFile save SDO_DataObject to a file.
saveDataObjectToString save SDO_DataObject to a xml file.
saveDocumentToFile save SDO_DAS_XML_Document object as a xml file.
saveDocumentToString save SDO_DAS_XML_Document object as a xml string.
This class can be used to get/set XML Declarations such as encoding, schema location etc.
getEncoding gets the encoding string.
getNoNamespaceSchemaLocation gets the no namespace schema location.
getRootDataObject gets the root DataObject.
getRootElementName gets the root DataObject's name.
getRootElementURI gets the root DataObject's URI.
getSchemaLocation gets schema location.
getXMLDeclaration gets whether xml declaration is set ot not.
getXMLVersion gets the xml version.
setEncoding sets the encoding string with the given value.
setNoNamespaceSchemaLocation sets the no namespace schema location with the given value.
setSchemaLocation sets the schema location with the given value.
setXMLDeclaraion to set/unset the xml declaration.
setXMLVersion sets the xml version with the given value.
Is a subclass of SDO_Exception . Thrown for any parser errors while loading the xsd/xml file.
(no version information, might be only in CVS)
SDO_DAS_XML_Document::getEncoding -- Returns encoding 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. |
Returns the encoding string for the SDO_DAS_XML_Document object.
(no version information, might be only in CVS)
SDO_DAS_XML_Document::getNoNamespaceSchemaLocation -- Returns no namespace schema location.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Returns the no namespace schema location.
(no version information, might be only in CVS)
SDO_DAS_XML_Document::getRootDataObject -- Returns the root SDO_DataObject.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Returns the root SDO_DataObject.
(no version information, might be only in CVS)
SDO_DAS_XML_Document::getRootElementName -- Returns root element's 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. |
Returns root element's name.
(no version information, might be only in CVS)
SDO_DAS_XML_Document::getRootElementURI -- Returns root element's URI 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. |
Returns root element's URI string.
(no version information, might be only in CVS)
SDO_DAS_XML_Document::getSchemaLocation -- Returns schema location.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Returns schema location.
(no version information, might be only in CVS)
SDO_DAS_XML_Document::getXMLDeclaration -- Returns whether the xml declaration is set or not.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Returns whether the xml declaration is set or not.
Returns whether the xml declaration is set or not. TRUE If it is set and FALSE if it is not.
(no version information, might be only in CVS)
SDO_DAS_XML_Document::getXMLVersion -- Returns xml declaration 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. |
Returns xml declaration string.
(no version information, might be only in CVS)
SDO_DAS_XML_Document::setEncoding -- Sets the given string as encoding.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Sets the given string as encoding.
(no version information, might be only in CVS)
SDO_DAS_XML_Document::setNoNamespaceSchemaLocation -- Sets the given string as no namespace schema location.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Sets the given string as no namespace schema location.
(no version information, might be only in CVS)
SDO_DAS_XML_Document::setSchemaLocation -- Sets the given string as schema location.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Sets the given string as schema location.
(no version information, might be only in CVS)
SDO_DAS_XML_Document::setXMLDeclaration -- Sets the xml declaration.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Sets the given given boolean value for xml declaration. Pass TRUE to set it and FLASE to not to unset it.
(no version information, might be only in CVS)
SDO_DAS_XML_Document::setXMLVersion -- Sets the given string as xml 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. |
Sets the given string as xml version.
(no version information, might be only in CVS)
SDO_DAS_XML::create -- To create SDO_DAS_XML object for a given schema file.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
This is the only static method of SDO_DAS_XML class. Used to instantiate SDO_DAS_XML object.
Returns SDO_DAS_XML object on success otherwise throws an exception as described below.
Thrown if a type is not defined in the underlying model.
Thrown for any symantical problems while parsing the given XSD File.
(no version information, might be only in CVS)
SDO_DAS_XML::createDataObject -- Creates SDO_DataObject for a given namespace URI and type name.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Creates SDO_DataObject for a given namespace URI and type name. The type should be defined in the underlying model otherwise SDO_TypeNotFoundException will be thrown.
(no version information, might be only in CVS)
SDO_DAS_XML::loadFromFile -- Returns SDO_DAS_XML_Document object for a given path to xml instance document.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Constructs the tree of SDO_DataObjects from the given address to xml instance document. Returns SDO_DAS_XML_Document Object. Use SDO_DAS_XML_Document::getRootDataObject method to get root data object.
Path to Instance document. This can be a path to a local file or it can be a URL.
Thrown if a type is not defined by the underlying model.
Thrown if the a property within a type is not defined in the underlying model.
Thrown for any symantical problems while parsing the given XSD File.
(no version information, might be only in CVS)
SDO_DAS_XML::loadFromString -- Returns SDO_DAS_XML_Document for a given xml instance string.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Constructs the tree of SDO_DataObjects from the given xml instance string. Returns SDO_DAS_XML_Document Object. Use SDO_DAS_XML_Document::getRootDataObject method to get root data object.
Thrown if a type is not defined by the underlying model.
Thrown if the a property within a type is not defined in the underlying model.
Thrown for any problems while parsing the given XSD File.
(no version information, might be only in CVS)
SDO_DAS_XML::saveDataObjectToFile -- Saves the SDO_DataObject object to File.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Saves the SDO_DataObject object as an XML File.
DataObject, which needs to be saves as an XML File.
URI string for the root DataObject.
Type name of the root DataObject.
(no version information, might be only in CVS)
SDO_DAS_XML::saveDataObjectToString -- Saves the SDO_DataObject object to 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. |
Saves the SDO_DataObject object as an XML string.
DataObject, which needs to be saves as an XML File.
URI string for the root DataObject.
Type name of the root DataObject.
(no version information, might be only in CVS)
SDO_DAS_XML::saveDocumentToFile -- Saves the SDO_DAS_XML_Document object to a file.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Saves the SDO_DAS_XML_Document object to a file.
(no version information, might be only in CVS)
SDO_DAS_XML::saveDocumentToString -- Saves the SDO_DAS_XML_Document object to a 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. |
Saves the SDO_DAS_XML_Document object to string.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
In order to use the Relational Data Access Service for Service Data Objects, you will need to understand some of the concepts behind SDO: the data graph, the data object, the disconnected way of working, the change summary, XPath and property expressions, and so on. If you are not familiar with these ideas, you might want to look first at the section on SDO. In addition, the Relational DAS makes use of the PDO extension to isolate itself from specifics of different back-end relational databases. In order to use the Relational DAS you will need to be able to create and pass a PDO database connection; for this reason you might also want to take a look at the section on PDO.
The job of the Relational DAS is to move data between the application and a relational database. In order to do this it needs to be told the mapping between the database entities - tables, columns, primary keys and foreign keys - and the elements of the SDO model - types, properties, containment properties and so on. You specify this information as metadata when you construct the Relational DAS.
The first step is to call the Relational DAS's constructor, passing the metadata that defines the mapping between database and SDO model. There are examples of this below.
The next step might be to call the executeQuery() or executePreparedQuery() methods on the Relational DAS, passing either a literal SQL statement for the DAS to prepare and execute, or a prepared statement with placeholders and a list of values to be inserted. You may also need to specify a small amount of metadata about the query itself, so that the Relational DAS knows exactly what columns will be returned from the database and in what order. You will also need to pass a PDO database connection.
The return value from executeQuery() or executePreparedQuery() is a normalised data graph containing all the data from the result set. For a query that returns data obtained from a number of tables, this graph will contain a number of data objects, linked by SDO containment references. There may also be SDO non-containment references within the data.
Once the query has been executed and the data graph constructed, there is no need for either that instance of the the Relational DAS or the database connection. There are no locks held on the database. Both the Relational DAS and the PDO database connection can be garbage collected.
Quite possibly the data in the data graph will go through a number of modifications. The data graph can be serialised into the PHP session and so may have a lifetime beyond just one client-server interaction. Data objects can be created and added to the graph, the data objects already in the graph can be deleted, and data objects in the graph can be modified.
Finally, the changes made to the data graph can be applied back to the database using the applyChanges() method of the Relational DAS. For this, another instance of the Relational DAS must be constructed, using the same metadata, and another connection to the database obtained. The connection and the data graph are passed to applyChanges(). At this point the Relational DAS examines the change summary and generates the necessary INSERT, UPDATE and DELETE SQL statements to apply the changes. Any UPDATE and DELETE statements are qualified with the original values of the data so that should the data have changed in the database in the meantime this will be detected. Assuming no such collisions have occurred the changes will be committed to the database. The application can then continue to work with the data graph, make more changes and apply them, or can discard it.
There are other ways of working with the data in the database: it is possible to just create data objects and write them to the database without a preliminary call to executeQuery(), for example. This scenario and others are explored in the Examples section below.
The installation instructions for all the SDO components are in the SDO install section of the SDO documentation.
In any case, the essential facts are that the Relational DAS is written in PHP and it should be placed somewhere on the PHP include_path .
Your application will of course need to include the Relational DAS with a statement like this:
<?php require_once 'SDO/DAS/Relational.php'; ?> |
The Relational DAS requires that the SDO extension be installed. The SDO extension requires a version of PHP 5.1, and the Relational DAS requires a recent version that contains an important fix for PDO. The most up-to-date information about required levels of PHP should be found in the changelog for the package on PECL. At the time of writing, though, the Relational DAS requires the most recent beta level of PHP 5.1, that is PHP 5.1.0b3.
The Relational DAS uses PDO to access the relational database, and so should run with a variety of different relational databases. At the time of writing it has been tested in the following configurations
MySQL 4.1.17, on Windows. The Relational DAS operates correctly with the php_pdo_mysql driver that comes with the pre-built binaries for PHP 5.1.0b3.
MySQL 4.1.17, on Linux. It is necessary to have the most up-to-date PDO driver for MySQL, which comes built in to PHP 5.1.0b3. It may be necessary to uninstall the usual driver that would have come from PECL using pear uninstall pdo_mysql . You will need to configure PHP with the --with-pdo-mysql option.
DB2 8.2 Personal Edition, on Windows. The Relational DAS operates correctly with the php_pdo_odbc driver that comes with the pre-built binaries for PHP 5.1.0b3.
DB2 8.2 Personal Developer's Edition, on Linux. The Developer's Edition is needed because it contains the include files needed when PHP is configured and built. You will need to configure PHP with the --with-pdo-odbc=ibm-db2 option.
The Relational DAS applies changes to the database within a user-delimited transaction: that is, it issues a call to PDO::beginTransaction() before beginning to apply changes, and PDO::commit() or PDO::rollback() on completion. Whichever database is chosen, the database and the PDO driver for the database must support these calls.
There are the following limitations in the current release of the Relational DAS:
No support for nulls. There is no support for SQL NULL type. It is not legal to assign PHP NULL to a data object property and the Relational DAS will not write that back as a NULL to the database. If nulls are found in the database on a query, the property will remain unset.
Only two types of SDO relationship. The metadata described below allows the Relational DAS to model just two types of SDO relationship: multi-valued containment properties and single-valued non-containment properties. In SDO, whether a property is single- or multi-valued, and whether it is containment or non-containment, are independent. The full range of possibilities that SDO allows cannot all be defined. There may be relationships that it would be useful to model but which the current implementation cannot manage. One example is a single-valued containment relationship.
No support for the full range of SDO data types. The Relational DAS defines all primitive properties in the SDO model as being of type string. SDO defines a richer set of types containing various integer, float, boolean and data and time types. String is adequate for the purposes of the Relational DAS since the combination of PHP, PDO and the database will ensure that values passed as strings will be converted to the proper type before being put in the database. This does affect some scenarios in which the Relational DAS has to work with a data graph that has come from or will go to a different DAS.
Only one foreign key per table. The metadata only provides the means to specify one foreign key per table. This foreign key may be mapped to one of the two types of SDO relationship supported. Obviously there are some scenarios that cannot be described under this limitation - it is not possible to have two non-containment references from one table to another for example.
This section illustrates how the Relational DAS can be used to create, retrieve, update and delete data in a relational database. Many of the examples are illustrated with a three-table database that contains companies, departments within those companies, and employees that work in those departments. This example is used in a number of places within the SDO literature. See the examples section of the Service Data Objects specification or the Examples section of the documentation for the SDO extension.
The Relational DAS is constructed with metadata that defines the relational database and how it should be mapped to SDO. The long section that follows describes this metadata and how to construct the Relational DAS. The examples that follow it all assume that this metadata is in an included php file.
The examples below and others can all be found in the Scenarios directory in the Relational DAS package.
The Relational DAS throws exceptions in the event that it finds errors in the metadata or errors when executing SQL statements against the database. For brevity the examples below all omit the use of try/catch blocks around the calls to the Relational DAS.
These examples all differ from the expected use of SDO in two important respects.
First, they show all interactions with the database completed within one script. In this respect these scenarios are not realistic but are chosen to illustrate just the use of the Relational DAS. It is expected that interactions with the database will be separated in time and the data graph serialised and deserialised into the PHP session one or more times as the application interacts with an end user.
Second, all queries executed against the database use hard-coded queries with no variables substituted. In this case it is safe to use the simple executeQuery() call, and this is what the examples illustrate. In practice, though, it is unlikely that the SQL statement is known entirely ahead of time. In order to allow variables to be safely substituted into the SQL queries, without running the risk of injecting SQL with unknown effects, it is safer to use the executePreparedQuery() which takes a prepared SQL statement containing placeholders and a list of values to be substituted.
This first long section describes in detail how the metadata describing the database and the required SDO model is supplied to the Relational DAS.
When the constructor for the Relational DAS is invoked, it needs to be passed several pieces of information. The bulk of the information, passed as an associative array in the first argument to the constructor, tells the Relational DAS what it needs to know about the relational database. It describes the names of the tables, columns, primary keys and foreign keys. It should be fairly easy to understand what is required, and once written it can be placed in a php file and included when needed. The remainder of the information, passed in the second and third arguments to the constructor, tells the Relational DAS what it needs to know about the relationships between objects and the shape of the data graph; it ultimately determines how the data from the database is to be normalised into a graph.
The first argument to the constructor describes the target relational database.
Each table is described by an associative array with up to four keys.
Key | Value |
---|---|
name | The name of the table. |
columns | An array listing the names of the columns, in any order. |
PK | The name of the column containing the primary key. |
FK | An array with two entries, 'from' and 'to', which define a column containing a foreign key, and a table to which the foreign key points. If there are no foreign keys in the table then the 'FK' entry does not need to be specified. Only one foreign key can be specified. Only a foreign key pointing to the primary key of a table can be specified. |
<?php /***************************************************************** * METADATA DEFINING THE DATABASE ******************************************************************/ $company_table = array ( 'name' => 'company', 'columns' => array('id', 'name', 'employee_of_the_month'), 'PK' => 'id', 'FK' => array ( 'from' => 'employee_of_the_month', 'to' => 'employee', ), ); $department_table = array ( 'name' => 'department', 'columns' => array('id', 'name', 'location', 'number', 'co_id'), 'PK' => 'id', 'FK' => array ( 'from' => 'co_id', 'to' => 'company', ) ); $employee_table = array ( 'name' => 'employee', 'columns' => array('id', 'name', 'SN', 'manager', 'dept_id'), 'PK' => 'id', 'FK' => array ( 'from' => 'dept_id', 'to' => 'department', ) ); $database_metadata = array($company_table, $department_table, $employee_table); ?> |
This metadata corresponds to a relational database that might have been defined to MySQL as:
create table company ( id integer auto_increment, name char(20), employee_of_the_month integer, primary key(id) ); create table department ( id integer auto_increment, name char(20), location char(10), number integer(3), co_id integer, primary key(id) ); create table employee ( id integer auto_increment, name char(20), SN char(4), manager tinyint(1), dept_id integer, primary key(id) ); |
or to DB2 as:
create table company ( \ id integer not null generated by default as identity, \ name varchar(20), \ employee_of_the_month integer, \ primary key(id) ) create table department ( \ id integer not null generated by default as identity, \ name varchar(20), \ location varchar(10), \ number integer, \ co_id integer, \ primary key(id) ) create table employee ( \ id integer not null generated by default as identity, \ name varchar(20), \ SN char(4), \ manager smallint, \ dept_id integer, \ primary key(id) ) |
Note that although in this example there are no foreign keys specified to the database and so the database is not expected to enforce referential integrity, the intention behind the co_id column on the department table and the dept_id column on the employee table is they should contain the primary key of their containing company or department record, respectively. So these two columns are acting as foreign keys.
There is a third foreign key in this example, that from the employee_of_the_month column of the company record to a single row of the employee table. Note the difference in intent between this foreign key and the other two. The employee_of_the_month column represents a single-valued relationship: there can be only one employee of the month for a given company. The co_id and dept_id columns represent multi-valued relationships: a company can contain many departments and a department can contain many employees. This distinction will become evident when the remainder of the metadata picks out the company-department and department-employee relationships as containment relationships.
There are a few simple rules to be followed when constructing the database metadata:
All tables must have primary keys, and the primary keys must be specified in the metadata. Without primary keys it is not possible to keep track of object identities. As you can see from the SQL statements that create the tables, primary keys can be auto-generated, that is, generated and assigned by the database when a record is inserted. In this case the auto-generated primary key is obtained from the database and inserted into the data object immediately after the row is inserted into the database.
It is not necessary to specify in the metadata all the columns that exist in the database, only those that will be used. For example, if the company table had another column that the application did not want to access with SDO, this need not be specified in the metadata. On the other hand it would have done no harm to specify it: if specified in the metadata but never retrieved, or assigned to by the application, then the unused column will not affect anything.
In the database metadata note that the foreign key definitions identify not the destination column in the table which is pointed to, but the table name itself. Strictly, the relational model permits the destination of a foreign key to be a non-primary key. Only foreign keys that point to a primary key are useful for constructing the SDO model, so the metadata specifies the table name. It is understood that the foreign key points to the primary key of the given table.
Given these rules, and given the SQL statements that define the database, the database metadata should be easy to construct.
The Relational DAS uses the database metadata to form most of the SDO model. For each table in the database metadata, an SDO type is defined. Each column which can represent a primitive value (columns which are not defined as foreign keys) are added as properties to the SDO type.
All primitive properties are given a type of string in the SDO model, regardless of their SQL type. When writing values back to the database the Relational DAS will create SQL statements that treat the values as strings, and the database will convert them to the appropriate type.
Foreign keys are interpreted in one of two ways, depending on the metadata in the third argument to the constructor that defines the SDO containment relationships. A discussion of this is therefore deferred until the section on SDO containment references below.
The second argument to the constructor is the application root type. The true root of each data graph is an object of a special root type and all application data objects come somewhere below that. Of the various application types in the SDO model, one has to be the application type immediately below the root of the data graph. If there is only one table in the database metadata, the application root type can be inferred, and this argument can be omitted.
The third argument to the constructor defines how the types in the model are to be linked together to form a graph. It identifies the parent-child relationships between the types which collectively form a graph. The relationships need to be supported by foreign keys to be found in the data, in a way shortly to be described.
The metadata is an array containing one or more associative arrays, each of which identifies a parent and a child. The example below shows a parent-child relationship from company to department, and another from department to employee. Each of these will become an SDO multi-valued containment property in the SDO model.
<?php $department_reference = array( 'parent' => 'company', 'child' => 'department'); $employee_reference = array( 'parent' => 'department', 'child' => 'employee'); $SDO_reference_metadata = array($department_reference, $employee_reference); ?> |
Foreign keys in the database metadata are interpreted as either multi-valued containment properties or single-valued non-containment properties, depending on whether they have a corresponding SDO containment reference specified in the metadata. In the example here, the foreign keys from department to company (the co_id column in the department table) and from employee to department (the dept_id column in the employee table) are interpreted as supporting the SDO containment references. Each containment reference mentioned in the SDO containment references metadata must have a corresponding foreign key present in the database and defined in the database metadata. The values of the foreign key columns for containment references do not appear in the data objects, instead they are represented by the containment reference from the parent to the child. So the co_id column in the department row in the database, for example, does not appear as a property on the department type, but instead as a containment relationship called department on the company type. Note that the foreign key and the parent-child relationship appear to have opposite senses: the foreign key points from the department to the company, but the parent-child relationship points from company to department.
The third foreign key in this example, the employee_of_the_month , is handled differently. This is not mentioned in the SDO containment references metadata. As a consequence this is interpreted in the second way: it becomes a single-valued non-containment reference on the company object, to which can be assigned references to SDO data objects of the employee type. It does appear as a property on the company type. The way to assign a value to it in the SDO data graph is to have a graph that contains an employee object through the containment references, and to assign the object to it. This is illustrated in the later examples below.
The following set of examples all use the Relational DAS to work with a data graph containing just one application data object, a single company and the data just to be found the company table. These examples do not exercise the power of SDO or the Relational DAS and of course the same result could be achieved more economically with direct SQL statements but they are intended to illustrate how to work with the Relational DAS.
For this very simple scenario it would be possible to simplify the database metadata to include just the company table - if that were done the second and third arguments to the constructor and the column specifier used in the query example would become optional.
Esempio 1. Creating a data object The simplest example is that of creating a single data object and writing it to the database. In this example a single company object is created, its name is set to 'Acme', and the Relational DAS is called to write the changes to the database. The company name is set here using the property name method. See the Examples section on the SDO extension for other ways of accessing the properties of an object. Data objects can only be created when you have a data object to start with, however. It is for that reason that the first call to the Relational DAS here is to obtain a root object. This is in effect how to ask for an empty data graph - the special root object is the true root of the tree. The company data object is then created with a call to createDataObject() on the root object. This creates the company data object and inserts it in the graph by inserting into a multi-valued containment property on the root object called 'company'. When the Relational DAS is called to apply the changes a simple insert statement 'INSERT INTO company (name} VALUES ("Acme");' will be constructed and executed. The auto-generated primary key will be set into the data object and the change summary will be reset, so that it would be possible to continue working with the same data object, modify it, and apply the newer changes a second time.
|
Esempio 2. Retrieving a data object In this example a single data object is retrieved from the database - or possibly more than one if there is more than one company called 'Acme'. For each company returned, the name and id properties are echoed. In this example the third argument to executeQuery(), the column specifier is needed as there are other tables in the metadata with column names of name and id. If there were no possible ambiguity it could be omitted.
|
Esempio 3. Updating a data object This example combines the previous two, in the sense that in order to be updated the object must first be retrieved. The application code reverses the company name (so 'Acme' becomes 'emcA') and then the changes are written back to the database in the same way that they were when the object was created. Because the query searches for the name both ways round the program can be run repeatedly to find the company and reverse its name each time. In this example the same instance of the Relational DAS is reused for the applyChanges(), as is the PDO database handle. This is quite alright; it also alright to allow the previous instances to be garbage collected and to obtain new instances. No state data regarding the graph is held the Relational DAS once it has returned a data graph to the application. All necessary data is either within the graph itself, or can be reconstructed from the metadata.
|
Esempio 4. Deleting a data object Any companies called 'Acme' or its reverse 'emcA' are retrieved. They are then all deleted from the graph with unset. In this example they are all deleted in one go by unsetting the containing reference. It is also possible to delete them individually.
|
The following set of examples all use two tables from the company database: the company and department tables. These examples exercise more of the function of the Relational DAS.
In this series of examples a company and department are created, retrieved, updated, and finally deleted. This illustrates the lifecycle for a data graph containing more than one object. Note that this example clears out the company and department tables at the start so that the exact results of the queries can be known.
You can find these examples combined into one script called 1cd-CRUD in the Scenarios directory in the Relational DAS package.
Esempio 5. One company, one department - Create As in the earlier example of creating just one company data object, the first action after constructing the Relational DAS is to call createRootDataObject() to obtain the special root object of the otherwise empty data graph. The company object is then created as a child of the root object, and the department object as a child of the company object. When it comes to applying the changes, the Relational DAS has to perform special processing to maintain the foreign keys that support the containment relationships, especially if auto-generated primary keys are involved. In this example, the relationship between the auto-generated primary key id in the company table and the co_id column in the department table must be maintained. When inserting a company and department for the first time the Relational DAS has to first insert the company row, then call PDO's getLastInsertId() method to obtain the auto-generated primary key, then add that as the value of the co_id column when inserting the department row.
|
Esempio 6. One company, one department - Retrieve and Update In this case the SQL query passed to executeQuery() performs an inner join to join the data from the company and department tables. Primary keys for both the company and department tables must be included in the query. The result set is re-normalised to form a normalised data graph. Note that a column specifier is passed as the third argument to the executeQuery() call enabling the Relational DAS to know which column is which in the result set. Note that the co_id column although used in the query is not needed in the result set. In order to understand what the Relational DAS is doing when it builds the data graph it may be helpful to visualise what the result set looks like. Although the data in the database is normalised, so that multiple department rows can point through their foreign key to one company row, the data in the result set is non-normalised: that is, if there is one company and multiple departments, the values for the company are repeated in each row. The Relational DAS has to reverse this process and turn the result set back into a normalised data graph, with just one company object. In this example the Relational DAS will examine the result set and column specifier, find data for both the company and department tables, find primary keys for both, and interpret each row as containing data for a department and its parent company. If it has not seen data for that company before (it uses the primary key to check) it creates a company object and then a department object underneath it. If it has seen data for that company before and has already created the company object it just creates the department object underneath. In this way the Relational DAS can retrieve and renormalise data for multiple companies and multiple departments underneath them.
|
Esempio 7. One company, two departments - Retrieve and Delete In this example the company and department are retrieved and then deleted. It is not necessary to delete them individually (although that would be possible) - deleting the company object from the data graph also deletes any departments underneath it. Note the way that the company object is actually deleted using the PHP unset call. The unset has to be performed on the containing reference which in this case is the company reference on the special root object. You must use:
|
The following examples use all three tables from the company database: the company, department, and employee tables. These introduce the final piece of function not exercised by the examples above: the non-containment reference employee_of_the_month.
Like the examples above for company and department, this set of examples is intended to illustrate the full lifecycle of such a data graph.
Esempio 8. One company, one department, one employee - Create In this example a company is created containing one department and just one employee. Note that this example clears out all three tables at the start so that the exact results of the queries can be known. Note how once the company, department and employee have been created, the employee_of_the_month property of the company can be made to point at the new employee. As this is a non-containment reference, this cannot be done until the employee object has been created within the graph. Non-containment references need to be managed carefully. For example if the employee were now deleted from under the department, it would not be correct to try to save the graph without first clearing or re-assigning the employee_of_the_month property. The closure rule for SDO data graphs requires that any object pointed at by a non-containment reference must also be reachable by containment references. When it comes to inserting the graph into the database, the procedure is similar to the example of inserting the company and department, but employee_of_the_month introduces an extra complexity. The Relational DAS needs to insert the objects working down the tree formed by containment references, so company, then department, then employee. This is necessary so that it always has the auto-generated primary key of a parent on hand to include in a child row. But when the company row is inserted the employee who is employee of the month has not yet been inserted and the primary key is not known. The procedure is that after the employee record is inserted and its primary key known, a final step is performed in which the the company record is updated with the employee's primary key.
|
Esempio 9. One company, one department, one employee - Retrieve and update The SQL statement passed to the Relational DAS is this time an inner join that retrieves data from all three tables. Otherwise this example introduces nothing that has not appeared in a previous example. The graph is updated by the addition of a new department and employee and some alterations to the name properties of the existing objects in the graph. The combined changes are then written back. The Relational DAS will process and apply an arbitrary mixture of additions, modifications and deletions to and from the data graph.
|
Esempio 10. One company, two departments, two employees - Retrieve and delete The company is retrieved as a complete data graph containing five data objects - the company, two departments and two employees. They are all deleted by deleting the company object. Deleting an object from the graph deletes all the object beneath it in the graph. Five SQL DELETE statements will be generated and executed. As always they will be qualified with a WHERE clause that contains all of the fields that were retrieved, so that any updates to the data in the database in the meantime by another process will be detected.
|
You may be interested in seeing the SQL statements that are generated in order to apply changes back to the database. At the top of the SDO/DAS/Relational.php you will find a number of constants which control whether the process of constructing and executing the SQL statements is to be traced. Try setting DEBUG_EXECUTE_PLAN to TRUE to see the generated SQL statements.
The Relational DAS provides two classes: the Relational DAS itself and the subclass of Exception that can be thrown. The Relational DAS has four publicly useful calls: the constructor, the createRootDataObject() call to obtain the root object of an empty data graph, the executeQuery() call to obtain a data graph containing data from a relational database, and the applyChanges() call to write changes made to a data graph back to the relational database.
The only object other than an SDO_DAS_Relational_Exception with which the application is expected to interact.
__construct - construct the Relational DAS with a model derived from the passed metadata
createRootDataObject - obtain an otherwise empty data graph containing just the special root object
executeQuery - execute an SQL query passed as a literal string and return the results as a normalised data graph
executePreparedQuery - execute an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph
applyChanges - examine the change summary in the data graph and apply those changes back to the database, subject to an assumption of optimistic concurrency
Is a subclass of PHP's Exception. It adds no behaviour to Exception. Thrown, with useful descriptive text, to signal errors in the metadata or unexpected failures to perform SQL operations.
(no version information, might be only in CVS)
SDO_DAS_Relational::applyChanges -- Applies the changes made to a data graph back to the database.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Given a PDO database handle and the special root object of a data graph, examine the change summary in the datagraph and applies the changes to the database. The changes that it can apply can be creations of data objects, deletes of data objects, and modifications to properties of data objects.
Constructed using the PDO extension. A typical line to construct a PDO database handle might look like this:
$dbh = new PDO("mysql:dbname=COMPANYDB;host=localhost",DATABASE_USER,DATABASE_PASSWORD); |
The special root object which is at the top of every SDO data graph.
None. Note however that the datagraph that was passed is still intact and usable. Furthermore, if data objects were created and written back to a table with autogenerated primary keys, then those primary keys will now be set in the data objects. If the changes were successfully written, then the change summary associated with the datagraph will have been cleared, so that it is possible to now make further changes to the data graph and apply those changes in turn. In this way it is possible to work with the same data graph and apply changes repeatedly.
SDO_DAS_Relational::applyChanges() can throw an SDO_DAS_Relational_Exception if it is unable to apply all the changes correctly.
The Relational DAS starts a database transaction before beginning to apply the changes and will commit the transaction only if they are all successful. The Relational DAS generates qualified update and delete statements which contain a where clause that specifies that the row to be updated or deleted must contain the same values that it did when the data was first retrieved. This is how the the optimistic concurrency is implemented. If any of the qualified update or delete statements fails to update or delete their target row, it may be because the data has been altered in the database in the meantime. In any event, if any update fails for any reason, the transaction is rolled back and an exception thrown. The exception will contain the generated SQL statement that failed.
The Relational DAS also catches any PDO exceptions and obtains PDO diagnostic information which it includes in an SDO_DAS_Relational_Exception which it then throws.
Please see the Examples section in the general information about the Relational DAS for many examples of calling this method. Please see also the section on Tracing to see how you can see what SQL statements are generated by the Relational DAS.
(no version information, might be only in CVS)
SDO_DAS_Relational::__construct -- Creates an instance of a Relational Data Access ServiceAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Constructs an instance of a Relational Data Access Service from the passed metadata.
An array containing one or more table definitions, each of which is an associative array containing the keys name, columns, PK, and optionally, FK. For a full discussion of the metadata, see the metadata section in the general information about the Relational DAS.
The root of each data graph is an object of a special root type and the application data objects come below that. Of the various application types in the SDO model, one has to be the the application type immediately below the root of the data graph. If there is only one table in the database metadata, so the application root type can be inferred, this argument can be omitted.
An array containing one or more definitions of a containment relation, each of which is an associative array containing the keys parent and child. The containment relations describe how the types in the model are connected to form a tree. The type specified as the application root type must be present as one of the parent types in the containment references. If the application only needs to work with one table at a time, and there are no containment relations in the model, this argument can be omitted. For a full discussion of the metadata, see the metadata section in the general information about the Relational DAS.
SDO_DAS_Relational::__construct() throws a SDO_DAS_Relational_Exception if any problems are found in the metadata.
For a full discussion of the metadata, see the metadata section in the general information about the Relational DAS.
(no version information, might be only in CVS)
SDO_DAS_Relational::createRootDataObject -- Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Returns the special root object at the top of an otherwise empty data graph. This call is used when the application wants to create a data graph from scratch, without having called executeQuery() to create a data graph.
The special root object has one multi-valued containment property, with a name of the application root type that was passed when the Relational DAS was constructed. The property can take values of only that type. The only thing that the application can usefully do with the root type is to call createDataObject() on it, passing the name of the application root type, in order to create a data object of their own application type.
Please see the Examples section in the general information about the Relational DAS for many examples of calling this method.
(no version information, might be only in CVS)
SDO_DAS_Relational::executePreparedQuery -- Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Executes a given query against the relational database, using the supplied PDO database handle. Differs from the simpler executeQuery() in that it takes a prepared statement and a list of values. This is the appropriate call to use either when the statement is to executed a number of times with different arguments, and there is therefore a performance benefit to be had from preparing the statement only once, or when the the SQL statement is to contain varying values taken from a source that cannot be completely trusted. In this latter case it may be unsafe to construct the SQL statement by simply concatenating the parts of the statement together, since the values may contain pieces of SQL. To guard against this, a so-called SQL injection attack, it is safer to prepare the SQL statement with placeholders (also known as parameter markers, denoted by '?') and supply a list of the values to be substituted as a separate argument. Otherwise this function is the same as executeQuery() in that it uses the model that it built from the the metadata to interpret the result set and returns a data graph.
Constructed using the PDO extension. A typical line to construct a PDO database handle might look like this:
$dbh = new PDO("mysql:dbname=COMPANYDB;host=localhost",DATABASE_USER,DATABASE_PASSWORD); |
A prepared SQL statement to be executed against the database. This will have been prepared by PDO's prepare() method.
An array of the values to be substituted into the SQL statement in place of the placeholders. In the event that there are no placeholders or parameter markers in the SQL statement then this argument can be specified as NULL or as an empty array;
The Relational DAS needs to examine the result set and for every column, know which table and which column of that table it came from. In some circumstances it can find this information for itself, but sometimes it cannot. In these cases a column specifier is needed, which is an array that identifies the columns. Each entry in the array is simply a string in the form table-name.column_name.
The column specifier is needed when there are duplicate column names in the database metadata, For example, in the database used within the examples, all the tables have both a id and a name column. When the Relational DAS fetches the result set from PDO it can do so with the PDO_FETCH_ASSOC attribute, which will cause the columns in the results set to be labelled with the column name, but will not distinguish duplicates. So this will only work when there are no duplicates possible in the results set.
To summarise, specify a column specifier array whenever there is any uncertainty about which column could be from which table and only omit it when every column name in the database metadata is unique.
All of the examples in the Examples use a column specifier. There is one example in the Scenarios directory of the installation that does not: that which works with just the employee table, and because it works with just one table, there can not exist duplicate column names.
Returns a data graph. Specifically, it returns a root object of a special type. Under this root object will be the data from the result set. The root object will have a multi-valued containment property with the same name as the application root type specified on the constructor, and that property will contain one or more data objects of the application root type.
In the event that the query returns no data, the special root object will still be returned but the containment property for the application root type will be empty.
SDO_DAS_Relational::executeQuery() can throw an SDO_DAS_Relational_Exception if it is unable to construct the data graph correctly. This can occur for a number of reasons: for example if it finds that it does not have primary keys in the result set for all the objects. It also catches any PDO exceptions and obtains PDO diagnostic information which it includes in an SDO_DAS_Relational_Exception which it then throws.
Esempio 1. Retrieving a data object using executePreparedQuery() In this example a single data object is retrieved from the database - or possibly more than one if there is more than one company called 'Acme'. For each company returned, the name and id properties are echoed. Other examples of the use of executePreparedQuery() can be found in the example code supplied in sdo/DAS/Relational/Scenarios .
|
(no version information, might be only in CVS)
SDO_DAS_Relational::executeQuery -- Executes a given SQL query against a relational database and returns the results as a normalised data graph.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Executes a given query against the relational database, using the supplied PDO database handle. Uses the model that it built from the the metadata to interpret the result set. Returns a data graph.
Constructed using the PDO extension. A typical line to construct a PDO database handle might look like this:
$dbh = new PDO("mysql:dbname=COMPANYDB;host=localhost",DATABASE_USER,DATABASE_PASSWORD); |
The SQL statement to be executed against the database.
The Relational DAS needs to examine the result set and for every column, know which table and which column of that table it came from. In some circumstances it can find this information for itself, but sometimes it cannot. In these cases a column specifier is needed, which is an array that identifies the columns. Each entry in the array is simply a string in the form table-name.column_name.
The column specifier is needed when there are duplicate column names in the database metadata. For example, in the database used within the examples, all the tables have both a id and a name column. When the Relational DAS fetches the result set from PDO it can do so with the PDO_FETCH_ASSOC attribute, which will cause the columns in the results set to be labelled with the column name, but will not distinguish duplicates. So this will only work when there are no duplicates possible in the results set.
To summarise, specify a column specifier array whenever there is any uncertainty about which column could be from which table and only omit it when every column name in the database metadata is unique.
All of the examples in the Examples use a column specifier. There is one example in the Scenarios directory of the installation that does not: that which works with just the employee table, and because it works with just one table, there can not exist duplicate column names.
Returns a data graph. Specifically, it returns a root object of a special type. Under this root object will be the data from the result set. The root object will have a multi-valued containment property with the same name as the application root type specified on the constructor, and that property will contain one or more data objects of the application root type.
In the event that the query returns no data, the special root object will still be returned but the containment property for the application root type will be empty.
SDO_DAS_Relational::executeQuery() can throw an SDO_DAS_Relational_Exception if it is unable to construct the data graph correctly. This can occur for a number of reasons: for example if it finds that it does not have primary keys in the result set for all the objects. It also catches any PDO exceptions and obtains PDO diagnostic information which it includes in an SDO_DAS_Relational_Exception which it then throws.
Please see the Examples section in the general information about the Relational DAS for many examples of calling this method.
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 | Variazioni |
---|---|---|---|
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_get_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_get_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_get_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 numero massimo di semafori consentito. sem_identifier è una risorsa semaforo ottenuta da sem_get().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Dopo avere processato una richiesta, qualsiasi semaforo acquisito dal processo, ma non esplicitamente rilasciato, sarà rilasciato automaticamente e causerà un messaggio di warning.
Vedere anche: sem_get() e sem_release().
La funzione sem_get() restituisce un identificativo che può essere utilizzato per accedere al semaforo con chiave indicata in key. Se necessario il semaforo viene creato con i bit dei permessi valorizzati come specificato in perm (di default 666). In max_acquire è indicato il numero massimo di processi che possono acquisire il semaforo simultaneamente (1 per default). In realtà questo valore è modificabile solo se il processo è l'unico, in quel momento, ad essere collegato al semaforo.
Il parametro facoltativo auto_release indica se il semaforo deve essere rilasciato automaticamente alla richiesta di shutdown. Parametro disponibile dal PHP 4.3.0.
La funzione ritorna un identificatore positivo di semaforo se ha successo, oppure FALSE se si verifica un errore.
Una seconda chiamata a sem_get() per la medesima chiave restituisce un identificativo di semaforo differente, ma entrambi gli gli identificativi accedono al medesimo semaforo sottostante.
Vedere anche: sem_acquire(), sem_release() e ftok().
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().
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().
La funzione shm_attach() restituisce un identificativo che può essere utilizzato per accedere alla memoria condivisa identificata dalla chiave key la prima chiamata crea il segmento di memoria condivisa di dimensione memsize (la dimensione di default può essere indicata in sysvshm.init_mem in php.ini, altrimenti viene fissata a 10000 bytes) e con i bit dei permessi (default: 0666).
Una seconda chiamata alla funzione shm_attach() con il medesimo parametro key restituirà un identificativo di memoria condivisa differente, ma entrambi accederanno alla medesima memoria condivisa sottostante. I parametri Memsize e perm saranno ignorati.
Vedere anche: ftok() e shm_detach().
La funzione shm_detach() disconnette dal segmento di memoria condivisa indicato dal parametro shm_identifier creato tramite la funzione shm_attach(). Si ricordi che la memoria condivisa continua a esistere nel sistema Unix e i dati sono ancora presenti.
La funzione shm_detach() restituisce sempre TRUE.
Vedere anche shm_attach(), shm_remove() e shm_remove_var().
La funzione shm_get_var() restituisce la variabile identificata dalla chiave variable_key, da un segmento di memoria condivisa identificato tramite shm_identifier. La variabile resta presente nella memoria condivisa.
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
shm_put_var -- Inserisce o aggiorna una variabile nella memoria condivisaLa funzione shm_put_var() inserisce o aggiorna la variabile indicata in variable con chiave variable_key. Sono suportati Tutti i tipi di variabili sono supportati.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Verrà generato un warning (E_WARNING level) se il parametro shm_identifier non è un puntatore valido ad un segmento di memoria condivisa SysV oppure se non vi è sufficiente memoria condivisa per completare la richiesta.
Rimuove la variabile identificata da variable_key e libera la memoria occupata.
Vedere anche shm_remove().
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
shm_remove -- Rimuove un segmento di memoria condivisa dal sistema UnixLa funzione shm_remove() rimuove un segmento di memoria condivisa identificata da shm_identifier. Tutti i dati contenuti saranno persi.
Vedere anche shm_remove_var().
SESAM/SQL-Server is a mainframe database system, developed by Fujitsu Siemens Computers, Germany. It runs on high-end mainframe servers using the operating system BS2000/OSD.
In numerous productive BS2000 installations, SESAM/SQL-Server has proven
the ease of use of Java-, Web- and client/server connectivity,
the capability to work with an availability of more than 99.99%,
the ability to manage tens and even hundreds of thousands of users.
There is a PHP 3 SESAM interface available which allows database operations via PHP-scripts.
Nota: Access to SESAM is only available with the latest CVS-Version of PHP 3. PHP 4 does not support the SESAM database.
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.
Nota: Questo modulo non è disponibile su piattaforme Windows.
This module provides an additional session save handler for the session module using PostgreSQLPostgreSQL as a storage system. A user session save handler may be used ((session_set_save_handler(), but this module is written in C. Therefore, this module could be twice as fast, compared to a session save handler written in PHP.
Session PgSQL is designed to scale any size of web sites and offers some advanced features:
session tables are created automatically |
automatic session table vacuum |
better garbage collection |
multiple PostgreSQL servers support |
automatic database server failover (switching) |
automatic database server load balancing if there are multiple PostgreSQL servers. |
short circuit UPDATE |
You need at least PHP >= 4.3.0, and PostgreSQL >=7.2.0 as database server. libpq that comes with PostgreSQL 7.2.0 or later (and header files to build) and libmm (and header files).
Short installation note:
Untar the tar.gz archive into php4/ext (Latest official releases can be found at SourceForge PHP Form Extension Project)
If the new directory is now called something like session_pgsql. You should name it to session_pgsql (except you only want to build it as self-contained php-module).
Run ./buildconf in php4
Run configure --with-session-pgsql (and your other options)
make; make install
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
PostgreSQL session save handler is still under development. Refer to the README file in the source distribution for configuration details.
Session table definition
CREATE TABLE php_session ( sess_id text, sess_name text, sess_data text, sess_created integer, sess_modified integer, sess_expire integer, sess_addr_created text, sess_addr_modified text, sess_counter integer, sess_error integer, sess_warning integer, sess_notice integer, sess_err_message text, sess_custom text ); CREATE INDEX php_session_idx ON php_session USING BTREE (sess_id); |
Avvertimento |
If you use HASH for INDEX, you'll have a deadlock problem when the server load is very high. Even if it's unlikely to have a deadlock under normal operation, it can occur. Do not use HASH for INDEX. |
You may change the session table as long as all fields are defined.
Application variables table definition
CREATE TABLE php_app_vars ( app_modified integer, app_name text, app_vars text ); |
I have at the moment not very much time to further develop this extension. I will implement more and more features in the near future.
If you have comments, bug fixes, enhancements or want to help developing this, you can drop me a mail at yohgaki@php.net. Any help is very welcome.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Get the number of errors and optional the error messages.
Set to TRUE the literal error message for each error is also returned.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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() ritorna il valore corrente di session.cache_expire. Il valore ritornato deve essere espressio in minuti, di default 180. Se si assegna nuova_scadenza_cache , il valore corrente di scadenza della cache viene sostituito con nuova_scadenza_cache.
La scadenza della cache viene reimpostata al valore predefinito di 180 memorizzato in session.cache_limiter ad ogni richiesta di pagina. Quindi, è necessario chiamare session_cache_expire() in ogni pagina (e prima di invocare session_start()).
Esempio 1. session_cache_expire() esempio
|
Nota: Impostazione nuova_scadenza_cache è utile soltanto, se session.cache_limiter è impostato su un valore diverso da nocache.
Vedere inoltre le impostazioni di configurazione session.cache_expire, session.cache_limiter e session_cache_limiter().
session_cache_limiter() 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.
Vedere inoltre session_encode().
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.
Whether to delete the old associated session file or not. Defaults to FALSE.
session_register() accetta un numero di argomenti variabile, ognuno dei quali può sia essere una stringa contenente il nome di una variabile o un array che contiene i nomi delle variabili o altri arrays. Per ogni nome, session_register() registra la variabile globale con quel nome nella sessione corrente.
Attenzione |
Questo registra un variabile global. Se volete registrare una variabile di sessione interna a una funzione, avete bisogno di assicurarvi di farla globale usando global() o usate gli arrays di sessione come scritto sotto. |
Attenzione |
Se state usando $HTTP_SESSION_VARS/$_SESSION, non usate session_register(), session_is_registered() e session_unregister(). |
Questa funzione restituisce TRUE quando tutte le variabili sono registrate con successo nella sessione.
Se session_start() non è stata chiamata prima che questa funzione venga chiamata, avverrà una chiamata imlicita senza parametri a session_start().
Potete anche creare una variabile di sessione semplicemente impostando l'appropriato membro di $HTTP_SESSION_VARS o $_SESSION (PHP >= 4.1.0) array.
$barney = "Una grande torta fiammeggiante."; session_register("barney"); $HTTP_SESSION_VARS["zim"] = "Mars attack."; # the auto-global $_SESSION array was introduced in PHP 4.1.0 $_SESSION["spongebob"] = "Ha i pantaloni a quadri."; |
Nota: Non è possibile registrare risorse variabili in una sessione. Per esempio, non potete creare una connessione a un database e archiviare l'id della connessione come una variabile di sessione e aspettarvi che la connessione sia ancora valida la prossima volta che la sessione viene riastabilita. Le funzioni PHP che restituiscono una risorsa sono identificate avendo un tipo di restituzione resource nelle loro definizioni di funzione. Una lista di funzioni che restituisce risorse è disponibile nell'appendice resource types.
Se viene usata $_SESSION (o $HTTP_SESSION_VARS per PHP 4.0.6 or inferiore), assegna la variabile a $_SESSION. i.e. $_SESSION['var'] = 'ABC';
Vedere anche session_is_registered() e session_unregister().
session_save_path() 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.
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.
The SimpleXML extension is enabled by default. To disable it, use the --disable-simplexml configure option.
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 change Ms. Coder to Miss Coder. |
Esempio 8. DOM Interoperability PHP has a mechanism to convert XML nodes between SimpleXML and DOM formats. This example shows how one might change a DOM element to SimpleXML.
|
(no version information, might be only in CVS)
SimpleXMLElement->asXML -- Return a well-formed XML string based on SimpleXML elementThe asXML method formats the parent object's data in XML version 1.0.
If specified, the function writes the data to the file rather than returning it.
If the filename isn't specified, this function returns a string on success and FALSE on error. If the parameter is specified, it returns TRUE if the file was written successfully and FALSE otherwise.
asXML also works on Xpath results:
Esempio 2. Using asXML() on Xpath results
|
(no version information, might be only in CVS)
SimpleXMLElement->attributes -- Identifies an element's attributesThis 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)
SimpleXMLElement->children -- Finds children of given nodeThis 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)
SimpleXMLElement->xpath -- Runs Xpath query on XML dataThe xpath method searches the SimpleXML node for children matching the Xpath path. It always returns an array of SimpleXMLElement 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.
See also dom_import_simplexml().
This function will convert the well-formed XML document in the file specified by filename to an object of class SimpleXMLElement. If any errors occur during file access or interpretation, the function returns FALSE.
You may use the optional class_name parameter so that simplexml_load_file() will return an object of the specified class. That class should extend the SimpleXMLElement class.
Since PHP 5.1.0 and Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.
Nota: Libxml 2 unescapes the URI, so if you want to pass e.g. b&c as the URI parameter a, you have to call simplexml_load_file(rawurlencode('http://example.com/?a=' . urlencode('b&c'))). Since PHP 5.1.0 you don't need to do this because PHP will do it for you.
Esempio 1. Interpret an XML document
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 of class SimpleXMLElement with properties containing the data held within the xml document. If any errors occur, it returns FALSE.
You may use the optional class_name parameter so that simplexml_load_string() will return an object of the specified class. That class should extend the SimpleXMLElement class.
Since PHP 5.1.0 and Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.
Esempio 1. Interpret an XML string
This script will display:
At this point, you can go about using $xml->body and such. |
See also: simplexml_load_file().
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.
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 | Changelog |
---|---|---|---|
soap.wsdl_cache_enabled | "1" | PHP_INI_ALL | Available since PHP 5.0.0. |
soap.wsdl_cache_dir | "/tmp" | PHP_INI_ALL | Available since PHP 5.0.0. |
soap.wsdl_cache_ttl | "86400" | PHP_INI_ALL | Available since PHP 5.0.0. |
Breve descrizione dei parametri di configurazione.
SoapClient->__call() - Calls a SOAP function (deprecated)
SoapClient->__doRequest() - Performs a SOAP request
SoapClient->__getFunctions() - Returns list of SOAP functions
SoapClient->__getLastRequest() - Returns last SOAP request
SoapClient->__getLastRequestHeaders() - Returns last SOAP request headers
SoapClient->__getLastResponse() - Returns last SOAP response
SoapClient->__getLastResponseHeaders() - Returns last SOAP response headers
SoapClient->__getTypes() - Returns list of SOAP types
SoapClient->__setCookie() - Sets the cookie that will be sent with the SOAP request
SoapClient->__soapCall() - Calls a SOAP function
SoapHeader is a special low-level class for passing or returning SOAP headers. It's just a data holder and it does not have any special methods except its constructor. It can be used in the SoapClient->__soapCall() method to pass a SOAP header or in a SOAP header handler to return the header in a SOAP response.
SoapParam is a special low-level class for naming parameters and returning values in non-WSDL mode. It's just a data holder and it does not have any special methods except its constructor.
SoapServer->addFunction() - Adds one or several functions those will handle SOAP requests
SoapServer->getFunctions() - Returns list of defined functions
SoapServer->handle() - Handles a SOAP request
SoapServer->setClass() - Sets class which will handle SOAP requests
SoapServer->setPersistence() - Sets persistence mode of SoapServer
SoapVar is a special low-level class for encoding parameters and returning values in non-WSDL mode. It's just a data holder and does not have any special methods except the constructor. It's useful when you want to set the type property in SOAP request or response.
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.
Added in PHP 5.1.0.
This function is useful when you like to check if the SOAP call failed, but don't like to use exceptions. To use it you must create a SoapClient object with the exceptions option set to zero or FALSE. In this case, the SOAP method will return a special SoapFault object which encapsulates the fault details (faultcode, faultstring, faultactor and faultdetails).
If exceptions is not set then SOAP call will throw an exception on error. is_soap_fault() checks if the given parameter is a SoapFault object.
Esempio 2. SOAP's standard method for error reporting is exceptions
|
(no version information, might be only in CVS)
SoapClient->__call() -- Calls a SOAP function (deprecated)This method is deprecated. Use SoapClient->__soapCall() instead of it.
This constructor creates SoapClient objects in WSDL or non-WSDL mode.
URI of the WSDL file or NULL if working in non-WSDL mode.
An array of options. If working in WSDL mode, this parameter is optional. If working in non-WSDL mode, you must set the location and uri options, where location is the URL to request and uri is the target namespace of the SOAP service.
The style and use options only work in non-WSDL mode. In WSDL mode, they come from the WSDL file.
The soap_version option specifies whether to use SOAP 1.1, or SOAP 1.2 client.
For HTTP authentication, you may use the login and password options. For making an HTTP connection through a proxy server, use the options proxy_host, proxy_port, proxy_login and proxy_password. For HTTPS client certificate authentication use local_cert and passphrase options.
The compression option allows to use compression of HTTP SOAP requests and responses.
The encoding option defines internal character encoding. This option does not change the encofing of SOAP requests (it is always utf-8), but converts strings into it.
The classmap option can be used to map some WSDL types to PHP classes. This option must be an array with WSDL types as keys and names of PHP classes as values.
The trace and exceptions options are useful for debuging purpose.
Esempio 1. SoapClient examples
|
Performs SOAP request over HTTP.
This method can be overridden in subclasses to implement different transport layers, perform additional XML processing or other purpose.
The XML SOAP request.
The URL to request.
The SOAP action.
The SOAP version.
Esempio 1. Some examples
|
(no version information, might be only in CVS)
SoapClient->__getFunctions() -- Returns list of SOAP functionsReturns the list of SOAP functions.
Nota: This function works only in WSDL mode.
(no version information, might be only in CVS)
SoapClient->__getLastRequest() -- Returns last SOAP requestNota: This method works only if the SoapClient object was created with the trace option.
SoapClient->__construct() |
SoapClient->__getLastRequestHeaders() |
SoapClient->__getLastResponse() |
SoapClient->__getLastResponseHeaders() |
(no version information, might be only in CVS)
SoapClient->__getLastRequestHeaders() -- Returns last SOAP request headersNota: This method works only if the SoapClient object was created with the trace option.
SoapClient->__construct() |
SoapClient->__getLastRequest() |
SoapClient->__getLastResponse() |
SoapClient->__getLastResponseHeaders() |
(no version information, might be only in CVS)
SoapClient->__getLastResponse() -- Returns last SOAP response.Nota: This method works only if the SoapClient object was created with the trace option.
SoapClient->__construct() |
SoapClient->__getLastResponseHeaders() |
SoapClient->__getLastRequest() |
SoapClient->__getLastRequestHeaders() |
(no version information, might be only in CVS)
SoapClient->__getLastResponseHeaders() -- Returns last SOAP response headers.Nota: This method works only if the SoapClient object was created with the trace option.
SoapClient->__construct() |
SoapClient->__getLastResponse() |
SoapClient->__getLastRequest() |
SoapClient->__getLastRequestHeaders() |
(no version information, might be only in CVS)
SoapClient->__getTypes() -- Returns list of SOAP types(no version information, might be only in CVS)
SoapClient->__setCookie() -- Sets the cookie that will be sent with the SOAP requestDefines a cookie to be sent along with the SOAP requests.
Nota: Calling this method will affect all following calls to SoapClient methods.
The name of the cookie.
The value of the cookie. If not specified, the cookie will be deleted.
This is a low level API function that is used to make a SOAP call. Usually, in WSDL mode, you can simply call SOAP functions as SoapClient methods. This method useful in non-WSDL mode when soapaction is unknown, uri differs from the default or when sending and/or receiving SOAP Headers.
On error, a call to a SOAP function can cause PHP to throw exceptions or return a SoapFault object if exceptions are disabled. To check if the function call failed to catch the SoapFault exceptions, check the result with is_soap_fault().
SOAP functions may return one, or multiple values. If only one value is returned by the SOAP function, the return value of __soapCall will be a simple value (e.g. an integer, a string, etc). If multiple values are returned, __soapCall will return an associative array of named output parameters.
Esempio 1. SoapClient->__soapCall() Examples
|
SoapClient->__construct() |
SoapParam->__construct() |
SoapVar->__construct() |
SoapHeader->__construct() |
SoapFault->__construct() |
is_soap_fault() |
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;
The error code of the SoapFault.
The error message of the SoapFault.
A string identifying the actor that caused the error.
Can be used to select the proper fault encoding from WSDL.
Can be used during SOAP header handling to report an error in the response header.
SoapClient->__construct() |
SoapClient->__soapCall() |
SoapVar->__construct() |
SoapParam->__construct() |
SoapFault->__construct() |
is_soap_fault() |
Constructs a new SoapHeader object.
The namespace of the SOAP header element.
The name of the SOAP header element.
A SOAP header's content. It can be a PHP value or a SoapVar object.
Value of the mustUnderstand attribute of the SOAP header element.
Value of the actor attribute of the SOAP header element.
Constructs a new SoapParam object.
The data to pass or return. You can pass this parameter directly as PHP value, but in this case it will be named as paramN and the SOAP Service may not understand it.
The parameter name.
(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 this parameter as a string.
To export several functions, pass an array of function names.
To export all the functions, pass a special constant SOAP_FUNCTIONS_ALL.
Nota: functions must receive all input arguments in the same order as defined in the WSDL file (They should not receive any output parameters as arguments) and return one or more values. To return several values they must return an array with named output parameters.
Esempio 1. Some examples
|
This constructor allows the creation of SoapServer objects in WSDL or non-WSDL mode.
If you want the WSDL mode, you must set this to the URI of a WSDL file. In the other case, you must set this to NULL and set the uri option.
Allow setting a default SOAP version (soap_version), internal character encoding (encoding), and actor URI (actor). The classmap option can be used to map some WSDL types to PHP classes. This option must be an array with WSDL types as keys and names of PHP classes as values.
Esempio 1. Some examples
|
(no version information, might be only in CVS)
SoapServer->fault() -- Issue SoapServer fault indicating an errorAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
SoapServer->getFunctions() -- Returns list of defined functionsThis method returns the list of all functions added by SoapServer->addFunction() or SoapServer->setClass().
Esempio 1. Some examples
|
Processes a SOAP request, calls necessary functions, and sends a response back.
The SOAP request. If this argument is omitted, the request is supposed to be in the $HTTP_RAW_POST_DATA PHP variable.
(no version information, might be only in CVS)
SoapServer->setClass() -- Sets class which will handle SOAP requestsExports all methods from specified class.
The object can be made persistent across request for a given PHP session with the SoapServer->setPersistence() method.
The name of the exported class.
These optional parameters will be passed to the default class constructor during object creation.
(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().
Constructs a new SoapVar object.
The data to pass or return.
The encoding ID, one of the XSD_... constants.
The type name.
The type namespace.
The XML node name.
The XML node namespace.
Esempio 1. Some examples
|
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().
La funzione socket_bind() esegue il bind del nome passato in indirizzo sul socket indicato da socket,
Una valida risorsa di tipo socket creata da socket_create().
Se il socket appartiene alla famiglia AF_INET, il parametro address è un classico indirizzo IP (ad esempio 127.0.0.1)
Se il socket appartiene alla famiglia AF_UNIX, il parametro address indica il percorso di un socket nel dominio Unix (ad esempio /tmp/my.sock).
Il parametro port, si utilizza soltanto con le connessioni tramite un socket di tipo AF_INET, ed indica quale porta sul server remoto si debba utilizzare per eseguire la connessione.
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.
Esempio 1. Utilizzo di socket_bind() per impostare un indirizzo sorgente
|
Nota: Questa funzione deve essere utilizzata sui socket prima di socket_connect().
Nota: Windows 9x/ME nota di compatibilità: socket_last_error() può restituire un codice di errore non valido se si tenta il bind del socket ad un indirizzo errato che non appartiene alla propria macchina.
(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 matriceAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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. |
La funzione socket_recvfrom() gestisce i dati binari dal PHP 4.3.0
(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, 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 sensiAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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().
SPL is a collection of interfaces and classes that are meant to solve standard problems.
Suggerimento: A more detailed documentation of SPL can be found here.
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
Il precedente esempio visualizzerà:
|
This function moves the iterator to the next entry.
Esempio 1. ArrayIterator::next() example
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
ArrayIterator::rewind -- Rewind array back to the startThis function rewinds the iterator to the beginning.
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
Il precedente esempio visualizzerà:
|
(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 -- Check 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 -- Return 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 inner iterator'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 pathAvvertimento |
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::getATime -- 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::getCTime -- Get inode modification time of fileAvvertimento |
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. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DirectoryIterator::getMTime -- 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. |
(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. |
Avvertimento |
Questa 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::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 iteratorAvvertimento |
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. |
(no version information, might be only in CVS)
SimpleXMLIterator::valid -- Check whether SimpleXML contains more entriesAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
This function returns an array with the names of the interfaces that the given class and its parents implement.
An object (class instance) or a string (class name).
Whether to allow this function to load the class automatically through the __autoload magic method. Defaults to TRUE.
Esempio 1. class_implements() example
Il precedente esempio visualizzerà qualcosa simile a:
|
This function returns an array with the name of the parent classes of the given class.
An object (class instance) or a string (class name).
Whether to allow this function to load the class automatically through the __autoload magic method. Defaults to TRUE.
Esempio 1. class_parents() example
Il precedente esempio visualizzerà qualcosa simile a:
|
Avvertimento |
Questa 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 returns an array with the current available SPL classes.
Esempio 1. spl_classes() example
Il precedente esempio visualizzerà qualcosa simile a:
|
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.
(PHP 5)
sqlite_array_query(no version information, might be only in CVS)
SQLiteDatabase->arrayQuery -- Esegue una query in un dato database e restituisce una matriceVersione ad oggetti (metodo):
class SQLiteDatabase {sqlite_array_query() esegue una data query e restituisce un matrice con l'intero set di risultati. E' simile a sqlite_query() e a eseguiresqlite_fetch_array() per ogni riga. sqlite_array_query() è significativamente più veloce.
Suggerimento: Le migliori performance con sqlite_array_query() si ottengono con query che restituiscono fino a 45 righe. Se si ha più dati si raccomanda di scrivere una propria funzione e di utilizzare sqlite_unbuffered_query().
Query da eseguire.
Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.
The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.
Quando decode_binary è impostato a TRUE (per default), il PHP decodificherà i dati binari se questi furono codificati con la funzione sqlite_escape_string(). Normalmente si dovrebbe lasciare inalterato il comportamento di default, a meno che non si debba intervenire su database creati da altre applicazioni SQLite.
Nota: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.
Restituisce una matrice contenente tutti i risultati, oppure FALSE.
I nomi delle colonne restituiti da SQLITE_ASSOC e da SQLITE_BOTH saranno maiuscoli o minuscoli in base al valore del parametro di configurazione sqlite.assoc_case.
(PHP 5)
sqlite_busy_timeout(no version information, might be only in CVS)
SQLiteDatabase->busyTimeout -- Imposta il timeout di 'in uso', o disabilita l'handle di 'in uso'Object oriented style (method):
class SQLiteDatabase {SImposta il tempo massimo che sqlite attenderà che un dbhandle diventi disponibile all'uso.
Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.
Numero di millisecondi. Se il parametro è impostato a 0, l'handle di 'in uso' viene disattivato e sqlite ritornerà immediatamente con un errore SQLITE_BUSY se un'altro processo/thread ha bloccato il database per un aggiornamento.
Il PHP imposta per default il timeout di 'in uso' a 60 secondi durante l'apertura del database.
Nota: Ci sono mille (1000) millisecondi in un secondo.
(PHP 5)
sqlite_changes(no version information, might be only in CVS)
SQLiteDatabase->changes -- Restituisce il numero di righe modificate dall'ultima istruzione SQLVersione ad oggetti (metodo):
class SQLiteDatabase {Restituisce il numero di righe modificate dall'ultima istruzione SQL eseguita sul database referenziato da dbhandle.
Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.
Chiude il database indicato dall'handle database. Se il database è persistente, questo sarà chiuso e rimosso dalla lista dei database persistenti.
Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale.
(PHP 5)
sqlite_column(no version information, might be only in CVS)
SQLiteResult->column(no version information, might be only in CVS)
SQLiteUnbuffered->column -- Scarica una riga dal set di risultati correnteScarica 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.
Risorsa SQLite per un set di risultati. Questo parametro non è richiesto quando la funzione è utilizzata nello stile ad oggetti.
Indice o nome della colonna da scaricare.
Quando decode_binary è impostato a TRUE (per default), il PHP decodificherà i dati binari se questi furono codificati con la funzione sqlite_escape_string(). Normalmente si dovrebbe lasciare inalterato il comportamento di default, a meno che non si debba intervenire su database creati da altre applicazioni SQLite.
Nota: Utilizzare questa funzione quando si opera su set di risultati con molte colonne o con colonne che contengano grandi quantità di dati.
(PHP 5)
sqlite_create_aggregate(no version information, might be only in CVS)
SQLiteDatabase->createAggregate -- Registra un aggregato UDF da utilizzare nelle istruzioni SQLVersione ad oggetti (metodo):
class SQLiteDatabase {sqlite_create_aggregate() è simile a sqlite_create_function() tranne che le funzioni di registrazione possono essere utilizzate per calcolare un risultato aggregato da tutte le righe della query.
La differenza chiave tra questa funzione e sqlite_create_function() è che entrambe le funzioni sono necessarie per gestire gli aggregati; la funzione step_func viene richiamata per ogni riga del set di risultati. La funzione PHP personalizzata dovrebbe accumulare i dati memorizzarli nel contesto di aggregazione. Una volta che tutte le righe sono state processate, si esegue la funzione finalize_func che dovrebbe prendere i dati dal contesto di aggregazione e restituire il risultato. La funzione personalizzata deve restituire un tipo riconosciuto da SQLite (ad esempio un tipo scalare).
Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.
Nome della funzione usata nell'istruzione SQL.
Funzione richiamata per ogni riga del set di risultati.
Funzione di callback richiamata per aggragare i dati da ogni riga.
Suggerisce al parser SQLite se la funzione di callback accetta un numero predefinito di argomenti.
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.
(PHP 5)
sqlite_create_function(no version information, might be only in CVS)
SQLiteDatabase->createFunction -- Registra una funzione utente "regolare" da utilizzare nelle istruzioni SQLVersione ad oggetti (metodo):
class SQLiteDatabase {La funzione sqlite_create_function() permette di registrare una funzione PHP in SQLite come UDF (funzione definita dall'utente, User Defined Function), in modo che possa essere richiamata dalle istruzioni SQL.
Le UDF possono essere utilizzate in qualsiasi istruzione SQL che permetta di richiamare funzioni, tipo SELECT e UPDATE e anche i triggers.
Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.
Indica il nome della funzione che si vuole utilizzare nelle istruzioni SQL.
Funzione di callback richiamata per gestire la funzione SQL.
Nota: Le funzioni di callback devono restituire un tipo noto a SQLite (ad esempio un tipo scalare).
Indicazione al parser SQLite se la funzione di callback accetta un numero predefinito di argomenti.
Nota: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.
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.
(PHP 5)
sqlite_current(no version information, might be only in CVS)
SQLiteResult->current(no version information, might be only in CVS)
SQLiteUnbuffered->current -- Scarica la riga corrente di un set di risultati in una matriceVersione ad oggetti (metodo):
class SQLiteResult {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.
Risorsa SQLite di un set di risultati. Questo parametro non è necessario quando la funzione è utilizzata ad oggetti.
The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.
Quando decode_binary è impostato a TRUE (per default), il PHP decodificherà i dati binari se questi furono codificati con la funzione sqlite_escape_string(). Normalmente si dovrebbe lasciare inalterato il comportamento di default, a meno che non si debba intervenire su database creati da altre applicazioni SQLite.
Restituisce una matrice della riga corrente dal set di risultati, oppure FALSE se la posizione corrente è oltre la riga finale.
I nomi delle colonne restituiti da SQLITE_ASSOC e da SQLITE_BOTH saranno maiuscoli o minuscoli in base al valore del parametro di configurazione sqlite.assoc_case.
Restituisce una descrizione leggibile del error_code restituito dalla funzione 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 restituiti da funzioni UDF create tramite sqlite_create_function() o sqlite_create_aggregate() - utilizzare invece sqlite_udf_encode_binary().
(PHP 5)
sqlite_exec(no version information, might be only in CVS)
SQLiteDatabase->exec -- ESegue una query priva di risultato in un dato databaseVersione ad oggetti (metodo):
class SQLiteDatabase {Esegue un'espressione SQL, indicata da query sul database (specificato dal parametro dbhandle).
Avvertimento |
SQLite esegue molteplici query separate da punto e virgola, in questo modo si può eseguire un batch di istruzioni SQL caricate da un file o racchiuse in uno script. |
Query da eseguire.
Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.
Nota: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.
Questa funzione restituisce il valore TRUE se ha successo, oppure FALSE per insuccesso. Se si deve eseguire una query che restituisca un risultato eseguire sqlite_query().
I nomi delle colonne restituiti da SQLITE_ASSOC e da SQLITE_BOTH saranno maiuscoli o minuscoli in base al valore del parametro di configurazione sqlite.assoc_case.
sqlite_factory() si comporta in modo simile a sqlite_open() in quanto apre un database SQLITE o cerca di crearlo se non esiste. Tuttavia, la funzione restituisce un oggetto SQLiteDatabase anzichè una risorsa. Vedere la pagina del manuale di sqlite_open() per maggiori dettagli.
Il nome del file del database SQLite.
Modalità del file. Intesa per essere utilizzata per aprire il database in modalità sola lettura. Attualmente questo parametro è ignorato dalla libreria SQLite. Il valore di default è il valore ottale 0666 ed è l'impostazione raccomandata.
Passato per riferimento ed è impostato per restituire un messaggio di errore descrittivo del perchè il database non può essere aperto in caso di errore.
Restituisce un oggetto SQLiteDatabase in caso di successo, NULL in caso di errore.
(PHP 5)
sqlite_fetch_all(no version information, might be only in CVS)
SQLiteResult->fetchAll(no version information, might be only in CVS)
SQLiteUnbuffered->fetchAll -- Scarica tutte le righe di un risultato in una matrice di matriciVersione ad oggetti (metodo):
class SQLiteResult {sqlite_fetch_all() restituisce una matrice con l'intero set di risultati dalla risorsa result. E' simile ad eseguire sqlite_query() (oppure sqlite_unbuffered_query()) e quindi sqlite_fetch_array() per ciascuna riga del set di risultati.
Risorsa SQLite. Questo parametro non è richiesto quando si usa il metodo ad oggetti.
The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.
Quando decode_binary è impostato a TRUE (per default), il PHP decodificherà i dati binari se questi furono codificati con la funzione sqlite_escape_string(). Normalmente si dovrebbe lasciare inalterato il comportamento di default, a meno che non si debba intervenire su database creati da altre applicazioni SQLite.
Restituisce una matrice della riga corrente da un set di risultati, oppure FALSE se la posizione corrente è oltre l'ultima riga.
I nomi delle colonne restituiti da SQLITE_ASSOC e da SQLITE_BOTH saranno maiuscoli o minuscoli in base al valore del parametro di configurazione sqlite.assoc_case.
Esempio 2. Esempio ad oggetti
|
(PHP 5)
sqlite_fetch_array(no version information, might be only in CVS)
SQLiteResult->fetch(no version information, might be only in CVS)
SQLiteUnbuffered->fetch -- Scarica in una matrice la riga successiva da un set di risultatiVersione ad oggetti (metodo):
class SQLiteResult {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.
Risorsa SQLite. Questo parametro non è richiesto nella versione ad oggetti.
The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.
Quando decode_binary è impostato a TRUE (per default), il PHP decodificherà i dati binari se questi furono codificati con la funzione sqlite_escape_string(). Normalmente si dovrebbe lasciare inalterato il comportamento di default, a meno che non si debba intervenire su database creati da altre applicazioni SQLite.
Restituisce una matrice della riga successiva dal set di risultati, FALSE se la posizine successive è oltre l'ultima riga.
I nomi delle colonne restituiti da SQLITE_ASSOC e da SQLITE_BOTH saranno maiuscoli o minuscoli in base al valore del parametro di configurazione sqlite.assoc_case.
Esempio 2. Esempio ad oggetti
|
(PHP 5)
sqlite_fetch_column_types(no version information, might be only in CVS)
SQLiteDatabase->fetchColumnTypes -- Restituisce una matrice con il formato delle colonne di una tabellaVersione ad oggetti (metodo):
class SQLiteDatabase {sqlite_fetch_column_types() rRestituisce una matrice con il tipo di dato delle colonne della tabella indicata da table_name.
Nome della tabella.
Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.
The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.
Restituisce una matrice con i tipi di dati delle colonne, oppure FALSE in caso di errore.
I nomi delle colonne restituiti da SQLITE_ASSOC e da SQLITE_BOTH saranno maiuscoli o minuscoli in base al valore del parametro di configurazione sqlite.assoc_case.
Esempio 2. Esempio ad oggetti
Il precedente esempio visualizzerà:
|
(PHP 5)
sqlite_fetch_object(no version information, might be only in CVS)
SQLiteResult->fetchObject(no version information, might be only in CVS)
SQLiteUnbuffered->fetchObject -- Scarica i dati deti della riga successiva come oggettoVersione ad oggetti (metodo):
class SQLiteResult {Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 5)
sqlite_fetch_single(no version information, might be only in CVS)
SQLiteResult->fetchSingle(no version information, might be only in CVS)
SQLiteUnbuffered->fetchSingle -- Scarica come stringa la prima colonna di un set di risultatiVersione ad oggetti (metodo):
class SQLiteResult {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.
SQLite risorsa. Questo parametro non è richiesto quando la funzione viene usata nella versione ad oggetti.
Quando decode_binary è impostato a TRUE (per default), il PHP decodificherà i dati binari se questi furono codificati con la funzione sqlite_escape_string(). Normalmente si dovrebbe lasciare inalterato il comportamento di default, a meno che non si debba intervenire su database creati da altre applicazioni SQLite.
Esempio 1. Esempio di uso di sqlite_fetch_single()
|
(PHP 5)
sqlite_field_name(no version information, might be only in CVS)
SQLiteResult->fieldName(no version information, might be only in CVS)
SQLiteUnbuffered->fieldName -- Restituisce il nome di un particolare campoVersione ad oggetti (metodo):
class SQLiteResult {Dato il numero ordinale di colonna, field_index, restituisce il nome del campo dal set di risultati indicato in result.
Risorsa SQLite. Questo parametro non è richiesto quando si utilizza la funzione nella versione ad oggetti.
Numero ordinale della colonna nel set di risultati.
Restituisce il nome del campo dal set di risultati SQLite, dato il numero della colonna, oppure FALSE in caso di errore.
I nomi delle colonne restituiti da SQLITE_ASSOC e da SQLITE_BOTH saranno maiuscoli o minuscoli in base al valore del parametro di configurazione sqlite.assoc_case.
Indica se sono disponibili o meno ulteriori righe.
sqlite_has_more() restituisce TRUE se sono disponibili ulteriori righe dal set di risultati result, oppure FALSE in caso contrario.
(PHP 5)
sqlite_has_prev(no version information, might be only in CVS)
SQLiteResult->hasPrev -- Indica se è disponibile o meno una riga precedenteObject oriented style (method):
class SQLiteResult {Indica se è disponibile o meno una riga precedente nel dato set di risultati.
Risorsa set di risultati di SQLite. Questo parametro non è richiesto nel caso si utilizzi la funzione nella versione ad oggetti.
Nota: This function cannot be used with unbuffered result handles.
Restituisce TRUE se vi sono ulteriori righe precedenti dal set di risultati result, oppure FALSE in caso contrario.
(no version information, might be only in CVS)
sqlite_key(no version information, might be only in CVS)
SQLiteResult->key -- Restituisce l'indice di riga correnteObject oriented style (method):
class SQLiteResult {sqlite_key() restituisce l'indice della riga corrente del set di risultati result.
Risorsa set di risultati di SQLite. Questo parametro non è richiesto nel caso si utilizzi la funzione nella versione ad oggetti.
Nota: This function cannot be used with unbuffered result handles.
Versione | Descrizione |
---|---|
5.0.4 | Prima di PHP 5.0.4, sqlite_key() poteva essere chiamato come metodo dell'oggetto SQLiteResult, e non per via procedurale. |
(PHP 5)
sqlite_last_error(no version information, might be only in CVS)
SQLiteDatabase->lastError -- Restituisce il codice di errore dell'ultimo errore accorso sul databaseVersione ad oggetti (metodo):
class SQLiteDatabase {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().
Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.
(PHP 5)
sqlite_last_insert_rowid(no version information, might be only in CVS)
SQLiteDatabase->lastInsertRowid -- Restituisce l'identificativo di riga dell'ultima riga inseritaVersione ad oggetti (metodo):
class SQLiteDatabase {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.
Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.
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. |
(PHP 5)
sqlite_next(no version information, might be only in CVS)
SQLiteResult->next(no version information, might be only in CVS)
SQLiteUnbuffered->next -- Si sposta al successivo numero di rigaVersione ad oggetti (metodo):
class SQLiteResult {La funzione sqlite_next() avanza il set di risultati indicato da result alla riga successiva.
Risorsa set di risultati di SQLite. Questo parametro non è richiesto nella versione ad oggetti.
(PHP 5)
sqlite_num_fields(no version information, might be only in CVS)
SQLiteResult->numFields(no version information, might be only in CVS)
SQLiteUnbuffered->numFields -- Resituitsce il numero di campi da un set di risultatiVersione ad oggetti (metodo):
class SQLiteResult {Restituisce il numero di campi presenti nel set di risultati result.
Risorsa set di risultati di SQLite. Questo parametro non è richiesto nella versione ad oggetti.
(PHP 5)
sqlite_num_rows(no version information, might be only in CVS)
SQLiteResult->numRows -- Restituisce il numero di righe da un set di risultati bufferizzatoVersione ad oggetti (metodo):
class SQLiteResult {Restituisce il numero di righe dal set di risultati result bufferizzato.
Risorsa set di risultati di SQLite. Questo parametro non è richiesto nella versione ad oggetti.
Nota: This function cannot be used with unbuffered result handles.
Versione ad oggetti (costruttore):
class SQLiteDatabase {Apre un database SQLite o lo crea se non esiste.
Nome del database SQLite. Se il file non esiste, SQLite tenterà di crearlo. Il PHP deve avere i permessi di scrittura sul file se si desidera inserire dei dati o modficare lo schema del database, o creare il database se non esiste.
Specifica la modalità del file. E' inteso per essere utilizzato per l'apertura del file in modalità read-only. Attualmente questo parametro viene ignorato da SQLite. Per default la modalità di apertura è il valore ottale 0666, ed è questa l'impostazione raccomandata.
Passato per riferimento, è impostato per contenere un messaggio descrittivo di errore nel caso non si riesca ad aprire il database a causa di un errore.
Restituisce una risorsa (database handle) se ha successo, oppure FALSE se si verifica 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 alla modalità sicura e a open_basedir.
(PHP 5)
sqlite_popen -- Apre una connessione persistente ad un database SQLite e crea il database se non esisteQuesta 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.
Nome del database SQLite. Se il file non esiste, SQLite tenterà di crearlo. Il PHP deve avere i permessi di scrittura sul file se si desidera inserire dei dati o modficare lo schema del database, o creare il database se non esiste.
Specifica la modalità del file. E' inteso per essere utilizzato per l'apertura del file in modalità read-only. Attualmente questo parametro viene ignorato da SQLite. Per default la modalità di apertura è il valore ottale 0666, ed è questa l'impostazione raccomandata.
Passato per riferimento, è impostato per contenere un messaggio descrittivo di errore nel caso non si riesca ad aprire il database a causa di un errore.
Restituisce una risorsa (database handle) se ha successo, oppure FALSE se si verifica un errore.
(PHP 5)
sqlite_prev(no version information, might be only in CVS)
SQLiteResult->prev -- Si posiziona sulla riga precedente di un set di risultatiVersione ad oggetti (metodo):
class SQLiteResult {sqlite_prev() si sposta alla riga precedente di result.
Risorsa risultato di SQLite. Questo parametro non è richiesto quando di usa la versione ad oggetti.
Nota: This function cannot be used with unbuffered result handles.
La funzione restituisce TRUE se ha successo, oppure FALSE se non esiste un record precedente.
(PHP 5)
sqlite_query(no version information, might be only in CVS)
SQLiteDatabase->query -- Esegue una query su un database e restituisce un puntatore al set di risultatiVersione ad oggetti (metodo):
class SQLiteDatabase {Esegue le istruzioni SQL indicate in query sul collegamento al database dato.
Query da eseguire.
Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.
Nota: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.
Questa funzione restituisce un handle o FALSE se si verifica un errore. Nei casi di query che restituiscano delle righe, l'handle restituito dalla funzione può essere utilizzato nelle funzioni sqlite_fetch_array() e sqlite_seek().
A prescindere dal tipo di query, questa funzione restituisce FALSE se la query fallisce.
sqlite_query() restituisce un puntatore ad un set di risultati bufferizzato e navigabile. Ciò è ragionevole per piccole query dove si ha la necessità di accedere alle righe in ordine casuale. I risultati bufferizzati allocano la memoria necessaria per contenere tutte le righe restituite dalla query, che non saranno restituite fino a che non saranno richieste. Se si ha soltanto la necessità di accedere alle righe in modo sequenziale, si raccomanda l'uso della funzione sqlite_unbuffered_query().
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). |
(PHP 5)
sqlite_rewind(no version information, might be only in CVS)
SQLiteResult->rewind -- Si posiziona sulla prima rigaVersione ad oggetti (metodo):
class SQLiteResult {sqlite_rewind() si posiziona sulla prima riga del set di risultati.
Risorsa risultato di SQLite. Questo parametro non è richiesto nella versione ad oggetti.
Nota: This function cannot be used with unbuffered result handles.
La funzione restituisce FALSE se non vi sono righe nel set di risultati, TRUE in caso contrario.
(PHP 5)
sqlite_seek(no version information, might be only in CVS)
SQLiteResult->seek -- Posizionamento su una data riga di un set di risultati bufferizzatoVersione ad oggetti (metodo):
class SQLiteResult {sqlite_seek() si posiziona sulla riga indicata dal parametro rownum.
Risorsa risultato di SQLite. Questo parametro non è richiesto nella versione ad oggetti.
Nota: This function cannot be used with unbuffered result handles.
Il numero ordinale di riga da cercare. I numeri di riga partono da zero ( 0 indica la prima riga).
Nota: This function cannot be used with unbuffered result handles.
(PHP 5)
sqlite_single_query(no version information, might be only in CVS)
SQLiteDatabase->singleQuery -- Esegue una query e restituisce o una matrice per ogni singola colonna o il valore della prima rigaVersione ad oggetti (metodo):
class SQLiteDatabase {Avvertimento |
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
|
sqlite_udf_encode_binary() applica la decofica dei dati binari al parametro data in modo che possa essere restituito dalle query (dato che la sottostante libreria libsqlite API non è binary safe).
Se esiste una possibilità che i dati possano essere binai (ad esempio contengono caratteri tipo NUL, oppure iniziano con il carattere 0x01), occorre eseguire questa funzione per codificare il valore da restituire all'UDF.
Il PHP non esegue questa codifica/decodifica in automatico, avrebbe impatti negativi sulle performance.
Nota: Non utilizzare sqlite_escape_string() per quitare stringhe restituite tramite UDF poiché porta ad avere una quotazione doppia. Utilizzare sqlite_udf_encode_binary()!
sqlite_udf_decode_binary() |
sqlite_escape_string() |
sqlite_create_function() |
sqlite_create_aggregate() |
(PHP 5)
sqlite_unbuffered_query(no version information, might be only in CVS)
SQLiteDatabase->unbufferedQuery -- Esegue una query senza scaricare e bufferizzare i datiVersione ad oggetti (metodo):
class SQLiteDatabase {sqlite_unbuffered_query() è simile a sqlite_query() tranne che i risultati sono restituiti in modo sequenziale una riga dopo l'altra, permettendo solo la lettura del record successivo.
Questa funzione è l'ideale per generare oggetti tipo tavole HTML in cui occorre processare una riga alla volta e non occorre muoversi a caso tra le righe.
Nota: Funzioni tipo sqlite_seek(), sqlite_rewind(), sqlite_next(), sqlite_current(), e sqlite_num_rows() non sono applicabili agli handles restituiti da sqlite_unbuffered_query().
La query da eseguire.
Risorsa SQLite Database restituita da sqlite_open () quando usato in modo procedurale. Questo parametro non è richiesto nel metodo ad oggetti.
Nota: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.
Resituisce un puntatore ad un risultato oppure FALSE.
sqlite_unbuffered_query() restituisce un set di risultati sequenzialeche può essere utilizzato per leggere una riga dopo l'altra.
(PHP 5)
sqlite_valid(no version information, might be only in CVS)
SQLiteResult->valid(no version information, might be only in CVS)
SQLiteUnbuffered->valid -- Indica se una o più righe sono disponibiliVersione ad oggetti (metodo):
class SQLiteResult {Verifica se una o più righe sono disponibili nel dato set di risultati.
Risorsa risultato di SQLite. Questo parametro non è richiesto quando la funzione viene usata ad oggetti.
Nota: This function cannot be used with unbuffered result handles.
PDO_SQLITE is a driver that implements the PHP Data Objects (PDO) interface to enable access to SQLite 3 databases.
In PHP 5.1, the SQLite extension also provides a driver for SQLite 2 databases; while it is not technically a part of the PDO_SQLITE driver, it behaves similarly, so it is documented alongside it. The SQLite 2 driver for PDO is provided primarily to make it easier to import legacy sqlite 2 database files into an application that uses the faster, more efficient sqlite 3 driver. As a result, the SQLite 2 driver is not as feature-rich as the SQLite 3 driver.
The PDO_SQLITE Data Source Name (DSN) is composed of the following elements:
The DSN prefix is sqlite:.
To access a database on disk, append the absolute path to the DSN prefix.
To create a database in memory, append memory: to the DSN prefix.
The SQLite extension in PHP 5.1 provides a PDO driver that supports accessing and creating SQLite 2 databases. This enables you to access databases you may have created with the SQLite extension in previous versions of PHP.
Nota: The sqlite2 driver is only available in PHP 5.1 if you have enabled both PDO and ext/sqlite. It is not currently available via PECL.
The DSN prefix for connecting to SQLite 2 databases is sqlite2:.
To access a database on disk, append the absolute path to the DSN prefix.
To create a database in memory, append memory: to the DSN prefix.
(no version information, might be only in CVS)
PDO::sqliteCreateAggregate -- Registers an aggregating User Defined Function for use in SQL statementsAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
PDO::sqliteCreateAggregate() is similar to PDO::sqliteCreateFunction() except that it registers functions that can be used to calculate a result aggregated across all the rows of a query.
The key difference between this function and PDO::sqliteCreateFunction() is that two functions are required to manage the aggregate; step_func is called for each row of the result set. Your PHP function should accumulate the result and store it into the aggregation context. Once all the rows have been processed, finalize_func will be called and it should then take the data from the aggregation context and return the result. Callback functions should return a type understood by SQLite (i.e. scalar type).
The name of the function used in SQL statements.
Callback function called for each row of the result set.
Callback function to aggregate the "stepped" data from each row.
Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.
Esempio 1. max_length aggregation function example
|
In this example, we are creating an aggregating function that will calculate the length of the longest string in one of the columns of the table. For each row, the max_len_step function is called and passed a context parameter. The context parameter is just like any other PHP variable and be set to hold an array or even an object value. In this example, we are simply using it to hold the maximum length we have seen so far; if the string has a length longer than the current maximum, we update the context to hold this new maximum length.
After all of the rows have been processed, SQLite calls the max_len_finalize function to determine the aggregate result. Here, we could perform some kind of calculation based on the data found in the context. In our simple example though, we have been calculating the result as the query progressed, so we simply need to return the context value.
Suggerimento: It is NOT recommended for you to store a copy of the values in the context and then process them at the end, as you would cause SQLite to use a lot of memory to process the query - just think of how much memory you would need if a million rows were stored in memory, each containing a string 32 bytes in length.
Suggerimento: You can use PDO::sqliteCreateFunction() and PDO::sqliteCreateAggregate() to override SQLite native SQL functions.
Nota: This method is not available with the SQLite2 driver. Use the old style sqlite API for that instead.
(no version information, might be only in CVS)
PDO::sqliteCreateFunction -- Registers a User Defined Function for use in SQL statementsAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
PDO::sqliteCreateFunction() allows you to register a PHP function with SQLite as an UDF (User Defined Function), so that it can be called from within your SQL statements.
The UDF can be used in any SQL statement that can call functions, such as SELECT and UPDATE statements and also in triggers.
The name of the function used in SQL statements.
Callback function to handle the defined SQL function.
Nota: Callback functions should return a type understood by SQLite (i.e. scalar type).
Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.
Nota: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.
In this example, we have a function that calculates the md5 sum of a string, and then reverses it. When the SQL statement executes, it returns the value of the filename transformed by our function. The data returned in $rows contains the processed result.
The beauty of this technique is that you do not need to process the result using a foreach() loop after you have queried for the data.
Suggerimento: You can use PDO::sqliteCreateFunction() and PDO::sqliteCreateAggregate() to override SQLite native SQL functions.
Nota: This method is not available with the SQLite2 driver. Use the old style sqlite API for that instead.
Bindings to the libssh2 library which provide access to resources (shell, remote exec, tunneling, file transfer) on a remote machine using a secure cryptographic transport.
Windows binaries may be found at http://snaps.php.net/. To install, download php_ssh2.dll to the folder specified by your php.ini file's extension_dir directive. Enable it by adding extension=php_ssh2.dll to your php.ini and restarting your webserver.
extension_dir=c:/php5/exts/ extension=php_ssh2.dll |
Linux, BSD, and other *nix variants can be compiled using the following steps:
Download and install OpenSSL. If you install OpenSSL via your distribution's packaging system be sure to install the development libraries as well. This will typically be a package named openssl-dev, openssl_devel, or some variation thereof.
Download and install libssh2. Typically this means executing the following command from the libssh2 source tree. ./configure && make all install.
Run the pear installer for PECL/ssh2: pear install ssh2
Copy ssh2.so from the directory indicated by the build process to the location specified in your php.ini file under extension_dir.
Add extension=ssh2.so to your php.ini
Restart your webserver to reload your php.ini settings.
Development Versions: There are currently no stable versions of PECL/ssh2, to force installation of the beta version of PECL/ssh2 execute: pear install ssh2-beta
Compiling PECL/ssh2 without using the PEAR command: Rather than using pear install ssh2 to automatically download and install PECL/ssh2, you may download the tarball from PECL. From the root of the unpacked tarball, run: phpize && ./configure --with-ssh2 && make to generate ssh2.so. Once built, continue the installation from step 4 above.
Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/ssh2.
Nota: You will need version 0.4 or greater of the libssh2 library (possibly higher, see release notes).
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.
Flag to ssh2_fingerprint() requesting hostkey fingerprint as an MD5 hash.
Flag to ssh2_fingerprint() requesting hostkey fingerprint as an SHA1 hash.
Flag to ssh2_fingerprint() requesting hostkey fingerprint as a string of hexits.
Flag to ssh2_fingerprint() requesting hostkey fingerprint as a raw string of 8-bit characters.
Flag to ssh2_shell() specifying that width and height are provided as character sizes.
Flag to ssh2_shell() specifying that width and height are provided in pixel units.
Default terminal width requested by ssh2_shell().
Default terminal height requested by ssh2_shell().
Default terminal units requested by ssh2_shell().
Flag to ssh2_fetch_stream() requesting STDIO subchannel.
Flag to ssh2_fetch_stream() requesting STDERR subchannel.
Default terminal type (e.g. vt102, ansi, xterm, vanilla) requested by ssh2_shell().
Authenticate using a public hostkey read from a file. If privkeyfile is encrypted (which it should be), the passphrase must be provided. If local_username is omitted, then the value for username will be used for it.
Esempio 1. Authentication using a public hostkey
|
Nota: ssh2_auth_hostbased_file() requires libssh2 >= 0.7 and PHP/SSH2 >= 0.7
Attempt "none" authentication which usually will (and should) fail. As part of the failure, this function will return an array of accepted authentication methods. If the server does accept "none" as an authentication method for username, this function will simply return TRUE.
Authenticate over SSH using a plain password
Authenticate using a public key read from a file. If privkeyfile is encrypted (which it should be), the passphrase must be provided.
Esempio 1. Authentication using a public key
|
Establish a connection to a remote SSH server and return a resource on success, FALSE on error.
methods may be an associative array with up to four parameters as described below.
Tabella 1. methods may be an associative array with any or all of the following parameters.
Index | Meaning | Supported Values* |
---|---|---|
kex | List of key exchange methods to advertise, comma separated in order of preference. | diffie-hellman-group1-sha1, diffie-hellman-group14-sha1, and diffie-hellman-group-exchange-sha1 |
hostkey | List of hostkey methods to advertise, come separated in order of preference. | ssh-rsa and ssh-dss |
client_to_server | Associative array containing crypt, compression, and message authentication code (MAC) method preferences for messages sent from client to server. | |
server_to_client | Associative array containing crypt, compression, and message authentication code (MAC) method preferences for messages sent from client to server. |
* - Supported Values are dependent on methods supported by underlying library. See libssh2 documentation for additional information.
Tabella 2. client_to_server and server_to_client may be an associative array with any or all of the following parameters.
Index | Meaning | Supported Values* |
---|---|---|
crypt | List of crypto methods to advertise, comma separated in order of preference. | rijndael-cbc@lysator.liu.se, aes256-cbc, aes192-cbc, aes128-cbc, 3des-cbc, blowfish-cbc, cast128-cbc, arcfour, and none** |
comp | List of compression methods to advertise, comma separated in order of preference. | zlib and none |
mac | List of MAC methods to advertise, come separated in order of preference. | hmac-sha1, hmac-sha1-96, hmac-ripemd160, hmac-ripemd160@openssh.com, and none** |
Crypt and MAC method "none": For security reasons, none is disabled by the underlying libssh2 library unless explicitly enabled during build time by using the appropriate ./configure options. See documentation for the underlying library for more information.
Tabella 3. callbackss may be an associative array with any or all of the following parameters.
Index | Meaning | Prototype |
---|---|---|
ignore | Name of function to call when an SSH2_MSG_IGNORE packet is received | void ignore_cb($message) |
debug | Name of function to call when an SSH2_MSG_DEBUG packet is received | void debug_cb($message, $language, $always_display) |
macerror | Name of function to call when a packet is received but the message authentication code failed. If the callback returns TRUE, the mismatch will be ignored, otherwise the connection will be terminated. | bool macerror_cb($packet) |
disconnect | Name of function to call when an SSH2_MSG_DISCONNECT packet is received | void disconnect_cb($reason, $message, $language) |
Esempio 1. Open a connection forcing 3des-cbc when sending packets, any strength aes cipher when receiving packets, no compression in either direction, and Group1 key exchange.
|
Once connected, the client should verify the server's hostkey using ssh2_fingerprint(), then authenticate using either password or public key.
See Also: ssh2_fingerprint(), ssh2_auth_none(), ssh2_auth_password(), and ssh2_auth_pubkey_file()
Execute a command at the remote end and allocate a channel for it. Returns a stream on success or FALSE on failure.
See Also: ssh2_connect(), ssh2_shell(), and ssh2_tunnel()
Fetches an alternate substream associated with an SSH2 channel stream identified by streamid. The SSH2 protocol currently defines only one substream, STDERR, which has a substream ID of SSH2_STREAM_STDERR (defined as 1).
Esempio 1. Opening a shell and retrieving the stderr stream associated with it.
|
See Also: ssh2_shell(), ssh2_exec(), and ssh2_connect()
Returns a server hostkey hash from an active session. Defaults to MD5 fingerprint encoded as ASCII hex values.
flags may be either of SSH2_FINGERPRINT_MD5 or SSH2_FINGERPRINT_SHA1 logically ORed with SSH2_FINGERPRINT_HEX or SSH2_FINGERPRINT_RAW. Defaults to SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX.
Esempio 1. Checking the fingerprint against a known value
|
Returns list of negotiated methods.
Esempio 1. Determining what methods were negotiated
|
See Also: ssh2_connect()
Nota: The publickey subsystem is used for managing publickeys on a server to which the client is already authenticated. To authenticate to a remote system using publickey authentication, use the ssh2_auth_pubkey_file() function instead.
Publickey Subsystem resource created by ssh2_publickey_init().
Publickey algorithm (e.g.): ssh-dss, ssh-rsa
Publickey blob as raw binary data
If the specified key already exists, should it be overwritten?
Associative array of attributes to assign to this public key. Refer to ietf-secsh-publickey-subsystem for a list of supported attributes. To mark an attribute as mandatory, preceed its name with an asterix. If the server is unable to support an attribute marked mandatory, it will abort the add process.
Esempio 1. Adding a publickey with ssh2_publickey_add()
|
Request the Publickey subsystem from an already connected SSH2 server.
The publickey subsystem allows an already connected and authenticated client to manage the list of authorized public keys stored on the target server in an implementation agnostic manner. If the remote server does not support the publickey subsystem, the ssh2_publickey_init() function will return FALSE.
Nota: The publickey subsystem is used for managing publickeys on a server to which the client is already authenticated. To authenticate to a remote system using publickey authentication, use the ssh2_auth_pubkey_file() function instead.
Returns an SSH2 Publickey Subsystem resource for use with all other ssh2_publickey_*() methods.
Nota: The publickey subsystem is used for managing publickeys on a server to which the client is already authenticated. To authenticate to a remote system using publickey authentication, use the ssh2_auth_pubkey_file() function instead.
Returns a numericly indexed array of keys, each of which is an associative array containing: name, blob, and attrs elements.
Tabella 1. Publickey elements
Array Key | Meaning |
---|---|
name | Name of algorithm used by this publickey, for example: ssh-dss or ssh-rsa. |
blob | Publickey blob as raw binary data. |
attrs | Attributes assigned to this publickey. The most common attribute, and the only one supported by publickey version 1 servers, is comment, which may be any freeform string. |
Esempio 1. Listing authorized keys with ssh2_publickey_list()
Il precedente esempio visualizzerà:
|
Nota: The publickey subsystem is used for managing publickeys on a server to which the client is already authenticated. To authenticate to a remote system using publickey authentication, use the ssh2_auth_pubkey_file() function instead.
Publickey Subsystem Resource
Publickey algorithm (e.g.): ssh-dss, ssh-rsa
Publickey blob as raw binary data
Copy a file from the remote server to the local filesystem using the SCP protocol.
See Also: ssh2_scp_send(), and copy()
Copy a file from the local filesystem to the remote server using the SCP protocol. The file will be created with the mode specified by create_mode.
See Also: ssh2_scp_recv(), and copy()
Stats a symbolic link on the remote filesystem without following the link. This function is similar to using the lstat() function with the ssh2.sftp:// wrapper in PHP5 and returns the same values. See the documentation for stat() for details on the values which may be returned.
Esempio 1. Stating a symbolic link via SFTP
|
See Also: ssh2_sftp_stat(), lstat(), and stat()
Creates a directory on the remote file server with permissions set to mode. If recursive is TRUE any parent directories required for dirname will be automatically created as well. This function is similar to using mkdir() with the ssh2.sftp:// wrapper.
Esempio 1. Creating a directory on a remote server
|
See Also: mkdir(), and ssh2_sftp_rmdir()
Returns the target of a symbolic link.
See Also: readlink(), and ssh2_sftp_symlink()
Translates filename into the effective real path on the remote filesystem.
Esempio 1. Resolving a pathname
|
See Also: realpath(), and ssh2_sftp_symlink() ssh2_sftp_readlink()
Renames a file on the remote filesystem.
See Also: rename()
Removes a directory from the remote file server. This function is similar to using rmdir() with the ssh2.sftp:// wrapper.
Esempio 1. Removing a directory on a remote server
|
See Also: rmdir(), and ssh2_sftp_mkdir()
Stats a file on the remote filesystem following any symbolic links. This function is similar to using the stat() function with the ssh2.sftp:// wrapper in PHP5 and returns the same values. See the documentation for stat() for details on the values which may be returned.
Esempio 1. Stating a file via SFTP
|
See Also: ssh2_sftp_lstat(), lstat(), and stat()
Creates a symbolic link named link on the remote filesystem pointing to target.
See Also: symlink(), and ssh2_sftp_readlink()
Deletes a file on the remote filesystem
See Also: unlink()
Request the SFTP subsystem from an already connected SSH2 server.
This method returns an SSH2 SFTP resource for use with all other ssh2_sftp_*() methods and the ssh2.sftp:// fopen wrapper.
See Also: ssh2_scp_send(), and ssh2_scp_recv()
Open a shell at the remote end and allocate a stream for it. term_type should correspond to one of the entries in the target system's /etc/termcap file and defaults to vanilla. env may be passed as an associative array of name/value pairs to set in the target environment.
width, and height define the width and height of the virtual terminal allocated for the shell process. width_height_type should be one of SSH2_TERM_UNIT_CHARS or SSH2_TERM_UNIT_PIXELS.
See Also: ssh2_exec(), ssh2_tunnel(), and ssh2_fetch_stream()
Open a socket stream to an arbitrary host/port by way of the currently connected SSH server.
See Also: ssh2_connect(), and fsockopen()
Streams were introduced with PHP 4.3.0 as a way of generalizing file, network, data compression, and other operations which share a common set of functions and uses. In its simplest definition, a stream is a resource object which exhibits streamable behavior. That is, it can be read from or written to in a linear fashion, and may be able to fseek() to an arbitrary locations within the stream.
A wrapper is additional code which tells the stream how to handle specific protocols/encodings. For example, the http wrapper knows how to translate a URL into an HTTP/1.0 request for a file on a remote server. There are many wrappers built into PHP by default (See Appendice M), and additional, custom wrappers may be added either within a PHP script using stream_wrapper_register(), or directly from an extension using the API Reference in Capitolo 44. Because any variety of wrapper may be added to PHP, there is no set limit on what can be done with them. To access the list of currently registered wrappers, use stream_get_wrappers().
A stream is referenced as: scheme://target
scheme(string) - The name of the wrapper to be used. Examples include: file, http, https, ftp, ftps, compress.zlib, compress.bz2, and php. See Appendice M for a list of PHP builtin wrappers. If no wrapper is specified, the function default is used (typically file://).
target - Depends on the wrapper used. For filesystem related streams this is typically a path and filename of the desired file. For network related streams this is typically a hostname, often with a path appended. Again, see Appendice M for a description of targets for builtin streams.
A filter is a final piece of code which may perform operations on data as it is being read from or written to a stream. Any number of filters may be stacked onto a stream. Custom filters can be defined in a PHP script using stream_filter_register() or in an extension using the API Reference in Capitolo 44. To access the list of currently registered filters, use stream_get_filters().
A context is a set of parameters and wrapper specific options which modify or enhance the behavior of a stream. Contexts are created using stream_context_create() and can be passed to most filesystem related stream creation functions (i.e. fopen(), file(), file_get_contents(), etc...).
Options can be specified when calling stream_context_create(), or later using stream_context_set_option(). A list of wrapper specific options can be found with the list of built-in wrappers (See Appendice M).
In addition, parameters may be set on a context using stream_context_set_params(). Currently the only context parameter supported by PHP is notification. The value of this parameter must be the name of a function to be called when an event occurs on a stream. The notification function called during an event should accept the following six parameters:
void my_notifier ( int notification_code, int severity, string message, int message_code, int bytes_transferred, int bytes_max )notification_code and severity are numerical values which correspond to the STREAM_NOTIFY_* constants listed below. If a descriptive message is available from the stream, message and message_code will be populated with the appropriate values. The meaning of these values is dependent on the specific wrapper in use. bytes_transferred and bytes_max will be populated when applicable.
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. This option must be used together with the STREAM_CLIENT_CONNECT flag. Used with stream_socket_client(). |
STREAM_CLIENT_CONNECT * | Open client socket connection. Client sockets should always include this flag. Used with stream_socket_client(). |
STREAM_CLIENT_PERSISTENT * | Client socket opened with stream_socket_client() should remain persistent between page loads. |
STREAM_SERVER_BIND * | Tells a stream created with stream_socket_server() to bind to the specified target. Server sockets should always include this flag. |
STREAM_SERVER_LISTEN * | Tells a stream created with stream_socket_server() and bound using the STREAM_SERVER_BIND flag to start listening on the socket. Connection-orientated transports (such as TCP) must use this flag, otherwise the server socket will not be enabled. Using this flag for connect-less transports (such as UDP) is an error. |
STREAM_NOTIFY_RESOLVE * | A remote address required for this stream has been resolved, or the resolution failed. See severity for an indication of which happened. |
STREAM_NOTIFY_CONNECT | A connection with an external resource has been established. |
STREAM_NOTIFY_AUTH_REQUIRED | Additional authorization is required to access the specified resource. Typical issued with severity level of STREAM_NOTIFY_SEVERITY_ERR. |
STREAM_NOTIFY_MIME_TYPE_IS | The mime-type of resource has been identified, refer to message for a description of the discovered type. |
STREAM_NOTIFY_FILE_SIZE_IS | The size of the resource has been discovered. |
STREAM_NOTIFY_REDIRECTED | The external resource has redirected the stream to an alternate location. Refer to message. |
STREAM_NOTIFY_PROGRESS | Indicates current progress of the stream transfer in bytes_transferred and possibly bytes_max as well. |
STREAM_NOTIFY_COMPLETED * | There is no more data available on the stream. |
STREAM_NOTIFY_FAILURE | A generic error occurred on the stream, consult message and message_code for details. |
STREAM_NOTIFY_AUTH_RESULT | Authorization has been completed (with or without success). |
STREAM_NOTIFY_SEVERITY_INFO | Normal, non-error related, notification. |
STREAM_NOTIFY_SEVERITY_WARN | Non critical error condition. Processing may continue. |
STREAM_NOTIFY_SEVERITY_ERR | A critical error occurred. Processing cannot continue. |
STREAM_IPPROTO_ICMP + | Provides a ICMP socket. |
STREAM_IPPROTO_IP + | Provides a IP socket. |
STREAM_IPPROTO_RAW + | Provides a RAW socket. |
STREAM_IPPROTO_TCP + | Provides a TCP socket. |
STREAM_IPPROTO_UDP + | Provides a UDP socket. |
STREAM_PF_INET + | Internet Protocol Version 4 (IPv4). |
STREAM_PF_INET6 + | Internet Protocol Version 6 (IPv6). |
STREAM_PF_UNIX + | Unix system internal protocols. |
STREAM_SOCK_DGRAM + | Provides datagrams, which are connectionless messages (UDP, for example). |
STREAM_SOCK_RAW + | Provides a raw socket, which provides access to internal network protocols and interfaces. Usually this type of socket is just available to the root user. |
STREAM_SOCK_RDM + | Provides a RDM (Reliably-delivered messages) socket. |
STREAM_SOCK_SEQPACKET + | Provides a sequenced packet stream socket. |
STREAM_SOCK_STREAM + | Provides sequenced, two-way byte streams with a transmission mechanism for out-of-band data (TCP, for example). |
Nota: The constants marked with * are just available since PHP 5.0.0.
Nota: The constants marked with + are available since PHP 5.1.0 and are meant to be used with stream_socket_pair(). Please note that some of these constants might not be available in your system.
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
|
Avvertimento |
Questa 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. |
Creates and returns a stream context with any options supplied in options preset.
options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value. It defaults to an empty array.
Esempio 1. Using stream_context_create()
|
See also stream_context_set_option(), and Listing of supported wrappers with context options (Appendice M).
Returns the default stream context which is used whenever file operations (fopen(), file_get_contents(), etc...) are called without a context parameter. Options for the default context can optionally be specified with this function using the same syntax as stream_context_create().
options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.
Esempio 1. Using stream_context_get_default()
|
See also stream_context_create(), and Listing of supported wrappers with context options (Appendice M).
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 (or from the offset position, if specified) in source to dest. If maxlength is not specified, all remaining content in source will be copied.
The source stream
The destination stream
Maximum bytes to copy
The offset where to start to copy data
Esempio 1. A stream_copy_to_stream() example
|
Adds filtername to the list of filters attached to stream. This filter will be added with the specified params to the end of the list and will therefore be called last during stream operations. To add a filter to the beginning of the list, use stream_filter_prepend().
By default, stream_filter_append() will attach the filter to the read filter chain if the file was opened for reading (i.e. File Mode: r, and/or +). The filter will also be attached to the write filter chain if the file was opened for writing (i.e. File Mode: w, a, and/or +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, and/or STREAM_FILTER_ALL can also be passed to the read_write parameter to override this behavior.
As of PHP 5.1.0, this function returns a resource which can be used to refer to this filter instance during a call to stream_filter_remove(). Prior to PHP 5.1.0, this function returns TRUE on success or FALSE on failure.
Esempio 1. Controlling where filters are applied
|
When using custom (user) filters: stream_filter_register() must be called first in order to register the desired user filter to filtername.
Nota: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is appended to a stream, data in the internal buffers is processed through the new filter at that time. This differs from the behavior of stream_filter_prepend().
See also stream_filter_register(), stream_filter_prepend(), and stream_get_filters().
Adds filtername to the list of filters attached to stream. This filter will be added with the specified params to the beginning of the list and will therefore be called first during stream operations. To add a filter to the end of the list, use stream_filter_append().
By default, stream_filter_prepend() will attach the filter to the read filter chain if the file was opened for reading (i.e. File Mode: r, and/or +). The filter will also be attached to the write filter chain if the file was opened for writing (i.e. File Mode: w, a, and/or +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, and/or STREAM_FILTER_ALL can also be passed to the read_write parameter to override this behavior. See stream_filter_append() for an example of using this parameter.
As of PHP 5.1.0, this function returns a resource which can be used to refer to this filter instance during a call to stream_filter_remove(). Prior to PHP 5.1.0, this function returns TRUE on success or FALSE on failure.
When using custom (user) filters: stream_filter_register() must be called first in order to register the desired user filter to filtername.
Nota: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is prepended to a stream, data in the internal buffers, which has already been processed through other filters will not be reprocessed through the new filter at that time. This differs from the behavior of stream_filter_append().
See also stream_filter_register(), and stream_filter_append().
(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
Il precedente esempio visualizzerà:
|
Esempio 2. Registering a generic filter class to match multiple filter names.
Il precedente esempio visualizzerà:
|
See also stream_wrapper_register(), stream_filter_prepend(), and stream_filter_append().
Removes a stream filter previously added to a stream with stream_filter_prepend() or stream_filter_append(). Any data remaining in the filter's internal buffer will be flushed through to the next filter before removing it.
Esempio 1. Dynamicly refiltering a stream
|
See also stream_filter_register(), stream_filter_append(), and stream_filter_prepend().
Identical to file_get_contents(), except that stream_get_contents() operates on an already open stream resource and returns the remaining contents in a string, up to maxlength bytes and starting at the specified offset.
Esempio 1. stream_get_contents() example
|
fgets() |
fread() |
fpassthru() |
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
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 PHP's own internal buffer.
Nota: You shouldn't use this value in a script.
The following items were added in PHP 4.3:
stream_type (string) - a label describing the underlying implementation of the stream.
wrapper_type (string) - a label describing the protocol wrapper implementation layered over the stream. See Appendice M for more information about wrappers.
wrapper_data (mixed) - wrapper specific data attached to this stream. See Appendice M for more information about wrappers and their wrapper data.
filters (array) - and array containing the names of any filters that have been stacked onto this stream. Documentation on filters can be found in the Filters appendix.
Nota: This function was introduced in PHP 4.3, but prior to this version, socket_get_status() could be used to retrieve the first four items, for socket based streams only.
In PHP 4.3 and later, socket_get_status() is an alias for this function.
Nota: This function does NOT work on sockets created by the Socket extension.
The following items were added in PHP 5.0:
mode (string) - the type of access required for this stream (see Table 1 of the fopen() reference)
seekable (bool) - whether the current stream can be seeked.
uri (string) - the URI/filename associated with this stream.
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.
Nota: Windows compatibility: stream_select() used on a pipe returned from proc_open() may cause data loss under Windows 98.
Use of stream_select() on file descriptors returned by proc_open() will fail and return FALSE under Windows.
See also stream_set_blocking().
If mode is 0, the given stream will be switched to non-blocking mode, and if 1, it will be switched to blocking mode. This affects calls like fgets() and fread() that read from the stream. In non-blocking mode an fgets() call will always return right away while in blocking mode it will wait for data to become available on the stream.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
This function was previously called as set_socket_blocking() and later socket_set_blocking() but this usage is deprecated.
Nota: Prior to PHP 4.3, this function only worked on socket based streams. Since PHP 4.3, this function works for any stream that supports non-blocking mode (currently, regular files and socket streams).
See also stream_select().
Sets the timeout value on stream, expressed in the sum of seconds and microseconds. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
When the stream times out, the 'timed_out' key of the array returned by stream_get_meta_data() is set to TRUE, although no error/warning is generated.
Esempio 1. stream_set_timeout() example
|
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.
Avvertimento |
This function should not be used with UDP server sockets. Instead, use stream_socket_recvfrom() and stream_socket_sendto(). |
See also stream_socket_server(), stream_socket_get_name(), stream_set_blocking(), stream_set_timeout(), fgets(), fgetss(), fwrite(), fclose(), feof(), and the Curl extension.
Initiates a stream or datagram connection to the destination specified by remote_socket. The type of socket created is determined by the transport specified using standard URL formatting: transport://target. For Internet Domain sockets (AF_INET) such as TCP and UDP, the target portion of the remote_socket parameter should consist of a hostname or IP address followed by a colon and a port number. For Unix domain sockets, the target portion should point to the socket file on the filesystem. The optional timeout can be used to set a timeout in seconds for the connect system call. flags is a bitmask field which may be set to any combination of connection flags. Currently the selection of connection flags is limited to STREAM_CLIENT_CONNECT (default), STREAM_CLIENT_ASYNC_CONNECT and STREAM_CLIENT_PERSISTENT.
Nota: If you need to set a timeout for reading/writing data over the socket, use stream_set_timeout(), as the timeout parameter to stream_socket_client() only applies while connecting the socket.
stream_socket_client() returns a stream resource which may be used together with the other file functions (such as fgets(), fgetss(), fwrite(), fclose(), and feof()).
If the call fails, it will return FALSE and if the optional errno and errstr arguments are present they will be set to indicate the actual system level error that occurred in the system-level connect() call. If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the connect() call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments will always be passed by reference.
Depending on the environment, the Unix domain or the optional connect timeout may not be available. A list of available transports can be retrieved using stream_get_transports(). See Appendice O for a list of built in transports.
The stream will by default be opened in blocking mode. You can switch it to non-blocking mode by using stream_set_blocking().
Esempio 1. stream_socket_client() Example
|
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.
(PHP 5 >= 5.1.0RC1)
stream_socket_enable_crypto -- Turns encryption on/off on an already connected socketWhen called with the crypto_type parameter, stream_socket_enable_crypto() will setup encryption on the stream using the specified method.
Valid values for crypto_type
STREAM_CRYPTO_METHOD_SSLv2_CLIENT
STREAM_CRYPTO_METHOD_SSLv3_CLIENT
STREAM_CRYPTO_METHOD_SSLv23_CLIENT
STREAM_CRYPTO_METHOD_TLS_CLIENT
STREAM_CRYPTO_METHOD_SSLv2_SERVER
STREAM_CRYPTO_METHOD_SSLv3_SERVER
STREAM_CRYPTO_METHOD_SSLv23_SERVER
STREAM_CRYPTO_METHOD_TLS_SERVER
Once the crypto settings are established, cryptography can be turned on and off dynamically by passing TRUE or FALSE in the enable parameter.
If this stream should be seeded with settings from an already established crypto enabled stream, pass that stream's resource variable in the fourth parameter.
Returns TRUE on success, FALSE if negotiation has failed or 0 if there isn't enough data and you should try again (only for non-blocking sockets).
Esempio 1. stream_socket_enable_crypto() Example
|
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().
(PHP 5 >= 5.1.0RC1)
stream_socket_pair -- Creates a pair of connected, indistinguishable socket streamsstream_socket_pair() creates a pair of connected, indistinguishable socket streams. This function is commonly used in IPC (Inter-Process Communication).
The protocol family to be used: STREAM_PF_INET, STREAM_PF_INET6 or STREAM_PF_UNIX
The type of communication to be used: STREAM_SOCK_DGRAM, STREAM_SOCK_RAW, STREAM_SOCK_RDM, STREAM_SOCK_SEQPACKET or STREAM_SOCK_STREAM
The protocol to be used: STREAM_IPPROTO_ICMP, STREAM_IPPROTO_IP, STREAM_IPPROTO_RAW, STREAM_IPPROTO_TCP or STREAM_IPPROTO_UDP
Nota: Please consult the Streams constant list for further details on each constant.
Esempio 1. A stream_socket_pair() example This example shows the basic usage of stream_socket_pair() in Inter-Process Comunication.
Il precedente esempio visualizzerà qualcosa simile a:
|
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
|
Nota: If a message received is longer than the length parameter, excess bytes may be discarded depending on the type of socket the message is received from (such as UDP).
See also stream_socket_sendto(), stream_socket_client(), and stream_socket_server().
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.
Nota: For UDP sockets, you must use STREAM_SERVER_BIND as the flags parameter.
This function only creates a socket, to begin accepting connections use stream_socket_accept().
If the call fails, it will return FALSE and if the optional errno and errstr arguments are present they will be set to indicate the actual system level error that occurred in the system-level socket(), bind(), and listen() calls. If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the bind() call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments will always be passed by reference.
Depending on the environment, Unix domain sockets may not be available. A list of available transports can be retrieved using stream_get_transports(). See Appendice O for a list of bulitin transports.
Esempio 1. Using TCP server sockets
|
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
|
Restores a built-in wrapper previously unregistered with stream_wrapper_unregister().
stream_wrapper_unregister() allows you to disable an already defined stream wrapper. Once the wrapper has been disabled you may override it with a user-defined wrapper using stream_wrapper_register() or reenable it later on with stream_wrapper_restore().
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 saranno convertiti in \0, \a, \b, \f, \n, \r, \t e \v. In PHP \0 (NULL), \r (carriage return), \n (newline) e \t (tab) sono sequenze di escape predefinite, anche in C tutte queste sono sequenze di escape predefinite.
Valorizzare il parametro charlist con "\0..\37", significa che si vuole inserire il carattere di escape davanti ai caratteri la cui codifica ASCII è comprese tra 0 e 31.
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 tutti i dati GET, POST, e COOKIE. Non utilizzare addslashes() su stringhe che hanno già il carattere di escape per via del parametro magic_quotes_gpc altrimenti si ottiene un doppio escape. La funzione get_magic_quotes_gpc() può aiutare nella verifica di questa situazione.
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.
This function is an alias of: rtrim().
Nota: chop() è differente rispetto alla omonima funzione di Perl chop(), la quale rimuove l'ultimo carattere della stringa.
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
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
La funzione convert_uudecode() decodifica una stringa codificata con uuencode.
Vedere anche convert_uuencode().
convert_uuencode() codifica una trsinga usando l'algoritmo uuencode.
L'algoritmo uuencode codifica tutte le stringhe (comprese quelle binarie) in caratteri stampabili, rendendole sicure per la trasmissione via rete. I dati così codificati hanno una dimensione del 35% superiore all'originale.
Vedere anche convert_uudecode() e base64_encode().
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 ad ogni chiamata.
Alcuni sistemi operativi supportano più di un tipo di cifratura. Infatti in alcuni casi lo standard basato sul DES viene sostituito da un algoritmo basato su MD5. Il tipo di crittografia da utilizzare viene attivato tramite il parametro salt. Al momento dell'installazione il PHP cerca di determinare le caratteristiche della funzione crypt e accetterà salt per altri tipi di funzioni. Se il parametro salt non viene passato, il PHP genererà, per default, una chiave di due caratteri a meno che il sistema di cifratura di default del sistema non sia MD5, in questo caso si genererà una chiave casuale compatibile con MD5. Il PHP imposta una costante chiamata CRYPT_SALT_LENGTH dalla quale si può sapere se sul sistema si può utilizzare una chiave di due caratteri o la chiave più lunga di 12 caratteri.
Se si usa la chiave generata, bisogna fare attenzione che questa viene generata una sola volta. Se si chiama la funzione ricorsivamente, si possono avere dei problemi di formato e di sicurezza.
La crittografia basa sullo standard DES restituisce la chiave come primi due caratteri dell'output. Inoltre utilizza solo i primi 8 caratteri del parametro str, pertanto stringhe più lunghe che inizino con i medesimi otto caratteri, creeranno il medesimo risultato (se si utilizza la medesima chiave).
Sui sistemi nei quali la funzione cript() supporta più tipi di crittografia, si imposteranno le seguenti costanti a 0 o a 1 in base al tipo disponibile.
CRYPT_STD_DES - Standard basato su DES con chiave di due caratteri
CRYPT_EXT_DES - Estensione basato su DES con chiave di nove caratteri
CRYPT_MD5 - Crittografia basata su MD5 con 12 caratteri di chiave inizianti con $1$
CRYPT_BLOWFISH - Crittografia Blowfish con 16 caratteri di chiave inizianti con $2$ oppure $2a$
Nota: Non esiste una funzione di decriptazione, poiché crypt() è un algoritmo ad una via.
Esempio 1. Esempio di uso di crypt()
|
Esempio 3. Uso dei diversi tipi di criptazione
Il precedente esempio visualizzerà qualcosa simile a:
|
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.
Se il parametro limit è negativo, sono restituiti tutti i componenti tranne gli ultimi limit elementi. Questa caratteristica è stata inserita in PHP 5.1.0.
Sebbene implode() può, per ragioni storiche, accettare i parametri in entrambi gli ordini, explode() non può. Occorre accertarsi che il parametro separator sia antecedente al parametro string.
Nota: Il parametro limit è stato aggiunto dalla versione 4.0.1
Esempio 1. Esempi di uso di explode()
|
Esempio 2. Esempi del parametro limit
Il precedente esempio visualizzerà:
|
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Vedere anche preg_split(), spliti(), split(), strtok() e implode().
La funzione scrive una stringa formattata in base al parametro format nello stream indicato dal parametro handle. I valori per il parametro format sono descritti nella documentazione della funzione sprintf().
Restituisce la lunghezza della stringa prodotta.
Vedere anche: printf(), sprintf(), sscanf(), fscanf(), vsprintf() e number_format().
Esempio 2. fprintf(): formattazione della moneta
|
(PHP 4, PHP 5)
get_html_translation_table -- Restituisce la tabella di decodifica utilizzata da htmlspecialchars() e htmlentities()La funzione get_html_translation_table() restituisce la tabella di decodifica utilizzata dalle funzioni htmlspecialchars() e htmlentities().
Esistono due nuove costanti (HTML_ENTITIES, HTML_SPECIALCHARS) che permettono di indicare quale tabella sid esidera. Inoltre nelle funzioni htmlspecialchars() e htmlentities(), opzionalmente, si può specificare il quote_style con cui si lavora. Il default è ENT_COMPAT. Vedere la descrizione di queste modalità in htmlspecialchars().
Un'altro utilizzo interessante di questa funzione è dato, in combinazione con array_flip(), dalla possibilità di cambiare direzione alla decodifica.
Il contenuto $original sarà: "Hallo & <Frau> & Krämer".Vedere anche: htmlspecialchars(), htmlentities(), strtr() e array_flip().
Il parametro opzionale max_chars_per_line indica il numero massimo di caratteri per linea che saranno restituiti in output. La funzione tenta di evitare di spezzare le parole.
Vedere anche hebrevc()
(PHP 3, PHP 4, PHP 5)
hebrevc -- Converte il testo logico Ebraico in testo visuale con conversione del carattere di 'a capo'Questa funzione è simile a hebrev() con la differenza che converte il carattere di 'a capo' (\n) in "<br>\n". Il parametro opzionale max_chars_per_line indica il numero massimo di caratteri per linea che saranno restituiti. La funzione tenta di evitare di spezzare le parole.
Vedere anche hebrev()
La funzione html_entity_decode() è l'opposto di htmlentities() converte tutte le entità HTML presenti nel parametro string nel corrispondente carattere.
Il secondo parametro, quote_style, opzionale, indica cosa occorre fare per gli apici 'singoli' e "doppi". Sono possibili tre scelte indicate da tre costanti con default ENT_COMPAT:
Tabella 1. Costanti disponibili per quote_style
Nome della costante | Descrizione |
---|---|
ENT_COMPAT | Converte gli apici doppi e lascia inalterati gli apici singoli. |
ENT_QUOTES | Converte sia gli apici doppi sia gli apici singoli. |
ENT_NOQUOTES | Lascia entrambi i tipi di apici inalterati. |
Per il terzo parametro opzionale, charset, si utilizza come default il set di caratteri ISO-8859-1. Questo parametro indica quale set di caratteri utilizzare per la conversione.
Elenco dei set di caratteri supportati dal PHP 4.3.0 e successivi.
Tabella 2. set di caratteri supportati
Set di 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. Decodifica delle entità HTML
|
Nota: Ci si può chiedere come mai la sequenza trim(html_entity_decode(' ')); non produca una stringa vuota; questo accade perchè l'intità ' ' non corrisponde al codice ASCII 32 (che verrebbe rimosso da trim()), ma, nella codifica di default ISO-8859-1, corrisponde al carattere ASCII 160 (0xa0).
Vedere anche htmlentities(), htmlspecialchars(), get_html_translation_table(), and urldecode().
Questa funzione è identica a htmlspecialchars() tranne che htmlentities() converte tutti i caratteri che hanno una corrispettiva entità HTML.
Come per la funzione htmlspecialchars(), il secondo parametro opzionale quote_style indica cosa occorre fare per gli apici 'singoli' e "doppi". Sono possibili tre scelte indicate da tre costanti con default ENT_COMPAT:
Tabella 1. Costanti disponibili per quote_style
Nome della costante | Descrizione |
---|---|
ENT_COMPAT | Converte gli apici doppi e lascia inalterati gli apici singoli. |
ENT_QUOTES | Converte sia gli apici doppi sia gli apici singoli. |
ENT_NOQUOTES | Lascia entrambi i tipi di apici inalterati. |
Il suupporto per il parametro quote è stato introdotto in PHP 4.0.3.
Come per la funzione htmlspecialchars(), questa ha un terzo parametro charset, opzionale, che definisce quale set di caratteri utilizzare per la conversione. Il supporto per questo parametro è stato aggiunto in PHP 4.1.0. Attualmente per default si utilizza il set ISO-8859-1.
Elenco dei set di caratteri supportati dal PHP 4.3.0 e successivi.
Tabella 2. set di caratteri supportati
Set di 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.
Se si deve esere una decodifica (un giro al contrario) occorre utilizzare la funzione html_entity_decode().
Vedere anche html_entity_decode(), get_html_translation_table(), htmlspecialchars(), nl2br() e urlencode().
This function is the opposite of htmlspecialchars(). It converts special HTML entities back to characters.
The converted entities are: &, " (when ENT_NOQUOTES is not set), ' (when ENT_QUOTES is set), < and >.
The string to decode
The quote style. One of the following constants:
Alcuni caratteri hanno significati particolari in HTML, e, per questo, devono essere rappresentati tramite entità HTML, se devono mantenere il proprio significato. Questa funzione restituisce restituisce una stringa con la conversione di alcuni di questi caratteri; la conversione svolta non è sempre valida nell'ambito della programmazione web. Se occorre l'utilizzo di tutte le entità HTML, utilizzare htmlentities().
Questa funzione è utile nel prevenire la presenza di marcatori HTML negli input utente, tipo nei forum o nei guest book. Il secondo parametro quote_style, opzionale, indica alla funzione come comportarsi con gli apici singoli e doppi. La modalità di default è, ENT_COMPAT; questa modalità è compatibile con il passato e traduce solo gli apici doppi lasciando inalterati gli apici singoli. Se si imposta ENT_QUOTES, entrambi i tipi di apici, singoli e doppi, sono convertiti in entità e, infine, se si utilizza ENT_NOQUOTES ne gli apici singoli ne gli apici doppi sono convertiti in entità.
La conversioni applicate sono:
'&' (e commerciale) diventa '&'
'"' (doppio apice) diventa '"' con ENT_NOQUOTES is not set.
''' (singolo apice) diventa ''' soltanto con l'impostazione di ENT_QUOTES.
'<' (minore) diventa '<'
'>' (maggiore) diventa '>'
Occorre notare che questa funzione non converte null'altro oltre ai caratteri elencati in precedenza. Per la conversione di tutte le entità fare riferimento a htmlentities(). Il secondo parametro è stato inserito in PHP 3.0.17 e 4.0.3.
Il terzo parametro charset indica quale set di caratteri utilizzare nella conversione. Il set di caratteri di default è ISO-8859-1. Questo terzo parametro è stato aggiunto in PHP 4.1.0.
Elenco dei set di caratteri supportati dal PHP 4.3.0 e successivi.
Tabella 1. set di caratteri supportati
Set di 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.
Vedere anche get_html_translation_table(), strip_tags(), htmlentities() e nl2br().
Restituisce una stringa contenente tutti gli elementi di una matrice nel medesimo ordine, inserendo il parametro glue tra un elemento e l'altro.
Nota: La funzione implode(), per ragioni storiche, può accettare i propri parametri in entrambi gli ordini. Tuttavia per mantenere la consistenza con explode(), ed avere meno confusione, utilizzare i parametri nell'ordine documentato.
Nota: Dal PHP 4.3.0, il parametro glue di implode() è opzionale e come default utilizza una stringa vuota (''). Questo non è l'utilizzo preferenziale di implode(). Si suggerisce di utilizzare sempre il secondo parametro per compatibilità con le vecchie versioni.
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
(PHP 3 >= 3.0.17, PHP 4 >= 4.0.1, PHP 5)
levenshtein -- Calcola la distanza Levenshtein tra due stringheQuesta funzione restituisce la distanza Levenshtein tra due stringhe o -1 se uno degli argomenti è più lungo del limite di 255 caratteri.
La distanza Levenshtein è definita come il numero minimo di caratteri da sostituire, inserire o cancellare per trasformare str1 in str2. La complessità dell'algoritmo è O(m*n), dove n e m sono rispettivamente la lunghezza di str1 e di str2 (valore piuttosto buono se confrontato con similar_text(), che è O(max(n,m)**3), ma comunque costoso).
Nella sua versione più semplice la funzione richiede come parametri due stringhe e calcola il numero di caratteri da inserire, sostituire o rimuovere necessari a trasformare str1 in str2.
La seconda variante utilizza tre parametri addizionali che definiscono il costo delle operazioni di inserimento, sostituzione e di cancellazione. Questa versione è più generale e adattabile della precedente, ma non è altrettanto efficiente.
Esempio 1. Esempio di uso di levenshtein()
Il precedente esempio visualizzerà:
|
Vedere anche soundex(), similar_text() e metaphone().
La funzione restituisce un array associativo contenente le configurazioni locali per il formato numerico e monetario.
La funzione localeconv() restituisce i dati in base alle configurazioni locali come impostate da setlocale(). L'array associativo restituito contiene i seguenti campi:
Elemento | Descrizione | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
decimal_point | Carattere per il punto decimale | ||||||||||
thousands_sep | Separatore delle migliaia | ||||||||||
grouping | Array contenente i gruppi numerici | ||||||||||
int_curr_symbol | Simbolo internazionale della divisa (i.e. USD) | ||||||||||
currency_symbol | Simbolo della divisa locale (i.e. $) | ||||||||||
mon_decimal_point | Carattere per il punto decimale nella moneta | ||||||||||
mon_thousands_sep | Separatore delle migliaia nella moneta | ||||||||||
mon_grouping | Array contenente i gruppi monetari | ||||||||||
positive_sign | Segno per i valori positivi | ||||||||||
negative_sign | Segno per i valori negativi | ||||||||||
int_frac_digits | Numero di caratteri frazionali internazionali | ||||||||||
frac_digits | Numero di caratteri frazionali locali | ||||||||||
p_cs_precedes | TRUE se il simbolo della divisa precede i valori positivi, FALSE se segue tali valori | ||||||||||
p_sep_by_space | TRUE se uno spazio separa il simbolo della divisa dai valori positivi FALSE in caso contrario | ||||||||||
n_cs_precedes | TRUE se il simbolo della divisa precede i valori negativi, FALSE se segue tali valori | ||||||||||
n_sep_by_space | TRUE se uno spazio separa il simbolo della divisa dai valori negativi, FALSE in caso contrario | ||||||||||
p_sign_posn |
| ||||||||||
n_sign_posn |
|
I campi di raggruppamento contengono matrici che definiscono il modo con cui i numeri dovrebbero essere raggruppati. Ad esempio, i campi di raggruppamento per il formato en_US, contengono due elementi con i valori 3 e 3. L'indice più alto indica quanto è distinta il gruppo di sinistra. Se un elemento della matrice è uguale a CHAR_MAX, non vi sono più gruppi. Se nella matrice vi è un elemento a 0, occorre utilizzare l'elemento precedente.
Esempio 1. Esempio di uso di localeconv()
|
E' presente una costante, CHAR_MAX, per gli utilizzi descritti in precedenza.
Vedere anche setlocale().
Nota: Il secondo parametro è stato aggiunto nella versione 4.1.0 di PHP.
Questa funzione restituisce la stringa str a cui sono stati rimossi gli spazi iniziali. Senza la specifica del secondo parametro ltrim() rimuoverà i seguenti caratteri:
" " (ASCII 32 (0x20)), spazio ordinario.
"\t" (ASCII 9 (0x09)), tab.
"\n" (ASCII 10 (0x0A)), newline (line feed).
"\r" (ASCII 13 (0x0D)), carriage return.
"\0" (ASCII 0 (0x00)), il byte NUL.
"\x0B" (ASCII 11 (0x0B)), il tab verticale.
Si può anche specificare i caratteri che si desidera rimuovere, indicandoli nel parametro charlist. Quest'ultimo è costituito da un semplice elenco di caratteri da rimuovere. Con .. si può specificare un range di caratteri.
Esempio 1. Esempio di uso di ltrim()
|
Calcola l'hash md5 del file filename utilizzando l' RSA Data Security, Inc. MD5 Message-Digest Algorithm, e lo restituisce. L'hash prodotto è un numero esadecimale di 32 caratteri. Se il secondo parametro raw_output è impostato a TRUE, il valore md5 è restituito nel formato binario raw con una lunghezza di 16 caratteri.
Nota: Il parametro opzionale raw_output è stato aggiunto in PHP 5.0.0, e come default vale FALSE
Questa funzione ha il medesimo scopo dell'utilità di linea di comando md5sum.
Vedere anche md5(), crc32() e sha1_file().
Calcola il valore md5 della stringa str utilizzando il RSA Data Security, Inc. MD5 Message-Digest Algorithm, e restituisce tale valore. L'hash prodotto è un numero esadecimale di 32 caratteri. Se il secondo parametro raw_output è impostato a TRUE, il valore md5 è restituito nel formato binario raw con una lunghezza di 16 caratteri.
Nota: Il parametro opzionale raw_output è stato aggiunto in PHP 5.0.0, e come default vale FALSE
Vedere anche crc32(), md5_file() e sha1().
Calcola la chiave metaphone di str.
In modo simile a soundex() la funzione crea la medesima chiave per parole con il medesimo suono. Questa funzione è più accurata che soundex() poiché conosce le regole di base della pronuncia inglese. Le chiavi metaphone generate hanno lunghezza variabile.
La chiave Metaphone è stata sviluppata da Lawrence Philips <lphilips at verity dot com>. Viene descritta in ["Practical Algorithms for Programmers", Binstock & Rex, Addison Wesley, 1995].
money_format() restituisce una versione formattata di number. Questa funzione è un'interfaccia alla funzione C strfmon(), con la differenza che questa funzione converte un solo numero alla volta.
Nota: La funzione money_format() esiste solo se il sistema suppporta strfmon. Ad esempio, Windows non lo supporta perciò la funzione money_format() non è definita su Windows.
LA specifica del formato consiste nella seguente sequenza:
un carattere %
un flag opzionale flags
la lunghezza del campo, opzionale
la precisione a sinistra, opzionale
la precisione a destra, opzionale
un carattere di conversione, obbligatorio
Flag. Si possono utilizzare uno o più dei seguenti flag:
Il carattere = seguito da un singolo carattere (singolo byte) f è utilizzato come carattere di riempimento numerico. Il carattere di default è lo spazio.
Disabilita l'utilizzo del raggruppamento dei caratetrei (come definito nelle impostazioni locali).
Specifica lo stile di formattazione per i numeri positivi e negativi. Se si utilizza +, sarà utilizzato l'equivalente valore locale per + e -. Se si utilizza (, i valori negativi saranno racchiusi tra parentesi. Se non si da specifica, il default è +.
Sopprime il simbolo della moneta nella stringa di output.
Se presente, rende tutti i campi giustificati a sinistra (riempiti a a destra), il default prevede i campi allineati a destra (riempiti a sinistra).
Dimensioni del campo.
Una stringa numerica che specifica la lunghezza minima del campo. Il campo sarà allineato a destra a meno di non avere impostato il flag -. Il valore di default è 0 (zero).
Precisione a sinistra.
Sono attesi un numero massimo di (n) numeri a sinistra del carattere decimale (es. il punto decimale). Solitamente si utilizza per mantenere allineato l'output nella medesima colonna, utilizzando il carattere di riempimento, se il numero delle cifre è inferiore a n. Se il numero delle cifre è superiore a n, questa specifica viene ignorata.
Se il raggruppamento delle cifre non è soppresso tramite ^, saranno inseriti i separatori di raggruppamento prima dei caratteri di riempimento (se presenti). I separatori di gruppo non saranno applicati ai caratteri di riempimento, anche se il carattere di riempimento è un numero.
Per garantire l'allineamento, ogni carattere che, nella stringa formattata, appare prima o dopo il numero, tipo il simbolo della moneta o il segno, viene riempito con gli spazi necessari affinché la corrispondente stringa risultante da un valore positivo o negativo abbia la medesima lunghezza.
Precisione di destra .
Un punto seguito da un numero di cifre (p) dopo il carattere decimale. Se il valore di p è 0 (zero), il carattere decimale e le cifre alla sua destra saranno omesse. Se non vi è indicazione della precisione a destra, il default sarà preso della impostazioni locali. L'importo sarà arrontondato alle cifre decimali richieste prima di essere formattato.
Caratteri di conversione .
Il numero sarà formattato in base alle impostazioni internazionali locali (es. le impostazioni locali USA: USD 1,234.56).
Il numero sarà formattato in base alle locali impostazioni nazionali di moneta (es. per de_DE: DM1.234,56).
Restituisce il carattere %.
Nota: La categoria LC_MONETARY delle impostazioni locali influisce sul comportamento di questa funzione. Utilizzare setlocale() per impostare il default appropriato prima di utilizzare questa funzione.
I caratteri prima e dopo la stringa di formattazione saranno restituiti immutati.
Esempio 1. Esempio di uso di money_format() Per illustrare il funzionamento della funzione utilizzeremo diversi formati di impostazioni locali.
|
Vedere anche setlocale(), number_format(),sprintf(), printf() e sscanf().
La funzione nl_langinfo() viene utilizzata per accedere agli elementi delle impostazioni locali. Diversamente da localeconv(), che restituisce tutti gli elementi, nl_langinfo() permette di scegliere l'elemento specifico.
Se il parametro item non è valido, la funzione restituisce FALSE.
Il parametro item può essere un numero intero od il nome della costante indicante l'elemento. Di seguito viene riportata la lista dei nomi per item con le rispettive descrizioni. Alcune di quest costanti possono non essere definite in alcune impostazioni locali.
Tabella 1. Costanti di nl_langinfo
Costante | Descrizione |
---|---|
Costanti per la categoria LC_TIME | |
ABDAY_(1-7) | Nome abbreviato dell'n-esimo giorno della settimana. |
DAY_(1-7) | Nome dell'n-esimo giorno della settimana (DAY_1 = domenica). |
ABMON_(1-12) | Nome abbreviato dell'n-esimo mese dell'anno. |
MON_(1-12) | Nome dell'n-esimo mese dell'anno. |
AM_STR | Stringa per ante meridiano. |
PM_STR | Stringa per pomeridiano. |
D_T_FMT | Stringa di formato che può essere usata con strftime() per rappresentare la data e l'ora. |
D_FMT | Stringa di formato che può essere usata con strftime() per rappresentare la data. |
T_FMT | Stringa di formato che può essere usata con strftime() per rappresentare l'ora. |
T_FMT_AMPM | Stringa di formato che può essere usata con strftime() per rappresentare la data e l'ora nel formato a 12 ore con ante/post meridiano. |
ERA | Era alternativa. |
ERA_YEAR | Formato dell'anno nell'era alternativa. |
ERA_D_T_FMT | Formato di data e ora nell'era alternativa (la stringa può essere usata con strftime()). |
ERA_D_FMT | Formato della data nell'era alternativa (la stringa può essere usata con strftime()). |
ERA_T_FMT | Formato dell'ora nell'era alternativa (la stringa può essere usata con strftime()). |
Costanti per la categoria LC_MONETARY | |
INT_CURR_SYMBOL | Simbolo internazionale della divisa. |
CURRENCY_SYMBOL | Simobolo locale della moneta. |
CRNCYSTR | Stesso valore di CURRENCY_SYMBOL. |
MON_DECIMAL_POINT | Carattere separatore delle cifre decimali. |
MON_THOUSANDS_SEP | Separatore delle migliaia (gruppi di tre cifre). |
MON_GROUPING | Come l'elemento di raggruppamento. |
POSITIVE_SIGN | Segno per i valori positivi. |
NEGATIVE_SIGN | Segno per i valori negativi. |
INT_FRAC_DIGITS | Numero di cifre frazionarie internazionale. |
FRAC_DIGITS | Numero di cifre frazionarie locale. |
P_CS_PRECEDES | Resituisce 1 se CURRENCY_SYMBOL precede un valore positivo. |
P_SEP_BY_SPACE | Resituisce 1 se uno spazio separa CURRENCY_SYMBOL da un valore positivo. |
N_CS_PRECEDES | Resituisce 1 se CURRENCY_SYMBOL precede un valore negativo. |
N_SEP_BY_SPACE | Resituisce 1 se uno spazio separa CURRENCY_SYMBOL da un valore negativo. |
P_SIGN_POSN |
|
N_SIGN_POSN | |
Costanti per la categoria LC_NUMERIC | |
DECIMAL_POINT | Carattere separatore delle cifre decimali. |
RADIXCHAR | Come DECIMAL_POINT. |
THOUSANDS_SEP | Separatore delle migliaia (gruppi di tre cifre). |
THOUSEP | Come THOUSANDS_SEP. |
GROUPING | |
Costanti per la categoria LC_MESSAGES | |
YESEXPR | Stringa regex per il riconoscimento di 'si'. |
NOEXPR | Stringa regex per il riconoscimento di 'no'. |
YESSTR | Testo da visualizzare per 'si'. |
NOSTR | Testo da visualizzare per 'no'. |
Costanti per la categoria LC_CTYPE | |
CODESET | Restituisce una stringa con il nome della codifica dei caratteri. |
Nota: Questa funzione non è implementata su piattaforme Windows
Vedere anche setlocale() e localeconv().
(PHP 3, PHP 4, PHP 5)
nl2br -- Inserisce il tag HTML di 'a capo' prima di tutti i caratteri di 'a capo' della stringaRestituisce la stringa string con '<br />' inserito prima di tutti i newline.
Nota: A partire dal PHP 4.0.5, nl2br() è conforme a XHTML. Tutte le versioni precedenti alla 4.0.5 restituiscono la string con '<br>' invece di '<br />' inserito prima degli 'a capo'.
Vedere anche htmlspecialchars(), htmlentities(), wordwrap() e str_replace().
La funzione number_format() restituisce una versione formattata di number. Questa funzione accetta uno, due, o quattro parametri (non tre).
Se si specifica soltanto un parametro, il number sarà formattato senza decimali, ma con la virgola (",") per suddividere le migliaia.
Se sono specdificati due parametri, il number sarà formattato con tante cifre decimali quanto indicato in decimals, precedute dal punto ("."), e con la virgola (",") come separatore delle migliaia.
Se sono indicati tutti i quattro parametri, il number sarà formattato con decimals cifre decimali, identificate dal carattere dec_point anziché dal punto (".") e con thousands_sep, invece della virgola (",") come separatore delle migliaia.
Sarà utilizzato solo il primo carattere di thousands_sep. Ad esempio, se si indica foo come thousands_sep per il numero 1000, la funzione number_format() restituirà 1f000.
Esempio 1. Esempio di uso di number_format() Ad esempio, la notazione francese solitamente utilizza due decimali, la virgola (',') come separatore decimale, e lo spazio (' ') come separatore delle migliaia. Questo può essere ottenuto con:
|
Restituisce il valore ASCII del primo carattere di string. Questa è la funzione complementare di chr().
Qui si può reperire la tabella ASCII: http://www.asciitable.com.
Vedere anche chr().
Suddivide la stringa str come se fosse una stringa di query passata via URL ed imposta le variabili con visibilità locale. Se si indica il secondo parametro arr, la variabili sono memorizzate come elementi della matrice arr.
Nota: Il supporto per il secondo parametro, opzionale, è stato aggiunto in PHP 4.0.3.
Nota: Per avere la QUERY_STRING corrente occorre utilizzare la variabile $_SERVER['QUERY_STRING']. Inoltre è opportuno leggere la sezione sulle variabili esterne al PHP.
Nota: L'impostazione magic_quotes_gpc influisce sull'output di questa funzione, poichè parse_str() utilizza lo stesso meccanismo che usa il PHP per compilare le variabili $_GET, $_POST, ecc.
Esempio 1. Esempio di uso di parse_str()
|
Vedere anche parse_url(), pathinfo(), get_magic_quotes_gpc() e urldecode().
Visualizza arg. Restituisce sempre 1,
In realtà print() non è una funzione (è un costrutto del linguaggio) pertanto non sono richieste le parentesi per la lista degli argomenti.
Esempio 1. Esempio di uso di print()
|
Per breve discussione tra print() e echo(), vedere la pagina di FAQTs Knowledge Base Article: http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40
Nota: Poichè questo è un costrutto del linguaggio e non una funzione, non può essere chiamato con le variabili funzione
Produce un output formattato secondo le specifiche del parametro format, che viene descritto nella documentazione di sprintf().
Restituisce la lunghezza della stringa visualizzata.
Vedere anche print(), sprintf(), vprintf(), sscanf(), fscanf() e flush().
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
quoted_printable_decode -- Converte una stringa 'quoted-printable' in una stringa a 8 bitQuesta funzione restituisce una stringa a 8 bit corrispondente alla codifica della stringa 'quoted-printable' ( in base a RFC2045, sezione 6.7, e non RFC2821, sezione 4.5.2, punti addizionali non sono rimossi dall'inizio della linea). Questa funzione è simile a imap_qprint(), tranne che quest'ultima richiede il modulo IMAP per essere utilizzata.
Restituisce una versione di str con il carattere backslash (\) davanti ai seguenti caratteri:
. \ + * ? [ ^ ] ( $ ) |
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Vedere anche addslashes(), htmlentities(), htmlspecialchars(), nl2br() e stripslashes().
Nota: Il secondo parametro è stato aggiunto nella versione 4.1.0 di PHP.
Questa funzione restituisce la stringa str a cui sono stati rimossi gli spazi finali. Senza la specifica del secondo parametro rtrim() rimuoverà i seguenti caratteri:
" " (ASCII 32 (0x20)), spazio ordinario.
"\t" (ASCII 9 (0x09)), tab.
"\n" (ASCII 10 (0x0A)), newline (line feed).
"\r" (ASCII 13 (0x0D)), carriage return.
"\0" (ASCII 0 (0x00)), il byte NUL.
"\x0B" (ASCII 11 (0x0B)), il tab verticale.
Si può anche specificare i caratteri che si desidera rimuovere, indicandoli nel parametro charlist. Quest'ultimo è costituito da un semplice elenco di caratteri da rimuovere. Con .. si può specificare un range di caratteri.
Esempio 1. Esempio di uso di rtrim()
|
Il parametro category è una costante (o stringa) che indica la categoria di parametri coinvolta nelle impostazioni locali:
LC_ALL la somma di tutte le seguenti categorie
LC_COLLATE per i confronti di stringhe, vedere strcoll()
LC_CTYPE per la classificazione dei caratteri e le conversioni, ad esempio strtoupper()
LC_MONETARY per localeconv()
LC_NUMERIC per il separatore decimale (vedere anche localeconv())
LC_TIMEper la formattazione di data e orario con strftime()
Nota: Dalla versione 4.2.0 di PHP il passaggio di category come stringa è deprecato; piuttosto utilizzare le precedenti costanti. Passare quelle costanti come stringa (all'interno di apici) darà come risultato un warning.
Se il parametro locale è NULL oppure una stringa vuota "", i nomi locali saranno impostati dai valori delle omonime variabili d'ambiente, oppure da "LANG".
Se il parametro locale vale "0", le impostazioni localizzate non vengono toccate, ma vengono restituiti i valori correnti.
Se il parametro locale è una matrice oppure è seguito da parametri addizionali, allora si tenterà di impostare ciascun elemento, o parametro, fino a quando non si ha successo. Questo è utile se l'impostazione locale è nota sotto differenti nomi in sistemi differenti oppure per prevedere più casistiche qualora alcune non fossero disponibili.
Nota: Il passaggio di molteplici impostazioni non è possibile prima di PHP 4.3.0.
La funzione restituisce le nuove impostazioni locali, oppure FALSE se la funzionalità di localizzazione non è implementata sul sistema, se l'impostazione richiesta non esiste, oppure se il nome della categoria non è valida. Un nome di categoria non valido genera anche un warning. I nomi delle categoria possono essere trovati nella RFC 1766 e ISO 639. Differenti sistemi hanno differenti schemi di denominazione delle impostazioni locali.
Nota: Il valore restituito da setlocale() dipende dal sistema su cui gira il PHP. La funzione restituisce fedelmente quello che la funzione di sistema restituisce.
Suggerimento: Gli utenti di Windows potranno trovare informazioni utili per il parametro locale sul sito MSDN di Microsoft. Le stringhe di linguaggio supportate possono essere trovate in http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_language_strings.asp e le stringhe identificanti i paesi/regioni alla pagina http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_country_strings.asp. I sistemi Windows supportano la codifica a tre lettere ISO 3166-Alpha-3 per identificare i paesi/regioni ISO 3166-Alpha-3, tale codifica può essere reperita nel sito . .
Esempio 1. Esempi di uso di setlocale()
|
Esempio 2. Esempio di uso di setlocale() perWindows
|
Calcola l'hash sha1 di filename usando il US Secure Hash Algorithm 1, e restituisce l'hash. L'hash è un numero esadecimale di 40 caratteri.
Il nome del file
Quando è impostato a TRUE, l'hash sha1 è restituito in formato binario con una lunghezza di 20 caratteri. Per default vale FALSE.
Calcola l'hash sha1 di str usando il US Secure Hash Algorithm 1, e restituisce l'hash. L'hash è un numero esadecimale di 40 caratteri. Se il parametro opzionale raw_output è impostato a TRUE, allora l'hash sha1 è restituito in formato binario con una lunghezza di 20 caratteri.
Nota: Il parametro opzionale raw_output è stato aggiunto in PHP 5.0.0 ed ha come default FALSE
Vedere anche sha1_file(), crc32() e md5()
Questa funzione calcola la similitudine tra due stringhe come descritto in Oliver [1993]. Attenzione che questa implementazione non utilizza lo stack come nel psuedo codice di Oliver, ma utilizza chiamate ricorsive che possono o non possono velocizzare l'intero processo. Occorre anche rilevare che la complessità di questo algoritmo è O(N**3) dove N è la lunghezza della stringa più lunga.
Passando per riferimento il terzo argomento, similar_text() la funzione calcolerà la similitudine in percentuale. La funzione restituisce il numero di caratteri corrispondenti in entrambe le stringhe.
Vedere anche levenshtein() e soundex().
Calcola la chiave soundex di str.
Le chiavi soundex hanno la caratteristica di essere simili per parole con pronuncia similare, e pertanto possono essere utilizzate per semplificare le ricerche in archivi nei casi in cui si conosce la pronuncia ma non la sillabazione. Questa funzione soundex restituisce una stringa di 4 caratteri di cui il primo è una lettera.
Questa particolare funzione soundex è stata descritta da Donald Knuth in "The Art Of Computer Programming, vol. 3: Sorting And Searching", Addison-Wesley (1973), pp. 391-392.
Esempio 1. Esempio di uso di Soundex
|
Vedere anche levenshtein(), metaphone() e similar_text().
La funzione restituisce una stringa formattata in base al parametro format.
La stringa di formato è composta da 0 o più direttive: i caratteri ordinari (escluso il %) sono copiati direttamente nel risultato, mentre le specifiche di conversione, scaricano il proprio parametro. Queste note si applicano alle funzioni fprintf(), sprintf() e printf().
Ciascun parametro di conversione consiste nel segno percento (%), seguito da uno più dei seguenti elementi nell'ordine si ha:
Un parametro opzionale di specifica del segno che forza la presenza del segno (- oppure +) in caso di numero. Per default, si usa soltanto il segno - se il numero è negativo. Questo parametro forza i numeri positiva ad avere il segno +, ed è stato aggiunto in PHP 4.3.0.
Un parametro opzionale per la specifica del riempimento che indica quale carattere sarà utilizzato per completare la stringa risultante in modo da raggiungere la dimensione richiesta. Questo può essere uno spazio oppure uno 0 (il carattere zero). Per default si completa con spazi. Un carattere di riempimento alternativo può essere indicato anteponendo a questo l'apice singolo ('). Vedere gli esempi seguenti.
Un parametro opzionale per la specifica dell'allineamento che indica se la stringa risultante debba essere giustificata a destra o a sinistra. Per default le stringhe sono giustificate a destra; il carattere - forza la giustificazione a sinistra.
Un parametro numerico opzionale per la specifica della dimensione che indica di quanti caratteri (come minimo) debba essere lunga la stringa.
Un parametro opzionale per indicare la precisione per indicare quante cifre decimali debbano essere visualizzate per i numeri in virgola mobile. Quando si usa questo parametro in una stringa si impone come una sorta di punto di cutoff, esso imposta un limite alla lunghezza della stringa.
Una specifica di tipo che indica il tipo di dati dell'argomento. I possibili tipi sono:
% - il carattere percento. Nessun argomento è richiesto. |
b - l'argomento è trattato come un intero e sarà presentato come numero binario. |
c - l'argomento è trattato come un intero e sarà presentato come carattere ASCII del valore corrispondente. |
d - l'argomento è trattato come un intero e sarà presentato come un numero decimale con segno. |
e - l'argomento è reso con notazione scientifica (ad esempio 1.2e+2). |
u - l'argomento è trattato come un intero e sarà presentato come un numero decimale senza segno. |
f - l'argomento è trattato come un float e sarà presentato come un numero in virgola mobile (influenzato dalle impostazioni locali). |
F - l'argomento è trattato come un numero float, e sarà presentato come un numero in virgola mobile (non influenzato dalle impostazioni locali). Disponibile da PHP 4.3.10 e PHP 5.0.3. |
o - l'argomento è trattato come un intero e sarà presentato come un numero ottale. |
s - l'argomento sarà trattato e presentato come una stringa. |
x - l'argomento sarà trattato come un intero e presentato in forma esadecimale (con le lettere in minuscolo). |
X - l'argomento è trattato come un intero e sarà presentato come un numero esadecimale (con le lettere maiuscole). |
A partire dal PHP 4.0.6 la stringa di formato supporta lo scambio dei parametri. Eccone un esempio:
Vedere anche printf(), sscanf(), fscanf(), vsprintf() e number_format().
Esempio 5. Esempi di uso di printf()
L'output di questo programma sarà:
|
Esempio 6. printf(): specifiche di stringa
L'output di questo programma sarà:
|
La funzione sscanf() è la versione di input di printf(). sscanf() legge dalla stringa str e ne interpreta il contenuto basandosi sul parametro format, che viene descritto nella documentazione di sprintf(). Se vengono passati soltanto due parametri, i valori ricavati sono restituiti in una matrice. Altrimenti, se viene fornito il terzo parametro, la funzione restituire il numero dei valori assegnati. Il terzo parametro deve essere passato per riferimento.
Qualsiasi tipo di spazio nella stringa di formato identifica il corrispondente spazio nella stringa di input. Ciò significa che anche i tab \t nella stringa di formato possono identificare un carattere di spazio nella stringa di input.
Esempio 1. Esempio di uso di sscanf()
|
Questa funzione restituisce una stringa od una matrice con tutte le occorrenze di search in subject (non distinguendo tra maiuscole e minuscole) sostituite con il valore replace Se non occorrono particolari regole di sostituzione si dovrebbe utilizzare questa funzione anziché eregi_replace() o preg_replace() con il parametro i.
Se il parametro subject è una matrice, allora la ricerca e la sostituzione viene eseguita su ogni elemento di subject, ed il valore restituito è pure quello una matrice.
Se search e replace sono matrici, allora str_ireplace() prende i valori da ciascuna matrice e li utilizza per fare la ricerca e la sostituzione in subject. Se replace ha meno valori di search, allora si utilizza una stringa vuota per sostituire i valori mancanti. Se search è una matrice e replace è una stringa; allora questa stringa viene utilizzata per sostituire ogni valore di search.
Questa funzione è sicura con i dati binari.
Nota: Dal PHP 5.0.0 il numero dei testi trovati e sostituiti sarà restituito in count che deve essere passato per riferimento. Prima del PHP 5.0.0 questo parametro non è disponibile.
Vedere anche: str_replace(), ereg_replace(), preg_replace() e strtr().
(PHP 4 >= 4.0.1, PHP 5)
str_pad -- Riempie una stringa con un'altra stringa portando la prima ad una lunghezza pre-determinataQuesta funzione restituisce la stringa input riempita per una data lunghezza a sinistra, a destra, o in entrambi i lati. Se il parametro opzionale pad_string non viene passato, l' input viene completato con spazi, altrimenti viene completato con i caratteri di pad_string fino al limite.
Il parametro pad_type, opzionale, può valere STR_PAD_RIGHT, STR_PAD_LEFT, oppure STR_PAD_BOTH. Se non si indica pad_type lo si assume pari a STR_PAD_RIGHT.
Se il valore di pad_length è negativo oppure minore della stringa di input, non si ha nessun completamento.
Esempio 1. Esempio di uso di str_pad()
|
Nota: Il parametro pad_string può essere troncato se il numero di caratteri necessari al completamento non può essere diviso per la lunghezza di pad_string.
Restituisce il parametro input_str ripetuto tante volte quanto indicato in multiplier. multiplier deve essere maggiore o uguale a 0. Se multiplier è impostato a zero, la funzione restituisce una stringa vuota.
Vedere anche for, str_pad() e substr_count().
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
str_replace -- Sostituisce tutte le occorrenze della stringa cercata con la stringa di sostituzioneQuesta funzione restituisce una stringa, od una matrice, con tutte le occorrenze di search nella stringa subject sostituite con il valore del parametro replace. Se non occorrono particolari capacità di sostituzione (tipo le espressioni regolari), si dovrebbe utilizzare questa funzione invece di ereg_replace() o preg_replace().
Dal PHP 4.0.5, ogni parametro di str_replace() può essere una matrice.
Avvertimento |
Nelle versioni di PHP antecedenti la 4.3.3 esisteva un errore quando si utilizzano le matrici per search e replace che faceva ignorare gli indici vuoti di search avanzando il puntatore interno di replace, questo è stato corretto dal PHP 4.3.3, ogni script che si basava su questo errore, per potere simulare il comportamento originale, dovrebbe rimuovere gli elementi vuoti prima di richiamare questa funzione. |
Se subject è una matrice, allora la ricerca e la sostituzione sono eseguite su ogni elemento di subject, ed il valore restituito è pure una matrice.
Se search e replace sono matrici, allora str_replace() prende i valori da ciascuna matrice e li usa per svolgere la ricerca e la sostituzione in subject. Se replace ha meno valori di search, allora si utilizzeranno delle stringhe vuote per completare i rimanenti valori da sostituire. Se search è una matrice e replace è una stringa, allora questa stringa di sostituzione sarà utilizzata per ogni valore di search. Il contrario non avrebbe senso.
Esempio 1. Esempi di uso di str_replace()
|
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Nota: Dal PHP 5.0.0 il numero di stringhe trovate e e sostituite, sarà restituito nel parametro, passato per riferimento, count. Nelle versioni antecedenti al PHP 5.0.0 questo parametro non è disponibile.
Vedere anche: str_ireplace(), substr_replace(), ereg_replace(), preg_replace() e strtr().
Questa funzione esegue la codifica ROT13 della stringa str e restituisce la stringa risultante. La codifica ROT, semplicemente, sposta ogni lettera di 13 posizioni nell'alfabeto, e lascia immutati i caratteri non alfabetici. La codifica e la decodifica sono eseguiti dalla stessa funzione, passando alla funzione una stringa codificata, questa restituirà la stringa originaria.
Nota: Il comportamento di questa funzione era errato fino al PHP 4.3.0. nelle versioni precedenti a questa, veniva modificato anche il parametro str se veniva passato per riferimento.
str_shuffle() mischia una stringa. Viene generata una di tute le possibili permutazioni.
Converte una stringa in una matrice. Se viene passato il parametro opzionale split_length, la matrice restituita sarà composta da segmenti, ciascuno della lunghezza di split_length caratteri, in caso contrario ciascun segmento sarà lungo un carattere.
FALSE è restituito se split_length è minore di 1. Se split_length supera la lunghezza di string, sarà restituita l'intera stringa come primo (ed unico) elemento della matrice.
Esempio 1. Esempi di uso di str_split()
L'output potrà essere:
|
Vedere anche: chunk_split(), preg_split(), split(), count_chars(), str_word_count() e for.
(PHP 4 >= 4.3.0, PHP 5)
str_word_count -- Restituisce informazioni sulle parole utilizzate in una stringaConta il numero di parole presenti in string. Se non viene indicato il parametro opzionale format, allora la funzione restituirà un intero indicante il numero di parole trovate. Nel caso in cui sia specificato format, la funzione restituisce una matrice il cui contenuto dipende dal parametro format. I possibili valori per format ed i rispettivi output sono elencati di seguito.
Per gli scopi di questa funzione 'parola' è definita come testo dipendente dalle impostazioni locali, contenente caratteri alfabetici, che può contenere, ma non cominciare, con i caratteri "'" and "-".
La stringa
Indica il tipo di valore restituito dalla funzione. Le attuali impostazioni ammesse per il parametro sono:
0 - restituisce il numero di parole trovate
1 - restituisce una matrice contenente tutte le parole trovate all'interno di string.
2 - restituisce una matrice associativa, in cui le chiavi sono la posizione numerica della parola in string ed il valore è la parola stessa.
Lista di caratteri addizionali da considerare come 'parole'
Esempio 1. Esempio di uso di str_word_count()
Il precedente esempio visualizzerà:
|
(PHP 3 >= 3.0.2, PHP 4, PHP 5)
strcasecmp -- Confronto non sensibile alle maiuscole e sicuro con i dati binariRestituisce < 0 se str1 è minore di str2; > 0 se str1 è maggiore di str2, e 0 se sono uguali.
Vedere anche ereg(), strcmp(), substr(), stristr(), strncasecmp() e strstr().
Restituisce < 0 se str1 è minore di str2; > 0 se str1 è maggiore di str2, e 0 se sono uguali.
Attenzione: il confronto tiene conto delle lettere maiuscole e minuscole.
Vedere anche ereg(), strcasecmp(), substr(), stristr(), strncasecmp(), strncmp() e strstr().
Restituisce < 0 se str1 è minore di str2; > 0 se str1 è maggiore di str2, e 0 se sono uguali. strcoll() utilizza le impostazioni locali per il confronto. Se le impostazioni locali sono conformi al C o a POSIX, allora la funzione è equivalente a strcmp().
Attenzione. questo confronto distingue tra maiuscole e minuscole, e, diversamente da strcmp() non è affidabile con i dati binari.
Nota: strcoll() è stato aggiunto in PHP 4.0.5, ma sui sistemi win32 non è stato abilitato fino alla versione 4.2.3.
Vedere anche ereg(), strcmp(), strcasecmp(), substr(), stristr(), strncasecmp(), strncmp(), strstr() e setlocale().
(PHP 3 >= 3.0.3, PHP 4, PHP 5)
strcspn -- Trova la lunghezza del segmento iniziale che non soddisfa una mascheraRestituisce la lunghezza del segmento iniziale di str1 che non contiene nessuno dei caratteri specificati in str2.
Dal PHP 4.3.0, strcspn() accetta due parametri interi, opzionali, che possono essere utilizzati per definire la posizione di inizio e la lunghezza della stringa da esaminare.
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Vedere anche strspn().
Questa funzione tenga di restituire una stringa priva dei tag HTML e PHP partendo dalla stringa str. La funzione utilizza la stessa macchina a stati di rimozione dei tag utilizzata per la funzione fgetss().
Si può utilizzare il secondo parametro, opzionale, per indicare quale tag ignorare.
Nota: allowable_tags è stato aggiunto in PHP 3.0.13 e PHP 4.0b3.
Dal PHP 4.3.0, sono rimossi anche i commenti HTML. Questo comportamento è da programma e non può essere modificato tramite allowable_tags.
Avvertimento |
Poiché strip_tags() non valida il testo HTML, tag parziali, o interrotti possono portare alla rimozione di più testo di quanto atteso. |
Avvertimento |
Questa funzione non modifica alcun attributo sui tag che sono abilitati tramite allowable_tags, incluso lo style e l'attributo onmouseover che possono essere sfruttati da utenti malevoli quando pubblicano testi che saranno visualizzati da altri utenti. |
La funzione strip_tags() è sicura con i contenuti binari dal PHP 5.0.0
Vedere anche htmlspecialchars().
Rimuove i backslash da una stringa. Riconosce i caratteri C \n, \r ..., le rappresentazioni ottali e esadecimali.
Vedere anche addcslashes().
(PHP 5)
stripos -- Trova la prima occorrenza in una stringa senza distinzione tra maiuscole e minuscoleRestituisce la posizione numerica della prima occorrenza di needle nella stringa haystack. Differentemente da strpos(), stripos() non distingue tra maiuscole e minuscole.
Occorre rilevare che needle può essere una stringa di uno o più caratteri.
Se needle non viene trovato, stripos() restituirà boolean FALSE.
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
Esempio 1. Esempi di uso di stripos()
|
Se needle non è una stringa, sarà convertito in un intero e utilizzato come valore ordinale di un carattere.
Il parametro opzionale offset permette di indicare da quale carattere di haystack iniziare la ricerca. La posizione restituita sarà relativa all'inizio di haystack.
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Vedere anche strpos(), strrpos(), strrchr(), substr(), stristr(), strstr(), strripos() e str_ireplace().
Rimuove i backslash da una stringa. (\' diventa ' e così via.) I doppi backslash (\\) sono ridotti ad un singolo backslash (\).
Un esempio di uso di stripslashes() è dato dall'opzione PHP magic_quotes_gpc che, quando è impostata a on (come è per default), e non siinseriscono questi dati in una procedura (tipo in un database) che richiede il carattere di escape. Ad esempio, se si visualizza dati da un form HTML.
Nota: La funzione stripslashes() non è ricorsiva Se si desidera utilizzare questa funzione su una matrice multi-dimensionale, occorre utilizzare una funzione ricorsiva.
Esempio 2. Esempio di utilizzo di stripslashes() su una matrice
Il precedente esempio visualizzerà:
|
Per maggiori dettagli su "magic quotes", vedere get_magic_quotes_gpc().
Vedere anche addslashes() e get_magic_quotes_gpc().
Restituisce il contenuto di haystack dalla prima occorrenza di needle fino alla fine. needle e haystack sono esaminati senza distinguere tra lettere maiuscole e minuscole.
Se needle non viene trovato, la funzione restituisce FALSE.
Se needle non è una stringa, viene convertito in un intero e si utilizza il valore ordinale del carattere.
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Restituisce la lunghezza della stringa string.
Vedere anche count() e mb_strlen().
(PHP 4, PHP 5)
strnatcasecmp -- Versione insensibile alle maiuscole/minuscole di confronto tra stringhe tramite l'algoritmo dell"ordine naturale"Questa funzione implementa un algoritmo di confronto che ordina le stringhe alfa-numeriche nel modo in cui lo farebbe un uomo. Il comportamento di questa funzione è simile a strnatcmp(), tranne che il confronto non distingue tra le lettere maiuscole e minuscole. Per maggiori informazioni vedere: Martin Pool's Natural Order String Comparison page.
Al pari delle altre funzioni di confronto tra stringhe, questa restituisce < 0 se str1 è minore di str2; > 0 se str1 è maggiore di str2, e 0 se sono uguali.
Vedere anche ereg(), strcasecmp(), substr(), stristr(), strcmp(), strncmp(), strncasecmp(), strnatcmp() e strstr().
Questa funzione implementa un algoritmo di confronto che ordina le stringhe alfa-numeriche nel modo con cui lo avrebbe fatto un uomo, questo è detto "ordinamento naturale". Un esempio della differenza tra questo algoritmo e quello solito dei computer (utilizzato da strcmp()) è illustrato di seguito:
<?php $arr1 = $arr2 = array("img12.png", "img10.png", "img2.png", "img1.png"); echo "Standard string comparison\n"; usort($arr1, "strcmp"); print_r($arr1); echo "\nNatural order string comparison\n"; usort($arr2, "strnatcmp"); print_r($arr2); ?> |
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 ) |
Al pari delle altre funzioni di confronto tra stringhe, questa restituisce < 0 se str1 è minore di str2; > 0 se str1 è maggiore di str2, e 0 se sono uguali.
Nota questo confronto distingue tra lettere maiuscole e minuscole.
Vedere anche ereg(), strcasecmp(), substr(), stristr(), strcmp(), strncmp(), strncasecmp(), strnatcasecmp(), strstr(), natsort() e natcasesort().
(PHP 4 >= 4.0.2, PHP 5)
strncasecmp -- Confronto sicuro con i testi binari, insensibile alle lettere maiuscole/minuscole sui primi n caratteriQuesta funzione è simile a strcasecmp(), con la differenza che si può indicare il numero dei caratteri (len) per ciascuna stringa che possono essere utilizzati per il confronto.
Restituisce < 0 if str1 se è minore di str2; > 0 se str1 è maggiore di str2, e 0 se sono uguali.
Vedere anche ereg(), strcasecmp(), strcmp(), substr(), stristr() e strstr().
Questa funzione è simile a strcmp(), con la differenza che si può specificare il limite superiore del numero di caratteri (len) per ciascuna stringa, da utilizzare per il confronto.
Restituisce < 0 se str1 è minore di str2; > 0 se str1 è maggiore di str2, e 0 se sono uguali.
Nota: questo confronto distingue tra lettere minuscole e maiuscole.
Vedere anche ereg(), strncasecmp(), strcasecmp(), substr(), stristr(), strcmp() e strstr().
strpbrk() cerca nella stringa haystack i caratteri indicati in char_list, e restituisce una stringa a partire dal carattere trovato (oppure FALSE se non ve ne sono).
Nota: char_list distingue tra maiuscole e minuscole.
Restituisce la posizione numerica della prima occorrenza di needle nella stringa haystack. Differentemente rispetto a strrpos(), questa funzione considera tutta la stringa needle, e, quindi, cercherà tutta la stringa.
Se needle non viene trovato strpos() restituirà boolean FALSE.
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Esempio 1. Esempio di uso di strpos()
|
Se needle non è una stringa, viene convertito in un intero e utilizzato come valore ordinale di un carattere.
Il parametro opzionale offset permette di indicare da quale carattere in haystack iniziare la ricerca. La posizione restituita è, comunque, relativa all'inizio di haystack.
Vedere anche strrpos(), stripos(), strripos(), strrchr(), substr(), stristr() e strstr().
Questa funzione restituisce la porzione di haystack che inizia dall'ultima occorrenza di needle e finisce al termine di haystack.
Restituisce FALSE se needle non viene trovato.
Se needle contiene più di un carattere, in PHP 4 si utilizza solo il primo. Questo comportamento è differente rispetto a strchr().
Se needle non è una stringa, viene convertito in un intero e utilizzato come valore ordinale di un carattere.
strrchr() è affidabile con i dati binari dal PHP 4.3.0
(PHP 5)
strripos -- Trova la posizione dell'ultima occorrenza di una stringa in un'altra indipendentemente dalle lettere minuscole/maiusoleRestituisce la posizione numerica dell'ultima occorrenza di needle nella stringa haystack. Differentemente da strrpos(), strripos() non distingue tra lettere maiuscole minuscole. Attenzione che le posizioni della stringa partono da 0 e non da 1.
Notare anche che needle può essere una stringa di uno o più caratteri.
Se needle non è reperito, la funzione restituisce FALSE.
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
Esempio 1. Un semplice esempio di strripos()
Output:
|
Il parametro offset può indicare la posizione da cui cominciare la ricerca nella stringa.
Offset negativi inizieranno la ricerca alla posizione offset dall'inizio della stringa.
Vedere anche: strrpos(), strrchr(), substr(), stripos() e stristr().
(PHP 3, PHP 4, PHP 5)
strrpos -- Trova la posizione dell'ultima occorrenza di un carattere in una stringaRestituisce la posizione numerica dell'ultima occorrenza di needle nella stringa haystack. Fare attenzione che needle, in PHP 4, può essere solo un singolo carattere. Se si passa una stringa, verrà utilizzato solo il primo carattere.
Se needle non viene trovato, la funzione restituisce FALSE.
Si può facilmente confondere i valori restituiti "per carattere alla posizione 0" e per "carattere non trovato". Ecco come rilevare la differenza:
<?php // in PHP 4.0b3 e successivi: $pos = strrpos($mystring, "b"); if ($pos === false) { // note: three equal signs // not found... } // nelle versioni precedenti alla 4.0b3: $pos = strrpos($mystring, "b"); if (is_bool($pos) && !$pos) { // not found... } ?> |
Se needle non è una stringa, viene convertito in un intero, e usato come valore ordinale di un carattere.
Nota: Dal PHP 5.0.0 offset può essere indicato per indicare di iniziare la ricerca nella stringa da una posizione di caratteri arbitraria. Valori negativi fermeranno la ricerca ad un punto arbitrario prima della fine della stringa.
Nota: Il parametro needle può essere una stringa di uno o più caratteri a partire dal PHP 5.0.0.
Vedere anche: strpos(), strripos(), strrchr(), substr(), stristr() e strstr().
(PHP 3 >= 3.0.3, PHP 4, PHP 5)
strspn -- Trova la lunghezza di un testo che corrisponde alla maschera dataRestituisce la lunghezza di un segmento di str1 che contiene completamente i caratteri presenti in str2.
Il seguente codice:
assegnerà 2 a $var, poichè la stringa "42" è il più lungo segmento contenente i caratteri da "1234567890".Dal PHP 4.3.0, strspn() accetta altri due parametri interi opzionali: start che può essere usato per indicare la posizione di inizio da cui cercare, e length per indicare la lunghezza della stringa da esaminare.
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Vedere anche strcspn().
Restituisce la parte della stringa haystack dalla prima occorrenza di needle fino alla fine di haystack.
Se non si trova needle, restituisce FALSE.
Se needle non è una stringa, il parametro viene convertito in un intero e utilizzato come valore ordinale di un carattere.
Nota: Questa funzione distingue tra maiuscole e minuscole. Per una versione che non abbia questa distinzione guardare stristr().
Nota: Se si desidera soltanto determinare se una particolare stringa è presente in haystack, utilizzare la più veloce e meno costosa in termini di memoria strpos().
strstr() è sicura con i dati binari dal PHP 4.3.0
Vedere anche: ereg(), preg_match(), stristr(), strpos(), strrchr() e substr().
strtok() suddivide la stringa(str) in piccole stringhe (tokens), in cui ciascun token è delimitato dal carattere indicato in token. Perciò, se si ha la stringa "This is an example string" la si può dividere nelle singole parole utilizzando come separatore lo spazio.
Soltanto la prima chiamata a strtok() utilizza il parametro stringa. Ogni chiamata successiva richiede solo il carattere da utilizzare, poichè la funzione tiene traccia di dove è arrivata nella stringa corrente. Per ripartire da capo o iniziare con una nuova stringa ri-chiamare strtok() con il parametro stringa. Nota: si possono mettere più caratteri come separatori di stringhe. Il testo iniziale verrà suddiviso quando viene trovato uno qualsiasi di questi caratteri. Attenzione che soltanto la prima chiamata di strtok userà l'argomento stringa.
Il comportamento su segmenti vuoti è cambiato dal PHP 4.1.0. La vecchia versione restituiva una stringa vuota, mentre la nuova, più correttamente, salta quella parte di stringa:
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. |
La funzione restituisce la stringa string con tutti i caratteri alfabetici convertiti in minuscolo.
Nota: i caratteri 'alfabetici' sono determinati in base alle impostazioni locali. Ciò significa, ad esempio, che nelle impostazioni locali di default del "C", il carattere umlaut-A (Ä) non sarà convertito.
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Vedere anche: strtoupper(), ucfirst(), ucwords() e mb_strtolower().
Restituisce la stringa string con i caratteri alfabetici convertiti in maiuscolo.
Nota: i caratteri 'alfabetici' sono determinati in base alle impostazioni locali. Ciò significa, ad esempio, che nelle impostazioni locali di default del "C", il carattere umlaut-A (Ä) non sarà convertito.
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Vedere anche: strtolower(), ucfirst(), ucwords() e mb_strtoupper().
Questa funzione restituisce una copia di str, traducendo tutti i caratteri di from al corrispondente carattere indicato in to.
Se from e to hanno lunghezze differenti, i caratteri in più presenti nella stringa più lunga saranno ignorati.
strtr() può essere eseguita con solo due argomenti. Se viene chiamata con due parametri si comporta in modo nuovo: from deve essere un matrice che contiene le coppie stringa -> stringa da sostituire nella stringa sorgente. strtr() cercherà sempre prima di incrociare il testo più lungo e *NON* tenterà di sostituire parti su cui ha già lavorato.
Nota: I parametri opzionali to e from sono stati aggiunti in PHP 4.0.0
Vedere anche ereg_replace().
(PHP 5)
substr_compare -- Confronto tra due stringhe a partire da una data posizione per n caratteri, sicuro con i dati binari e, opzionalmente, senza distinguere tra lettere maiuscole e minuscoleLa funzione substr_compare() confronta main_str dalla posizione offset con la stringa str per length caratteri di lunghezza.
Restituisce < 0 se main_str dalla posizione offset è minore di str, > 0 se è maggiore di str, e 0 se sono uguali. Se length è uguale o maggiore della lunghezza di main_str ed è impostato il parametro length, substr_compare() visualizza un warning e restituisce FALSE.
Se case_insensitivity è TRUE, il confronto non distingue tra lettere maiuscole e minuscole.
Esempio 1. Esempio di uso di substr_compare()
|
substr_count() restituisce il numero di volte in cui la stringa needle compare in haystack. Fare attenzione che needle distingue tra lettere maiuscole e minuscole.
Vedere anche count_chars(), strpos(), substr() e strstr().
La funzione substr_replace() sostituisce una copia di string delimitata dai parametri start e (opzionalmente) length con il testo indicato in replacement. Viene restituito il testo risultante.
Se start è positivo, la sostituzione inizierà palla posizione start di string.
Se start è negativo, la sostituzione inizierà da start caratteri dalla fine di string.
Se è indicato il parametro length ed è positivo, indica il numero di caratteri del testo string che devono essere sostituiti. Se questo parametro è negativo, indica il numero di caratteri dalla fine di string a cui fermarsi nella sostituzione. Se non viene indicato, si utilizzerà il default strlen( string ); ad esempio si finirà la sostituzione alla fine di string.
Esempio 1. Esempio di uso di substr_replace()
|
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Vedere anche str_replace() e substr().
La funzione substr() restituisce la porzione di string indicata dai parametri start e length.
Se start non è negativo, la stringa restituita inizierà dalla posizione start di string, partendo da zero. Ad esempio, nella stringa 'abcdef', il carattere alla posizione 0 è 'a', il carattere alla posizione 2 è 'c', e così via.
Esempio 1. Esempi di base di substr()
|
Se start è negativo, la stringa restituita inizierà dal carattere start dalla fine di string.
Se length è indicato ed è positivo, la stringa restituita conterrà almeno length caratteri partendo da start (in base alla lunghezza di string). Se string è minore o uguale a start, la funzione restituisce FALSE
Se length è indicato ed è negativo, allora saranno omessi length caratteri dalla fine di string (dopo avere calcolato la posizione iniziale, nel caso in cui start sia negativo). Se start indica una posizione successiva a questo troncamento, la funzione restituirà una stringa vuota.
Vedere anche strrchr(), substr_replace(), ereg(), trim(), mb_substr() e wordwrap().
(PHP 3, PHP 4, PHP 5)
trim -- Rimuove gli spazi (ed altri caratteri) all'inizio e alla fine di un testoQuesta funzione restituisce il parametro str privo degli spazi iniziali e finali. Senza la specifica del secondo parametro, trim() rimuoverà questi caratteri:
" " (ASCII 32 (0x20)), spazio.
"\t" (ASCII 9 (0x09)), il carattere tab.
"\n" (ASCII 10 (0x0A)), il new line (line feed).
"\r" (ASCII 13 (0x0D)), il carriage return.
"\0" (ASCII 0 (0x00)), il byte NUL.
"\x0B" (ASCII 11 (0x0B)), il tab verticale.
La stringa che deve essere troncata.
Opzionale, Si può, inoltre, specificare quali caratteri si desidera rimuovere elencandoli in charlist. Questo parametro è un semplice elenco dei caratteri da rimuovere. Con .. si può indicare un range di caratteri.
Esempio 1. Esempio di uso di trim()
|
Esempio 2. Trimming array values with trim()
Il precedente esempio visualizzerà:
|
Restituisce un testo in cui il primo carattere di str è maiuscolo, se si tratta di una carattere alfabetico.
Attenzione che i 'caratteri alfabetici' sono determinati dalle impostazioni locali. Ad esempio nelle impostazioni locali "C" di default, caratteri tipo ä non saranno convertiti.
Vedere anche strtolower(), strtoupper() e ucwords().
(PHP 3 >= 3.0.3, PHP 4, PHP 5)
ucwords -- Converte in maiuscolo il primo carattere di ogni parola di una stringaRestituisce un testo in cui la lettera iniziale di ogni parola è convertita in maiuscolo, se il carattere è alfabetico.
Definizione di parola: sequenza di caratteri immediatamente seguita da un carattere di delimitazione (i delimitatori sono: spazio, form-feed, newline, carriage return, tab orizzontale e tab verticale).
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Vedere anche strtoupper(), strtolower() e ucfirst().
Scrive la stringa prodotta in base a format sul flusso indicato da handle. format è descritto nella documentazione di sprintf().
La funzione agisce come fprintf() ma accetta una matrice di argomenti, piuttosto che un numero variabile di argomenti.
Restituisce la lunghezza della stringa prodotta.
Vedere anche printf(), sprintf(), sscanf(), fscanf(), vsprintf() e number_format().
Visualizza i valori di una matrice come stringa formattata in base a format (che è descritto nella documentazione di sprintf()).
Agisce come printf() ma accetta una matrice di argomenti, piuttosto che un numero variabile di argomenti.
Restituisce la lunghezza della stringa prodotta.
Vedere anche printf(), sprintf(), e vsprintf()
Restituisce i valori di una matrice come testo formattato in base a format (descritto nella documentazione di sprintf()).
Agisce come sprintf() ma accetta una matrice di argomenti, piuttosto che un numero variabile di argomenti.
(PHP 4 >= 4.0.2, PHP 5)
wordwrap -- Divide una stringa ad un certo numero di caratteri utilizzando il carattere di divisioneRestituisce una stringa con str suddivisa alla colonna indicata dal parametro opzionale width. La linea è interrotta utilizzando il parametro opzionale break.
wordwrap() interrompe automaticamente la stringa alla colonna 75 ed utilizza come carattere di interruzione '\n' (newline), se non sono dati width e break
Se il parametro cut è impostato a 1, la stringa è sempre interrotta alla lunghezza indicata. Pertanto se una parola supera la larghezza data, questa verrà interrotta. (Vedere il secondo esempio).
Nota: Il parametro opzionale cut è stato aggiunto in PHP 4.0.3
Vedere anche nl2br() e chunk_split().
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.
(PHP 4, PECL)
swf_addbuttonrecord -- Controls location, appearance and active area of the current buttonThe 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).
(PHP 4, PECL)
swf_ortho2 -- Defines 2D orthographic mapping of user coordinates onto the current viewportThe 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, PECL)
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, PECL)
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.
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 | Changelog |
---|---|---|---|
sybase.allow_persistent | "1" | PHP_INI_ALL | Available since PHP 4.0.3. |
sybase.max_persistent | "-1" | PHP_INI_ALL | Available since PHP 4.0.3. |
sybase.max_links | "-1" | PHP_INI_ALL | Available since PHP 4.0.3. |
sybase.interface_file | "/usr/sybase/interfaces" | PHP_INI_SYSTEM | |
sybase.min_error_severity | "10" | PHP_INI_ALL | |
sybase.min_message_severity | "10" | PHP_INI_ALL | |
sybase.compatability_mode | "0" | PHP_INI_ALL | |
magic_quotes_sybase | "0" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
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.
Compatibility mode with old versions of PHP 3.0. If on, this will cause PHP to automatically assign types to results according to their Sybase type, instead of treating them all as strings. This compatibility mode will probably not stay around forever, so try applying whatever necessary changes to your code, and turn it off.
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 | Changelog |
---|---|---|---|
sybct.allow_persistent | "1" | PHP_INI_SYSTEM | Available since PHP 4.0.4. |
sybct.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 4.0.4. |
sybct.max_links | "-1" | PHP_INI_SYSTEM | Available since PHP 4.0.4. |
sybct.min_server_severity | "10" | PHP_INI_ALL | Available since PHP 4.0.4. |
sybct.min_client_severity | "10" | PHP_INI_ALL | Available since PHP 4.0.4. |
sybct.hostname | NULL | PHP_INI_ALL | Available since PHP 4.0.4. |
sybct.deadlock_retry_count | "0" | PHP_INI_ALL | Available since PHP 4.3.0. |
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 define how often deadlocks are to be retried. The default is -1, or "forever".
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.
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
Il precedente esempio visualizzerà:
|
This command is not effective for SELECT statements, only on statements which modify records. To retrieve the number of rows returned from a SELECT, use sybase_num_rows().
See also sybase_num_rows().
sybase_close() 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, FALSE on error, or TRUE if the query was successful but didn't return any columns.
sybase_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if sybase_connect() was called, and use it.
See also sybase_select_db() and sybase_connect().
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 the /etc/hosts.allow and /etc/hosts.deny files to check if access to service daemon should be granted or denied for a client.
The service name.
The client remote address. Can be either an IP address or a domain name.
An optional user name.
If address looks like domain name then DNS is used to resolve it to IP address; set nodns to TRUE to avoid this.
Tidy is a binding for the Tidy HTML clean and repair utility which allows you to not only clean and otherwise manipulate HTML documents, but also traverse the document tree.
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 | Changelog |
---|---|---|---|
tidy.default_config | "" | PHP_INI_SYSTEM | Available since PHP 5.0.0. |
tidy.clean_output | "0" | PHP_INI_PERDIR | Available since PHP 5.0.0. |
Breve descrizione dei parametri di configurazione.
tidyNode->hasChildren - Returns TRUE if the current node has childrens
tidyNode->hasSiblings - Returns TRUE if the current node has siblings
tidyNode->isAsp - Returns TRUE if the current node is ASP code
tidyNode->isComment - Returns TRUE if the current node is a comment
tidyNode->isHtml - Returns TRUE if the current node is HTML
tidyNode->isJste - Returns TRUE if the current node is JSTE
tidyNode->isPhp - Returns TRUE if the current node is PHP
tidyNode->isText - Returns TRUE if the current node is Text (no markup)
value - the value of the node (e.g. the html text)
name - the name of the tag (e.g. html, a, etc..)
type - the type of the node (one of the constants above, e.g. TIDY_NODETYPE_PHP)
line* - the line where the node starts
column* - the column where the node starts
proprietary* - TRUE if the node refers to a proprietary tag
id - the ID of the tag (one of the constants above, e.g. TIDY_TAG_FRAME)
attribute - an array with the attributes of the current node, or NULL if there aren't any
child - an array with the child tidyNodes, or NULL if there aren't any
Nota: The properties marked with * are just available since PHP 5.1.0.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Each TIDY_TAG_XXX represents a HTML tag. For example, TIDY_TAG_A represents a <a href="XX">link</a> tag. Each TIDY_ATTR_XXX represents a HTML atribute. For example TIDY_ATTR_HREF would represent the href atribute in the previous example.
The following constants are defined:
Tabella 2. tidy tag constants
constant |
---|
TIDY_TAG_UNKNOWN |
TIDY_TAG_A |
TIDY_TAG_ABBR |
TIDY_TAG_ACRONYM |
TIDY_TAG_ALIGN |
TIDY_TAG_APPLET |
TIDY_TAG_AREA |
TIDY_TAG_B |
TIDY_TAG_BASE |
TIDY_TAG_BASEFONT |
TIDY_TAG_BDO |
TIDY_TAG_BGSOUND |
TIDY_TAG_BIG |
TIDY_TAG_BLINK |
TIDY_TAG_BLOCKQUOTE |
TIDY_TAG_BODY |
TIDY_TAG_BR |
TIDY_TAG_BUTTON |
TIDY_TAG_CAPTION |
TIDY_TAG_CENTER |
TIDY_TAG_CITE |
TIDY_TAG_CODE |
TIDY_TAG_COL |
TIDY_TAG_COLGROUP |
TIDY_TAG_COMMENT |
TIDY_TAG_DD |
TIDY_TAG_DEL |
TIDY_TAG_DFN |
TIDY_TAG_DIR |
TIDY_TAG_DIV |
TIDY_TAG_DL |
TIDY_TAG_DT |
TIDY_TAG_EM |
TIDY_TAG_EMBED |
TIDY_TAG_FIELDSET |
TIDY_TAG_FONT |
TIDY_TAG_FORM |
TIDY_TAG_FRAME |
TIDY_TAG_FRAMESET |
TIDY_TAG_H1 |
TIDY_TAG_H2 |
TIDY_TAG_H3 |
TIDY_TAG_H4 |
TIDY_TAG_H5 |
TIDY_TAG_H6 |
TIDY_TAG_HEAD |
TIDY_TAG_HR |
TIDY_TAG_HTML |
TIDY_TAG_I |
TIDY_TAG_IFRAME |
TIDY_TAG_ILAYER |
TIDY_TAG_IMG |
TIDY_TAG_INPUT |
TIDY_TAG_INS |
TIDY_TAG_ISINDEX |
TIDY_TAG_KBD |
TIDY_TAG_KEYGEN |
TIDY_TAG_LABEL |
TIDY_TAG_LAYER |
TIDY_TAG_LEGEND |
TIDY_TAG_LI |
TIDY_TAG_LINK |
TIDY_TAG_LISTING |
TIDY_TAG_MAP |
TIDY_TAG_MARQUEE |
TIDY_TAG_MENU |
TIDY_TAG_META |
TIDY_TAG_MULTICOL |
TIDY_TAG_NOBR |
TIDY_TAG_NOEMBED |
TIDY_TAG_NOFRAMES |
TIDY_TAG_NOLAYER |
TIDY_TAG_NOSAFE |
TIDY_TAG_NOSCRIPT |
TIDY_TAG_OBJECT |
TIDY_TAG_OL |
TIDY_TAG_OPTGROUP |
TIDY_TAG_OPTION |
TIDY_TAG_P |
TIDY_TAG_PARAM |
TIDY_TAG_PLAINTEXT |
TIDY_TAG_PRE |
TIDY_TAG_Q |
TIDY_TAG_RP |
TIDY_TAG_RT |
TIDY_TAG_RTC |
TIDY_TAG_RUBY |
TIDY_TAG_S |
TIDY_TAG_SAMP |
TIDY_TAG_SCRIPT |
TIDY_TAG_SELECT |
TIDY_TAG_SERVER |
TIDY_TAG_SERVLET |
TIDY_TAG_SMALL |
TIDY_TAG_SPACER |
TIDY_TAG_SPAN |
TIDY_TAG_STRIKE |
TIDY_TAG_STRONG |
TIDY_TAG_STYLE |
TIDY_TAG_SUB |
TIDY_TAG_TABLE |
TIDY_TAG_TBODY |
TIDY_TAG_TD |
TIDY_TAG_TEXTAREA |
TIDY_TAG_TFOOT |
TIDY_TAG_TH |
TIDY_TAG_THEAD |
TIDY_TAG_TITLE |
TIDY_TAG_TR |
TIDY_TAG_TR |
TIDY_TAG_TT |
TIDY_TAG_U |
TIDY_TAG_UL |
TIDY_TAG_VAR |
TIDY_TAG_WBR |
TIDY_TAG_XMP |
Tabella 3. tidy attribute constants
constant |
---|
TIDY_ATTR_UNKNOWN |
TIDY_ATTR_ABBR |
TIDY_ATTR_ACCEPT |
TIDY_ATTR_ACCEPT_CHARSET |
TIDY_ATTR_ACCESSKEY |
TIDY_ATTR_ACTION |
TIDY_ATTR_ADD_DATE |
TIDY_ATTR_ALIGN |
TIDY_ATTR_ALINK |
TIDY_ATTR_ALT |
TIDY_ATTR_ARCHIVE |
TIDY_ATTR_AXIS |
TIDY_ATTR_BACKGROUND |
TIDY_ATTR_BGCOLOR |
TIDY_ATTR_BGPROPERTIES |
TIDY_ATTR_BORDER |
TIDY_ATTR_BORDERCOLOR |
TIDY_ATTR_BOTTOMMARGIN |
TIDY_ATTR_CELLPADDING |
TIDY_ATTR_CELLSPACING |
TIDY_ATTR_CHAR |
TIDY_ATTR_CHAROFF |
TIDY_ATTR_CHARSET |
TIDY_ATTR_CHECKED |
TIDY_ATTR_CITE |
TIDY_ATTR_CLASS |
TIDY_ATTR_CLASSID |
TIDY_ATTR_CLEAR |
TIDY_ATTR_CODE |
TIDY_ATTR_CODEBASE |
TIDY_ATTR_CODETYPE |
TIDY_ATTR_COLOR |
TIDY_ATTR_COLS |
TIDY_ATTR_COLSPAN |
TIDY_ATTR_COMPACT |
TIDY_ATTR_CONTENT |
TIDY_ATTR_COORDS |
TIDY_ATTR_DATA |
TIDY_ATTR_DATAFLD |
TIDY_ATTR_DATAPAGESIZE |
TIDY_ATTR_DATASRC |
TIDY_ATTR_DATETIME |
TIDY_ATTR_DECLARE |
TIDY_ATTR_DEFER |
TIDY_ATTR_DIR |
TIDY_ATTR_DISABLED |
TIDY_ATTR_ENCODING |
TIDY_ATTR_ENCTYPE |
TIDY_ATTR_FACE |
TIDY_ATTR_FOR |
TIDY_ATTR_FRAME |
TIDY_ATTR_FRAMEBORDER |
TIDY_ATTR_FRAMESPACING |
TIDY_ATTR_GRIDX |
TIDY_ATTR_GRIDY |
TIDY_ATTR_HEADERS |
TIDY_ATTR_HEIGHT |
TIDY_ATTR_HREF |
TIDY_ATTR_HREFLANG |
TIDY_ATTR_HSPACE |
TIDY_ATTR_HTTP_EQUIV |
TIDY_ATTR_ID |
TIDY_ATTR_ISMAP |
TIDY_ATTR_LABEL |
TIDY_ATTR_LANG |
TIDY_ATTR_LANGUAGE |
TIDY_ATTR_LAST_MODIFIED |
TIDY_ATTR_LAST_VISIT |
TIDY_ATTR_LEFTMARGIN |
TIDY_ATTR_LINK |
TIDY_ATTR_LONGDESC |
TIDY_ATTR_LOWSRC |
TIDY_ATTR_MARGINHEIGHT |
TIDY_ATTR_MARGINWIDTH |
TIDY_ATTR_MAXLENGTH |
TIDY_ATTR_MEDIA |
TIDY_ATTR_METHOD |
TIDY_ATTR_MULTIPLE |
TIDY_ATTR_NAME |
TIDY_ATTR_NOHREF |
TIDY_ATTR_NORESIZE |
TIDY_ATTR_NOSHADE |
TIDY_ATTR_NOWRAP |
TIDY_ATTR_OBJECT |
TIDY_ATTR_OnAFTERUPDATE |
TIDY_ATTR_OnBEFOREUNLOAD |
TIDY_ATTR_OnBEFOREUPDATE |
TIDY_ATTR_OnBLUR |
TIDY_ATTR_OnCHANGE |
TIDY_ATTR_OnCLICK |
TIDY_ATTR_OnDATAAVAILABLE |
TIDY_ATTR_OnDATASETCHANGED |
TIDY_ATTR_OnDATASETCOMPLETE |
TIDY_ATTR_OnDBLCLICK |
TIDY_ATTR_OnERRORUPDATE |
TIDY_ATTR_OnFOCUS |
TIDY_ATTR_OnKEYDOWN |
TIDY_ATTR_OnKEYPRESS |
TIDY_ATTR_OnKEYUP |
TIDY_ATTR_OnLOAD |
TIDY_ATTR_OnMOUSEDOWN |
TIDY_ATTR_OnMOUSEMOVE |
TIDY_ATTR_OnMOUSEOUT |
TIDY_ATTR_OnMOUSEOVER |
TIDY_ATTR_OnMOUSEUP |
TIDY_ATTR_OnRESET |
TIDY_ATTR_OnROWENTER |
TIDY_ATTR_OnROWEXIT |
TIDY_ATTR_OnSELECT |
TIDY_ATTR_OnSUBMIT |
TIDY_ATTR_OnUNLOAD |
TIDY_ATTR_PROFILE |
TIDY_ATTR_PROMPT |
TIDY_ATTR_RBSPAN |
TIDY_ATTR_READONLY |
TIDY_ATTR_REL |
TIDY_ATTR_REV |
TIDY_ATTR_RIGHTMARGIN |
TIDY_ATTR_ROWS |
TIDY_ATTR_ROWSPAN |
TIDY_ATTR_RULES |
TIDY_ATTR_SCHEME |
TIDY_ATTR_SCOPE |
TIDY_ATTR_SCROLLING |
TIDY_ATTR_SELECTED |
TIDY_ATTR_SHAPE |
TIDY_ATTR_SHOWGRID |
TIDY_ATTR_SHOWGRIDX |
TIDY_ATTR_SHOWGRIDY |
TIDY_ATTR_SIZE |
TIDY_ATTR_SPAN |
TIDY_ATTR_SRC |
TIDY_ATTR_STANDBY |
TIDY_ATTR_START |
TIDY_ATTR_STYLE |
TIDY_ATTR_SUMMARY |
TIDY_ATTR_TABINDEX |
TIDY_ATTR_TARGET |
TIDY_ATTR_TEXT |
TIDY_ATTR_TITLE |
TIDY_ATTR_TOPMARGIN |
TIDY_ATTR_TYPE |
TIDY_ATTR_USEMAP |
TIDY_ATTR_VALIGN |
TIDY_ATTR_VALUE |
TIDY_ATTR_VALUETYPE |
TIDY_ATTR_VERSION |
TIDY_ATTR_VLINK |
TIDY_ATTR_VSPACE |
TIDY_ATTR_WIDTH |
TIDY_ATTR_WRAP |
TIDY_ATTR_XML_LANG |
TIDY_ATTR_XML_SPACE |
TIDY_ATTR_XMLNS |
Tabella 4. tidy nodetype constants
constant | description |
---|---|
TIDY_NODETYPE_ROOT | root node |
TIDY_NODETYPE_DOCTYPE | doctype |
TIDY_NODETYPE_COMMENT | HTML comment |
TIDY_NODETYPE_PROCINS | Processing Instruction |
TIDY_NODETYPE_TEXT | Text |
TIDY_NODETYPE_START | start tag |
TIDY_NODETYPE_END | end tag |
TIDY_NODETYPE_STARTEND | empty tag |
TIDY_NODETYPE_CDATA | CDATA |
TIDY_NODETYPE_SECTION | XML section |
TIDY_NODETYPE_ASP | ASP code |
TIDY_NODETYPE_JSTE | JSTE code |
TIDY_NODETYPE_PHP | PHP code |
TIDY_NODETYPE_XMLDECL | XML declaration |
This simple example shows basic Tidy usage.
Esempio 2. Basic Tidy usage
|
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 documenttidy_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 ( tidy object )Object oriented style:
bool tidy->cleanRepair ( void )This function cleans and repairs the given tidy object.
See also tidy_repair_file() and tidy_repair_string().
(PHP 5)
tidy_config_count -- Returns the Number of Tidy configuration errors encountered for specified documenttidy_config_count() returns the number of errors encountered in the configuration of the specified tidy object.
tidy::__construct() constructs a new tidy object.
If the filename parameter is given, this function will also read that file and initialize the object with the file, acting like tidy_parse_file().
Il parametro config può essere passato sia come matrice sia come stringa. Se lo si passa come stringa, questo indica il nome del file di configurazione; nel primo caso viene interpretato come impostazione di opzioni. Guardare http://tidy.sourceforge.net/docs/quickref.html per maggiori dettagli su ogni singola opzione.
Il parametro encoding imposta la codifica dei caratteri per le operazioni di input ed output. I possibili valori sono: ascii, latin1, raw, utf8, iso2022, mac, win1252, utf16le, utf16be, utf16, big5 and shiftjis.
Esempio 1. tidy::__construct() example
Il precedente esempio visualizzerà:
|
See also tidy_parse_file() and tidy_parse_string().
Procedural style:
bool tidy_diagnose ( tidy object )Object oriented style:
bool tidy->diagnose ( void )tidy_diagnose() runs diagnostic tests on the given tidy object, adding some more information about the document in the error buffer.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. tidy_diagnose() example
Il precedente esempio visualizzerà:
|
See also tidy_get_error_buffer().
tidy_error_count() returns the number of Tidy errors encountered for the specified document.
Esempio 1. tidy_error_count() example
Il precedente esempio visualizzerà:
|
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:
tidyNode tidy_get_body ( tidy object )Object oriented style:
tidyNode tidy->body ( void )This function returns a tidyNode object starting from the <body> tag of the tidy parse tree.
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 ( tidy object )Object oriented style:
array tidy->getConfig ( void )tidy_get_config() returns an array with the configuration options in use by the given tidy object.
For an explanation about each option, visit http://tidy.sourceforge.net/docs/quickref.html.
Esempio 1. tidy_get_config() example
Il precedente esempio visualizzerà:
|
See also tidy_reset_config() and tidy_save_config().
(PHP 5)
tidy_get_error_buffer -- Return warnings and errors which occurred parsing the specified documentProcedural style:
string tidy_get_error_buffer ( tidy object )Object 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
Il precedente esempio visualizzerà:
|
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:
tidyNode tidy_get_head ( tidy object )Object oriented style:
tidyNode tidy->head ( void )This function returns a tidyNode object starting from the <head> tag of the tidy parse tree.
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 ( tidy object )Object oriented style:
int tidy->getHtmlVer ( void )tidy_get_html_ver() returns the detected HTML version for the specified tidy object.
Avvertimento |
This function is not yet implemented in the Tidylib itself, so it always return 0. |
(PHP 5)
tidy_get_html -- Returns a tidyNode Object starting from the <html> tag of the tidy parse treeProcedural style:
tidyNode tidy_get_html ( tidy object )Object oriented style:
tidyNode tidy->html ( void )This function returns a tidyNode object starting from the <html> tag of the tidy parse tree.
Esempio 1. tidy_get_html() example
Il precedente esempio visualizzerà:
|
Nota: Questa funzione è disponibile solo con Zend Engine 2, ciò implica PHP >= 5.0.0.
See also tidy_get_body() and tidy_get_head().
Procedural style:
string tidy_get_opt_doc ( tidy object, string optname )Object oriented style:
string tidy->getOptDoc ( string optname )tidy_get_opt_doc() returns the documentation for the given option name.
Nota: You need at least libtidy from 25 April, 2005 for this function be available.
Returns a string if the option exists and has documentation available, or FALSE otherwise.
Esempio 1. Print all options along with their documentation and default value
|
tidy_get_output() returns a string with the repaired html.
Esempio 1. tidy_get_output() example
Il precedente esempio visualizzerà:
|
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:
tidyNode tidy_get_root ( tidy object )Object oriented style:
tidyNode tidy->root ( void )Returns a tidyNode object representing the root of the tidy parse tree.
Esempio 1. dump nodes
Il precedente esempio visualizzerà:
|
Nota: Questa funzione è disponibile solo con Zend Engine 2, ciò implica PHP >= 5.0.0.
Procedural style:
int tidy_get_status ( tidy object )Object oriented style:
int tidy->getStatus ( void )tidy_get_status() returns the status for the specified tidy object. It returns 0 if no error/warning was raised, 1 for warnings or accessibility errors, or 2 for errors.
Procedural style:
mixed tidy_getopt ( tidy object, string option )Object oriented style:
mixed tidy->getOpt ( string option )tidy_getopt() returns the value of the specified option for the specified tidy object. The return type depends on the type of the specified option. You will find a list with each configuration option and their types at: http://tidy.sourceforge.net/docs/quickref.html.
Esempio 1. tidy_getopt() example
Il precedente esempio visualizzerà:
|
Procedural style:
bool tidy_is_xhtml ( tidy object )Object oriented style:
bool tidy->isXhtml ( void )This function returns TRUE if the specified tidy object is a XHTML document, or FALSE otherwise.
Avvertimento |
This function is not yet implemented in the Tidylib itself, so it always return FALSE. |
Procedural style:
bool tidy_is_xml ( tidy object )Object oriented style:
bool tidy->isXml ( void )This function returns TRUE if the specified tidy object is a generic XML document (non HTML/XHTML), or FALSE otherwise.
Avvertimento |
This function is not yet implemented in the Tidylib itself, so it always return FALSE. |
(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->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->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. |
Procedural style:
tidy tidy_parse_file ( string filename [, mixed config [, string encoding [, bool use_include_path]]] )Object oriented style:
bool tidy->parseFile ( string filename [, mixed config [, string encoding [, bool use_include_path]]] )This function parses the given file.
Il parametro config può essere passato sia come matrice sia come stringa. Se lo si passa come stringa, questo indica il nome del file di configurazione; nel primo caso viene interpretato come impostazione di opzioni. Guardare http://tidy.sourceforge.net/docs/quickref.html per maggiori dettagli su ogni singola opzione.
Il parametro encoding imposta la codifica dei caratteri per le operazioni di input ed output. I possibili valori sono: ascii, latin1, raw, utf8, iso2022, mac, win1252, utf16le, utf16be, utf16, big5 and shiftjis.
Nota: I parametri opzionali config e encoding sono stati aggiunti in Tidy 2.0.
See also tidy_parse_string(), tidy_repair_file() and tidy_repair_string().
Procedural style:
tidy tidy_parse_string ( string input [, mixed config [, string encoding]] )Object oriented style:
bool tidy->parseString ( string input [, mixed config [, string encoding]] )tidy_parse_string() parses a document stored in a string.
Il parametro config può essere passato sia come matrice sia come stringa. Se lo si passa come stringa, questo indica il nome del file di configurazione; nel primo caso viene interpretato come impostazione di opzioni. Guardare http://tidy.sourceforge.net/docs/quickref.html per maggiori dettagli su ogni singola opzione.
Il parametro encoding imposta la codifica dei caratteri per le operazioni di input ed output. I possibili valori sono: ascii, latin1, raw, utf8, iso2022, mac, win1252, utf16le, utf16be, utf16, big5 and shiftjis.
Esempio 1. tidy_parse_string() example
Il precedente esempio visualizzerà:
|
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
Il precedente esempio visualizzerà:
|
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 filetidy_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 markupSets 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 documenttidy_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.
tidy_warning_count() returns the number of Tidy warnings encountered for the specified document.
See also tidy_access_count() and tidy_error_count().
(no version information, might be only in CVS)
tidyNode->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)
tidyNode->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.
This functions returns TRUE if the current node is ASP, or FALSE otherwise.
Nota: This function was named tidy_node->is_asp() in PHP 4/Tidy 1.
(no version information, might be only in CVS)
tidyNode->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)
tidyNode->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.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: This function was named tidy_node->is_jste() in PHP 4/Tidy 1.
Returns TRUE if the current node is PHP code, FALSE otherwise.
Esempio 1. get the PHP code from a mixed HTML/PHP document
Il precedente esempio visualizzerà:
|
Nota: This function was named tidy_node->is_php() in PHP 4/Tidy 1.
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.
T_OLD_FUNCTION is not defined in PHP 5.
T_ML_COMMENT is not defined in PHP 5. All comments in PHP 5 are of token T_COMMENT.
T_DOC_COMMENT was introduced in PHP 5.
PHP 5 only.
PHP 5 only.
PHP 5 only.
PHP 5 only.
PHP 5 only.
PHP 5 only.
PHP 5 only.
PHP 5 only.
PHP 5 only.
PHP 5 only.
PHP 5 only.
PHP 5 only.
PHP 5 only.
PHP 5 only.
PHP 5 only.
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.
For a list of parser tokens, see Appendice Q, or use token_name() to translate a token value into its string representation.
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.
Esempio 1. token_get_all() examples
|
token_name() gets the symbolic name for a PHP token value.
The symbolic name of the given token. The returned name returned matches the name of the matching token constant.
Unicode Support.
Avvertimento |
This extension is still in development and it isn't available to public yet. |
First you should download and install ICU:
Then checkout latest PHP and configure it --with-icu-dir=<dir> option, where <dir> was the dir to where you installed ICU. You don't need to explicitly use this option if you install ICU to a standard location.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Unicode Configuration Options
Name | Default | Changeable | Changelog |
---|---|---|---|
unicode.fallback_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0. |
unicode.from_error_mode | 2 | PHP_INI_ALL | Available since PHP 6.0.0. |
unicode.from_error_subst_char | "3f" | PHP_INI_ALL | Available since PHP 6.0.0. |
unicode.http_input_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0. |
unicode.output_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0. |
unicode.runtime_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0. |
unicode.script_encoding | NULL | PHP_INI_ALL | Available since PHP 6.0.0. |
unicode.semantics | off | PHP_INI_PERDIR | Available since PHP 6.0.0. |
Breve descrizione dei parametri di configurazione.
Default encoding for output.
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 default Locale, which is used by PHP to localize certain features. Please note that this isn't influenced by setlocale() or the system settings.
Sets the default Locale for PHP programs. Please note that this has nothing to do with setlocale() nor with the system locale.
The new Locale name. A comprehensive list of the supported locales is available at http://www-950.ibm.com/software/globalization/icu/demo/locales/en/?d_=en.
Esempio 1. A i18n_loc_set_default() example This example demonstrates a possible usage of i18n_loc_set_default() to localize the sort() functions.
Il precedente esempio visualizzerà:
If we didn't use the locale, PHP would sort the string using the ASCII characters value, thus returning (wrongly):
|
(PHP 5 CVS only)
unicode_encode -- Takes a unicode string and converts it to a string in the specified encodingAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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. Returns FALSE on failure and an error of level E_WARNING will be issued.
If the optional format parameter is set to 1, get_headers() parses the response and sets the array's keys.
Esempio 1. get_headers() example
Il precedente esempio visualizzerà qualcosa simile a:
|
(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 TRUE will result in PHP trying to open the file along the standard include path as per the include_path directive. This is used for local files, not URLs.
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.
Nota: arg_separator.output is used to separate arguments.
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 parses a URL and returns an associative array containing any of the various components of the URL that are present.
This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.
On seriously malformed URLs, parse_url() may return FALSE and emit a E_WARNING. Otherwise an associative array is returned, whose components may be (at least one):
scheme
- e.g. http
host
port
user
pass
path
query
- after the question mark ?
fragment
- after the hashmark #
Esempio 1. A parse_url() example
Il precedente esempio visualizzerà:
|
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() or htmlspecialchars().
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 | Variazioni |
---|---|---|---|
unserialize_callback_func | "" | PHP_INI_ALL | Disponibile dal PHP 4.2.0. |
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().
(PHP 4 >= 4.2.0, PHP 5)
debug_zval_dump -- Dumps a string representation of an internal zend value to outputDumps a string representation of an internal zend value to output.
Beware the refcount: The refcount value returned by this function is non-obvious in certain circumstances. For example, a developer might expect the above example to indicate a refcount of 2. The third reference is created when actually calling debug_zval_dump().
This behavior is further compounded when a variable is not passed to debug_zval_dump() by reference. To illustrate, consider a slightly modified version of the above example:
Why refcount(1)? Because a copy of $var1 is being made, when the function is called.
This function becomes even more confusing when a variable with a refcount of 1 is passed (by copy/value):
A refcount of 2, here, is extremely non-obvious. Especially considering the above examples. So what's happening?
When a variable has a single reference (as did $var1 before it was used as an argument to debug_zval_dump()), PHP's engine optimizes the manner in which it is passed to a function. Internally, PHP treats $var1 like a reference (in that the refcount is increased for the scope of this function), with the caveat that if the passed reference happens to be written to, a copy is made, but only at the moment of writing. This is known as "copy on write."
So, if debug_zval_dump() happened to write to its sole parameter (and it doesn't), then a copy would be made. Until then, the parameter remains a reference, causing the refcount to be incremented to 2 for the scope of the function call.
var_dump() |
debug_backtrace() |
References Explained |
Reference Counting and Aliasing (by Andi Gutmans) |
Versione | Descrizione |
---|---|
4.2.0 | doubleval() è diventato un alias di floatval(). Prima esisteva solo doubleval(). |
Varibaile da controllare
Nota: empty() agisce solo su variabili, qualsiasi altra cosa genera un errore di parsing. In altre parole, il seguente comando non funziona: empty(trim($name)).
empty() è l'opposto di (boolean) var, tranne che non viene dato alcun warning quando la variabile non è valorizzata.
Restituisce FALSE se var non è vuota ed ha un valore diverso da zero.
I seguenti valori sono considerati vuoti:
"" (stringa vuota) |
0 (0 come intero) |
"0" (0 come stringa) |
NULL |
FALSE |
array() (matrice vuota) |
var $var; (una variabile dichiarata, ma senza valore in una classe) |
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
Può anche essere di tipo scalare. La funzione floatval() non può essere usata con variabili di tipo array oppure object.
(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, visibili da dove get_defined_vars() viene eseguito.
Esempio 1. Esempio di uso di get_defined_vars()
|
Questa funzione restituisce il tipo della risorsa data.
Se il parametro handle è una risorsa, questa funzione restituirà una stringa indicante il tipo di risorsa. Se il tipo non è identificato dalla funzione, il valore restituito sarà Unknown.
La funzione restituisce FALSE e genera un errore se handle non è di tipo resource.
Esempio 1. Esempio di uso di get_resource_type()
|
Restituisce il tipo della variabile PHP var.
Avvertimento |
Non utilizzare gettype() per testare certi tipi di variabili poichè la stringa restistuita potrebbe variare nelle versioni future. Inoltre questa funzione è lenta dato che richiede confronti tra stringhe Piuttosto utilizzare le funzioni is_*. |
La stringa restituita può assumere i seguenti valori:
"boolean" (dalla versione 4 di PHP)
"integer"
"double" (per ragioni storiche viene restituito "double" in caso di variabile di tipo float, e non semplicemente "float")
"string"
"array"
"object"
"resource" (dalla versione 4 di PHP)
"NULL" (dalla versione 4 di PHP)
"user function" (soltanto in PHP 3, deprecated)
"unknown type"
Nella versione 4 di PHP si dovrebbe applicare alle funzioni function_exists() o method_exists() al posto del precedente gettype().
Vedere anche settype(), is_array(), is_bool(), is_float(), is_int(), is_null(), is_numeric(), is_object(), is_resource(), is_scalar() e is_string().
(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).
Valore scalare da convertire in intero
Base per la conversione (il default è 10)
Il valore intero di var se riesce, oppure 0 in caso di errore. Le matrici e gli oggetti vuoti restituiscono 0, la matrici e gli oggetti pieni restituiscono 1.
Il valore massimo dipende dal sistema. Nei sistemi a 32 bit si ha come valore per il caso di intero con segno il range da -2147483648 a 2147483647. Così, ad esempio, su tali sistemi, la riga intval('1000000000000') restituirà 2147483647. Il massimo valore per un intero con segno sui sistemi a 64 bit è 9223372036854775807.
Le stringhe probabilmente restituiranno 0, sebbene il valore restituito dipenda dal primo carattere a sinistra della stringa. Si utilizzano le comuni di integer casting .
Esempio 1. Esempi di uso di intval() I seguenti esempi sono basati su un sistema a 32 bit.
|
floatval() |
strval() |
settype() |
is_numeric() |
Type juggling |
BCMath Arbitrary Precision Mathematics Functions |
(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)Verifica se una variabile è di tipo float (decimale a virgola mobile).
Nota: Per verificare se una variabile è un numero oppure una stringa numerica (come le variabili dei form, che sono sempre stringhe) occorre usare la funzione is_numeric().
Verifica che la variabile data sia di tipo integer
Nota: Per verificare se una variabile è un numero oppure una stringa numerica (come le variabili dei form, che sono sempre stringhe) occorre usare la funzione is_numeric().
Verifica se una variabile è un numero o una stringa numerica.
Restituisce TRUE se var è un numero o una stringa numerica, FALSE in caso contrario.
Restituisce TRUE se la variabile individuata dal parametro var è di tipo resource, altrimenti restituisce FALSE.
Verifica se la data variabile sia di tipo scalare
Le variabili scalari sono quelle contenenti valori di tipo integer, float, string oppure boolean. I tipi array, object e resource non sono scalari.
Restituisce TRUE se la variabile indicata dal parametro var è di tipo scalare, in caso contrario restituisce FALSE.
Esempio 1. Esempio di uso di is_scalar()
Il precedente esempio visualizzerà:
|
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: Questa funzione non gira correttamente sino alla versione 4.0.7.
Nota: Nella versione 3 di PHP si serializzano le proprietà dell'oggetto, ma non i metodi. Nella versione 4 questa limitazione è stata rimossa, pertanto possono essere recuperati sia le proprietà sia i metodi. Per maggiori informazioni vedere la sezione Serializzare oggetti in Oggetti e Classi.
Non è possibile serializzare gli oggetti predefiniti di PHP.
Esempio 1. Esempio di serialize()
|
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 boolean, integer, float, string, array oppure object. Nel caso in cui la stringa passata non sia deserializzabile la funzione restituisce FALSE e genera un E_NOTICE.
Avvertimento |
FALSE è restituito sia in caso di errore e sia in caso di de-serializzazione del valore FALSE. Questo caso particolare può essere intercettato confrontando str con serialize(false) o rilevando il E_NOTICE generato. |
Direttiva unserialize_callback_func: E' possibile impostare una funzione di callback che possa essere richiamata se, durante la fase di deserializzazione, occorre istanziare una classe indefinita. (per evitare di ottenere un tipo object incompleto "__PHP_Incomplete_Class".) Per definire il parametro 'unserialize_callback_func' si può agire sul php.ini, o usare ini_set() oppure con .htaccess. Verrà utilizzata questa funzione ogni volta che occorre istanziare una classe indefinita. Per disabilitare questa opzione, lasciare vuota questa impostazione. Attenzione che la direttiva unserialize_callback_func è disponibile dalla versione 4.2.0 di PHP.
Se la variabile da ripristinare è un oggetto, dopo avere ricostruito l'oggetto, il PHP cercherà di eseguire la funzione membro __wakeup() (se esiste).
Esempio 1. Esempio di unserialize_callback_func.
|
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; ?> |
Il precedente esempio visualizzerà:
Nel caso di una variabile PASSATA PER RIFERIMENTO ad una funzione, l'uso della funzione unset() distrugge solo la copia locale della variabile. Nell'ambiente chiamante, la variabile manterrà il medesimo valore che aveva prima dell'uso di unset().
<?php function foo(&$bar) { unset($bar); $bar = "blah"; } $bar = 'something'; echo "$bar\n"; foo($bar); echo "$bar\n"; ?> |
Il precedente esempio visualizzerà:
Se si usa unset() su una variabile statica all'interno di una funzione, unset() cancella la variabile e tutti i suoi riferimenti.
Il precedente esempio 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 5 soltanto le proprietà pubbliche, private e protette di un oggetto possono essere restituite.
Suggerimento: Come con qualsiasi cosa che invia il risultato direttamente al browser, è possibile utilizzare la funzione output-control per catturare l'uscita di questa funzione e salvarla - per esempio - in una stringa.
Esempio 1. var_dump() example
Il precedente esempio visualizzerà:
Il precedente esempio visualizzerà:
|
La funzione var_export() restituisce informazioni strutturate sulla data variabile. E' simile a var_dump() con una differenza: il valore restituito è codice PHP.
La variabile che si desidera esportare.
Se utilizzato ed impostato a TRUE, la funzione var_export() restituisce la rappresentazione della variabile anzichè visualizzarla.
Restituisce la rappresentazione della variabile quando il parametro return viene impostato a TRUE. Altrimenti la funzione restituisce NULL.
Esempio 1. Esempio di utilizzo di var_export()
Il precedente esempio visualizzerà:
Il precedente esempio visualizzerà:
|
Nota: Le variabili di tipo resource, le matrici e gli oggetti contenenti oggetti non possono essere esportati da questa funzione.
This extension allows you to process credit cards and other financial transactions using Verisign Payment Services, formerly known as Signio (http://www.verisign.com/products-services/payment-processing/online-payment/payflow-pro/index.html).
When using these functions, you may omit calls to pfpro_init() and pfpro_cleanup() as this extension will do so automatically if required. However the functions are still available in case you are processing a number of transactions and require fine control over the library. You may perform any number of transactions using pfpro_process() between the two.
These functions were added in PHP 4.0.2.
Nota: These functions only provide a link to Verisign Payment Services. Be sure to read the Payflow Pro Developers Guide for full details of the required parameters.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.1.0.
Nota: Questo modulo non è disponibile su piattaforme Windows.
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.
Avvertimento |
If you are planing to use this extension along with the OpenSSL extension or with ModSSL, you should compile this extension as shared: --with-pfpro=shared,/usr/local. |
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Verisign Payflow Pro configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
pfpro.defaulthost/PFPRO_VERSION < 3 | "test.signio.com" | PHP_INI_ALL | |
pfpro.defaulthost | "test-payflow.verisign.com" | PHP_INI_ALL | Available since PHP 4.0.2. |
pfpro.defaultport | "443" | PHP_INI_ALL | Available since PHP 4.0.2. |
pfpro.defaulttimeout | "30" | PHP_INI_ALL | Available since PHP 4.0.2. |
pfpro.proxyaddress | "" | PHP_INI_ALL | Available since PHP 4.0.2. |
pfpro.proxyport | "" | PHP_INI_ALL | Available since PHP 4.0.2. |
pfpro.proxylogon | "" | PHP_INI_ALL | Available since PHP 4.0.2. |
pfpro.proxypassword | "" | PHP_INI_ALL | Available since PHP 4.0.2. |
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
|
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, PECL)
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. |
(4.0.5 - 4.2.3 only, PECL)
vpopmail_add_user -- Aggiunge un nuovo utente al dominio virtuale specificatoAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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.2.3 only, PECL)
vpopmail_alias_del_domain -- Elimina tutti gli alias virtuali di un dominioAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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.2.3 only, PECL)
vpopmail_alias_get_all -- Riceve tutte le linee di un alias per un dominioAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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, PECL)
vpopmail_error -- Riceve il messaggio testuale dell'ultimo errore di vpopmailAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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().
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.1.0.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
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 convert your data to UTF-8 first (see utf8_encode() and iconv()).
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_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> |
The win32service extension is a Windows specific extension that allows PHP to communicate with the Service Control Manager to start, stop, register and unregister services, and even allows your PHP scripts to run as a service.
Windows NT, Windows 2000, Windows XP or Windows Server 2003. Any version of windows derived from Windows NT should be compatible.
You can download php_win32service.dll from http://snaps.php.net/win32/. Choose the PECL_X_X folder that matches you PHP version.
Copy the php_win32service.dll into your extension_dir.
Load the extension from your php.ini
extension=php_win32service.dll |
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.
An array of service details:
The short name of the service. This is the name that you will use to control the service using the net command. The service must be unique (no two services can share the same name), and, ideally, should avoid having spaces in the name.
The display name of the service. This is the name that you will see in the Services Applet.
The name of the user account under which you want the service to run. If omitted, the service will run as the LocalSystem account. If the username is specified, you must also provide a password.
The password that corresponds to the user.
The full path to the executable module that will be launched when the service is started. If omitted, the path to the current PHP process will be used.
Command line parameters to pass to the service when it starts. If you want to run a PHP script as the service, then the first parameter should be the full path to the PHP script that you intend to run.
Controls the load_order. This is not yet fully supported.
Sets the service type. If omitted, the default value is WIN32_SERVICE_WIN32_OWN_PROCESS. Don't change this unless you know what you're doing.
Specifies how the service should be started. The default is WIN32_SERVICE_AUTO_START which means the the service will be launched when the machine starts up.
Informs the SCM what it should do when it detects a problem with the service. The default is WIN32_SERVER_ERROR_IGNORE. Changing this value is not yet fully supported.
The optional machine name on which you want to create a service. If omitted, it will use the local machine.
Esempio 1. A win32_create_service() example Any text that describes the purpose of the example, or what goes on in the example should go here (inside the
|
Attempts to delete a service from the SCM database. Administrative privileges are required for this to succeed.
This function really just marks the service for deletion. If other processes (such as the Services Applet) are open, then the deletion will be deferred until those applications are closed. If a service is marked for deletion, further attempts to delete it will fail, and attempts to create a new service with that name will also fail.
The short name of the service.
The optional machine name. If omitted, the local machine will be used.
(PECL)
win32_get_last_control_message -- Returns the last control message that was sent to this serviceReturns the control code that was last sent to this service process. When running as a service you should periodically check this to determine if your service needs to stop running.
Returns a control constant; one of WIN32_SERVICE_CONTROL_CONTINUE, WIN32_SERVICE_CONTROL_INTERROGATE, WIN32_SERVICE_CONTROL_PAUSE, WIN32_SERVICE_CONTROL_STOP, WIN32_SERVICE_CONTROL_HARDWAREPROFILECHANGE, WIN32_SERVICE_CONTROL_POWEREVENT, WIN32_SERVICE_CONTROL_SESSIONCHANGE.
Queries the current status for a service, returning an array of information.
The short name of the service.
The optional machine name. If omitted, the local machine will be used.
Returns FALSE on failure, otherwise returns an array consisting of the following information:
The dwServiceType.
The dwCurrentState.
Which service controls are accepted by the service.
If the service exited, the return code from the process.
If the service exited with an error condition, the service specific code that is logged in the event log is visible here.
If the service is shutting down, holds the current check point number. This is used by the SCM as a kind of heart-beat to detect a wedged service process. The value of the check point is best interpreted in conjunction with the WaitHint value.
If the service is shutting down it will set WaitHint to a checkpoint value that will indicate 100% completion. This can be used to implement a progress indicator.
The windows process identifier. If 0, the process is not running.
The dwServiceFlags.
Informs the SCM of the current status of a running service. This call is only valid for a running service process.
The service status code, one of WIN32_SERVICE_RUNNING, WIN32_SERVICE_STOPPED, WIN32_SERVICE_STOP_PENDING, WIN32_SERVICE_START_PENDING, WIN32_SERVICE_CONTINUE_PENDING, WIN32_SERVICE_PAUSE_PENDING, WIN32_SERVICE_PAUSED.
(PECL)
win32_start_service_ctrl_dispatcher -- Registers the script with the SCM, so that it can act as the service with the given nameWhen launched via the Service Control Manager, a service process is required to "check-in" with it to establish service monitoring and communication facilities. This function performs the check-in by spawning a thread to handle the lower-level communication with the service control manager.
Once started, the service process should continue to check-in with the service control manager so that it can determine if it should terminate. This is achieved by periodically calling win32_get_last_control_message() and handling the return code appropriately.
Esempio 1. A win32_start_service_ctrl_dispatcher() example Any text that describes the purpose of the example, or what goes on in the example should go here (inside the
|
Attempts to start the named service. Usually requires administrative privileges.
The short name of the service.
Optional machine name. If omitted, the local machine is used.
Stops a named service. Requires administrative privileges.
The xattr extension allows for the manipulation of extended attributes on a filesystem.
To use xattr, you will need libattr installed. It is available at http://oss.sgi.com/projects/xfs/.
Nota: These functions only work on filesystems that support extended attributes, and have them enabled at mount time. Some common filesystems that support extended attributes are ext2, ext3, reiserfs, jfs, and xfs.
xattr is currently available through PECL http://pecl.php.net/package/xattr.
If PEAR is available on your *nix-like system you can use the pear installer to install the xattr extension, by the following command: pear -v install xattr.
You can always download the tar.gz package and install xattr by hand:
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.
Set attribute in root (trusted) namespace. Requires root privileges.
Do not follow the symbolic link but operate on symbolic link itself.
Function will fail if extended attribute already exists.
Function will fail if extended attribute doesn't exist.
This function gets the value of an extended attribute of a file.
Extended attributes have two different namespaces: user and root namespace. User namespace is available for all users while root namespace is available only for user with root privileges. xattr operates on user namespace by default, but you can change that using flags argument.
This functions gets a list of names of extended attributes of a file.
Extended attributes have two different namespaces: user and root namespace. User namespace is available for all users while root namespace is available only for user with root privileges. xattr operates on user namespace by default, but you can change that using flags argument.
Esempio 1. Prints names of all extended attributes of file
|
This function removes an extended attribute of a file.
Extended attributes have two different namespaces: user and root namespace. User namespace is available for all users while root namespace is available only for user with root privileges. xattr operates on user namespace by default, but you can change that using flags argument.
This function sets the value of an extended attribute of a file.
Extended attributes have two different namespaces: user and root namespace. User namespace is available for all users while root namespace is available only for user with root privileges. xattr operates on user namespace by default, but you can change that using flags argument.
The file in which we set the attribute.
The name of the extended attribute. This attribute will be created if it doesn't exist or replaced otherwise. You can change this behaviour by using the flags parameter.
The value of the attribute.
Tabella 1. Supported xattr flags
XATTR_CREATE | Function will fail if extended attribute already exists. |
XATTR_REPLACE | Function will fail if extended attribute doesn't exist. |
XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself. |
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges. |
Esempio 1. Sets extended attributes on .wav file
|
This functions checks if the filesystem holding the given file supports extended attributes. Read access to the file is required.
This function returns TRUE if filesystem supports extended attributes, FALSE if it doesn't and NULL if it can't be determined (for example wrong path or lack of permissions to file).
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.
Nota: You'll need at least libxdiff 0.7 for these functions to be aware of memory_limit.
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.
xdiff_file_diff_binary() makes binary diff of files file1 and file2 and stores result in file dest. This function works with both text and binary files. Resulting file is in binary format.
Nota: Both files will be loaded into memory so ensure that your memory_limit is set high enough.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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). Resulting file is human-readable.
Nota: This function doesn't work well with binary files. To make diff of binary files use xdiff_file_diff_binary().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
Esempio 1. xdiff_file_merge3() example The following code merges three files into one.
|
See also xdiff_string_merge3().
xdiff_file_patch_binary() patches file file with binary patch in file patch and stores result in file dest.
Nota: Both files (file and patch) will be loaded into memory so ensure that your memory_limit is set high enough.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. xdiff_file_patch_binary() example The following code applies binary diff to a file.
|
See also xdiff_string_patch_binary().
xdiff_file_patch() patches file file with unified patch in file patch and stores result in file dest.
flags can be either XDIFF_PATCH_NORMAL (default mode, normal patch) or XDIFF_PATCH_REVERSE (reversed patch).
Returns FALSE if an internal error happened, string with rejected chunks of patch or TRUE if patch has been successfully applied.
See also xdiff_string_patch().
xdiff_string_diff_binary() makes binary diff of strings str1 and str2.
Returns string with result or FALSE if an internal error happened.
See also xdiff_file_diff_binary().
xdiff_string_diff() makes unified diff of strings str1 and str2. context indicated how many lines of context you want to include in diff result. Set minimal to TRUE if you want to minimalize size of diff (can take a long time).
Nota: This function doesn't work well with binary strings. To make diff of binary strings use xdiff_string_diff_binary().
Returns string with result or FALSE if an internal error happened.
Esempio 1. xdiff_string_diff() example The following code makes unified diff of two articles.
|
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, FALSE if an internal error happened, or TRUE if merged string is empty.
See also xdiff_file_merge3().
xdiff_string_patch_binary() patches string str with binary patch in string patch.
Returns a patched string.
See also xdiff_file_patch_binary().
xdiff_string_patch() patches string str with unified patch in string patch.
flags can be either XDIFF_PATCH_NORMAL (default mode, normal patch) or XDIFF_PATCH_REVERSE (reversed patch).
If error is passed then rejected parts are stored inside this variable.
Esempio 1. xdiff_string_patch() example The following code applies changes to some article.
|
Returns a patched string.
See also xdiff_file_patch().
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.
Di norma questo modulo utilizza un expat compat layer. Tuttavia si può utilizzare anche expat, che può essere reperito all'indirizzo http://www.jclark.com/xml/expat.html. Il Makefile fornito con expat, per default, non compila la libreria, occorre utilizzare le seguenti istruzioni per il comando make:
libexpat.a: $(OBJS) ar -rc $@ $(OBJS) ranlib $@ |
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 byteQuesta 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.
Nota: La funzione xml_parse_into_struct() restituisce 0 in caso di errore e 1 in caso di successo. Questo non è lo stesso di FALSE e TRUE, fare attenzione con gli operatori tipo ===.
Nell'esempio seguente si illustra la struttura interna delle matrici generata dalla funzione. Qui si userà una semplice struttura con il tag note inserito all'interno del tag para, e quindi si analizzerà questo visualizzando la struttura ottenuta:
Esempio 1. Esempio di uso di xml_parse_into_struct()
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
|
La funzione xml_parse() esegue il parsing di un documento XML. Gli handler configurati per la gestione degli eventi saranno richiamati ogni volta che si renderà necessario.
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.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
In caso di parsing non riuscito, si può recuperare informazioni sull'errore usando xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number() e xml_get_current_byte_index().
Nota: Gli errori nelle entità sono riportati alla fine dei dati questo soltanto se is_final è impostato a TRUE.
(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 in input ed output per il PHP 4. A partire dal PHP 5, la codifica dell'input è determinata automaticamente, pertanto il parametro codifica indica solo dal codifica dell'output. In PHP 4, la codifica di default dell'output è la medesima utilizzata dall'input. Se si indica una stringa vuota, il parser tenta di inviduare la codifica utilizzata per il documento guardando l'intestazione dello stesso. In PHP 5.0.0 a 5.0.1, il set di caratteri di default è l' ISO-8859-1, mentre in PHP 5.0.2 e successivi è UTF-8. Le codifiche supportate sono "ISO-8859-1", "UTF-8" e "US-ASCII".
Vedere anche xml_parser_create() e xml_parser_free().
La funzione xml_parser_create() crea un nuovo parser XML e restituisce un handle da utilizzarsi con le altre funzioni XML.
Il parametro opzionale codifica indica la codifica dei caratteri in input ed output per il PHP 4. A partire dal PHP 5, la codifica dell'input è determinata automaticamente, pertanto il parametro codifica indica solo dal codifica dell'output. In PHP 4, la codifica di default dell'output è la medesima utilizzata dall'input. Se si indica una stringa vuota, il parser tenta di inviduare la codifica utilizzata per il documento guardando l'intestazione dello stesso. In PHP 5.0.0 a 5.0.1, il set di caratteri di default è l' ISO-8859-1, mentre in PHP 5.0.2 e successivi è UTF-8. Le codifiche supportate sono "ISO-8859-1", "UTF-8" e "US-ASCII".
Vedere anche xml_parser_create_ns() e xml_parser_free().
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 option non è valido (viene anche generato un E_WARNING). Altrimenti viene restituito il valore dell'opzione.
Vedere xml_parser_set_option() per l'elenco delle opzioni.
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_SKIP_TAGSTART | integer | Indica quanti caratteri devono essere ignorati dall'inizio del nome del tag. |
XML_OPTION_SKIP_WHITE | integer | Indica se contare anche gli spazi nei caratteri da ignorare. |
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.
(PHP 4 >= 4.0.5, PHP 5)
xml_set_end_namespace_decl_handler -- Valorizza il gestore dello spazio dei nomi
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.
Esempio 1. Esempio di uso di xml_set_object()
|
(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.
Queste funzioni possono essere utilizzate per scrivere client e server XML-RPC. Si possono trovare maggiori informazioni sul XML-RPC in http://www.xmlrpc.com/, e maggiore documentazione su questo modulo e le sue funzioni in http://xmlrpc-epi.sourceforge.net/.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
Per default il modulo XML-RPC non è abilitato in PHP. Per abilitarlo occorre utilizzare il perametro di configurazione --with-xmlrpc[=DIR] in fase di compila del PHP. Questo modulo è rilasciato con il PHP dalla versione 4.1.0.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Parametri di configurazione XML-RPC
Nome | Default | Modificabile | Variazioni |
---|---|---|---|
xmlrpc_errors | "0" | PHP_INI_SYSTEM | Disponibile dal PHP 4.1.0. |
xmlrpc_error_number | "0" | PHP_INI_ALL | Disponibile dal PHP 4.1.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. |
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. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza 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. |
The XMLReader extension is an XML Pull parser. The reader acts as a cursor going forward on the document stream and stopping at each node on the way.
The XMLReader extension is available in PECL for PHP 5.0 and is included in PHP 5.1 by default. It and can be enabled by adding the argument --with--xmlreader to your configure line. The libxml extension is required.
XMLReader->close() - Close the XMLReader input
XMLReader->expand() - Export current node to a DOM node
XMLReader->getAttribute() - Get value of attribute by name
XMLReader->getAttributeNo() - Get value of attribute by position
XMLReader->getAttributeNS() - Get value of attribute by name and URI
XMLReader->getParserProperty() - Indicates if parser property is set or not
XMLReader->isValid() - Indicates if document is valid
XMLReader->lookupNamespace() - Get URI for prefix in scope of node
XMLReader->moveToAttribute() - Positions reader on named attribute
XMLReader->moveToAttributeNo() - Positions reader on attribute by index
XMLReader->moveToAttributeNs() - Position reader on attribute by name and URI
XMLReader->moveToElement() - Move to parent element of current attribute node
XMLReader->moveToFirstAttribute() - Move to first attribute of node
XMLReader->moveToNextAttribute() - Move to next attribute of node
XMLReader->next() - Move to next element skipping children
XMLReader->open() - Set URI to be parsed
XMLReader->read() - Move to next node in stream
XMLReader->setParserProperty() - Set parser property
XMLReader->setRelaxNGSchema() - Set URI of RelaxNG schema to validate against
XMLReader->setRelaxNGSchemaSource() - Set string containing RelaxNG schema to validate against
XMLReader->XML() - Set string of data to be parsed
Tabella 1.
Name | Type | Read-only | Description |
---|---|---|---|
attributeCount | int | yes | The number of attributes on the node |
baseURI | string | yes | The base URI of the node |
depth | int | yes | Depth of the node in the tree starting at 0 |
hasAttributes | bool | yes | Indicates if node has attributes |
hasValue | bool | yes | Indicates if node has a text value |
isDefault | bool | yes | Indicates if attribute is defaulted from DTD |
isEmptyElement | bool | yes | Indicates if node is an empty element tag |
localName | string | yes | The local name of the node |
name | string | yes | The qualified name of the node |
namespaceURI | string | yes | The URI of the namespace associated with the node |
nodeType | int | yes | The node type for the node |
prefix | string | yes | The prefix of the namespace associated with the node |
value | string | yes | The text value of the node |
xmlLang | string | yes | The xml:lang scope which the node resides |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 2. XMLReader Node Types
Constant | Value | Description |
---|---|---|
XMLREADER_NONE (integer) | 0 | No node type |
XMLREADER_ELEMENT (integer) | 1 | Start element |
XMLREADER_ATTRIBUTE (integer) | 2 | Attribute node |
XMLREADER_TEXT (integer) | 3 | Text node |
XMLREADER_CDATA (integer) | 4 | CDATA node |
XMLREADER_ENTITY_REF (integer) | 5 | Entity Reference node |
XMLREADER_ENTITY (integer) | 6 | Entity Declaration node |
XMLREADER_PI (integer) | 7 | Processing Instruction node |
XMLREADER_COMMENT (integer) | 8 | Comment node |
XMLREADER_DOC (integer) | 9 | Document node |
XMLREADER_DOC_TYPE (integer) | 10 | Document Type node |
XMLREADER_DOC_FRAGMENT (integer) | 11 | Document Fragment node |
XMLREADER_NOTATION (integer) | 12 | Notation node |
XMLREADER_WHITESPACE (integer) | 13 | Whitespace node |
XMLREADER_SIGNIFICANT_WHITESPACE (integer) | 14 | Significant Whitespace node |
XMLREADER_END_ELEMENT (integer) | 15 | End Element |
XMLREADER_END_ENTITY (integer) | 16 | End Entity |
XMLREADER_XML_DECLARATION (integer) | 17 | XML Declaration node |
Tabella 3. XMLReader Parser Options
Constant | Value | Description |
---|---|---|
XMLREADER_LOADDTD (integer) | 1 | Load DTD but do not validate |
XMLREADER_DEFAULTATTRS (integer) | 2 | Load DTD and default attributes but do not validate |
XMLREADER_VALIDATE (integer) | 3 | Load DTD and validate while parsing |
XMLREADER_SUBST_ENTITIES (integer) | 4 | Subsitute entities and expand references |
Closes the input the XMLReader object is currently parsing.
(no version information, might be only in CVS)
XMLReader->expand() -- Returns a copy of the current node as a DOM objectThis method copies the current node and returns the appropriate DOM object.
(no version information, might be only in CVS)
XMLReader->getAttribute() -- Get the value of a named attributeReturns the value of a named attribute or an empty string if attribute does not exist or not positioned on an element node.
The value of the attribute, or an empty string if no attribute with the given name is found or not positioned of element.
(no version information, might be only in CVS)
XMLReader->getAttributeNo() -- Get the value of an attribute by indexReturns the value of an attribute based on its position or an empty string if attribute does not exist or not positioned on an element node.
The value of the attribute, or an empty string if no attribute exists at index or not positioned of element.
(no version information, might be only in CVS)
XMLReader->getAttributeNS() -- Get the value of an attribute by localname and URIReturns the value of an attribute by name and namespace URI or an empty string if attribute does not exist or not positioned on an element node.
The value of the attribute, or an empty string if no attribute with the given localName and namespaceURI is found or not positioned of element.
(no version information, might be only in CVS)
XMLReader->getParserProperty() -- Indicates if specified property has been setIndicates if specified property has been set.
(no version information, might be only in CVS)
XMLReader->isValid() -- Indicates if the parsed document is validReturns a boolean indicating if the document being parsed is currently valid.
XMLReader->setParserProperty() |
XMLReader->setRelaxNGSchema() |
XMLReader->setRelaxNGSchemaSource() |
(no version information, might be only in CVS)
XMLReader->lookupNamespace() -- Lookup namespace for a prefixLookup in scope namespace for a given prefix.
(no version information, might be only in CVS)
XMLReader->moveToAttribute() -- Move cursor to a named attributePositions cursor on the named attribute.
XMLReader->moveToElement() |
XMLReader->moveToAttributeNo() |
XMLReader->moveToAttributeNs() |
XMLReader->moveToFirstAttribute() |
(no version information, might be only in CVS)
XMLReader->moveToAttributeNo() -- Move cursor to an attribute by indexPositions cursor on attribute based on its position.
XMLReader->moveToElement() |
XMLReader->moveToAttribute() |
XMLReader->moveToAttributeNs() |
XMLReader->moveToFirstAttribute() |
(no version information, might be only in CVS)
XMLReader->moveToAttributeNs() -- Move cursor to a named attributePositions cursor on the named attribute in specified namespace.
XMLReader->moveToElement() |
XMLReader->moveToAttribute() |
XMLReader->moveToAttributeNo() |
XMLReader->moveToFirstAttribute() |
(no version information, might be only in CVS)
XMLReader->moveToElement() -- Position cursor on the parent Element of current AttributeMoves cursor to the parent Element of current Attribute. Returns TRUE if sucessful and FALSE if it fails or not positioned on Attribute when this method is called.
XMLReader->moveToAttribute() |
XMLReader->moveToAttributeNo() |
XMLReader->moveToAttributeNs() |
XMLReader->moveToFirstAttribute() |
(no version information, might be only in CVS)
XMLReader->moveToFirstAttribute() -- Position cursor on the first AttributeMoves cursor to the first Attribute.
XMLReader->moveToElement() |
XMLReader->moveToAttribute() |
XMLReader->moveToAttributeNo() |
XMLReader->moveToAttributeNs() |
XMLReader->moveToNextAttribute() |
(no version information, might be only in CVS)
XMLReader->moveToNextAttribute() -- Position cursor on the next AttributeMoves cursor to the next Attribute if positioned on an Attribute or moves to first attribute if positioned on an Element.
XMLReader->moveToElement() |
XMLReader->moveToAttribute() |
XMLReader->moveToAttributeNo() |
XMLReader->moveToAttributeNs() |
XMLReader->moveToFirstAttribute() |
(no version information, might be only in CVS)
XMLReader->next() -- Move cursor to next node skipping all subtreesPositions cursor on the next node skipping all subtrees.
(no version information, might be only in CVS)
XMLReader->open() -- Set the URI containing the XML to parseSet the URI containing the XML document to be parsed.
(no version information, might be only in CVS)
XMLReader->setParserProperty() -- Set or Unset parser optionsSet or Unset parser option for the parser. The options must be set after xmlreader-open() or xmlreader-xml() are called and before the first xmlreader-read() call.
One of the parser option constants.
If set to TRUE the option will be enabled otherwise will be disabled.
(no version information, might be only in CVS)
XMLReader->setRelaxNGSchema() -- Set the filename or URI for a RelaxNG SchemaSet the filename or URI for the RelaxNG Schema to use for validation.
(no version information, might be only in CVS)
XMLReader->setRelaxNGSchemaSource() -- Set the data containing a RelaxNG SchemaSet the data containing a RelaxNG Schema to use for validation.
The XSL extension implements the XSL standard, performing XSLT transformations using the libxslt library
This extension uses libxslt which can be found at http://xmlsoft.org/XSLT/. libxslt version 1.0.18 or greater is required.
PHP 5 includes the XSL extension by default and can be enabled by adding the argument --with-xsl[=DIR] to your configure line. DIR is the libxslt installation directory.
XSLTProcessor->getParameter() - Get value of a parameter
XSLTProcessor->hasExsltSupport() - Determine if PHP has EXSLT support
XSLTProcessor->importStylesheet() - Import stylesheet
XSLTProcessor->registerPHPFunctions() - Enables the ability to use PHP functions as XSLT functions
XSLTProcessor->removeParameter() - Remove parameter
XSLTProcessor->setParameter() - Set value for a parameter
XSLTProcessor->transformToDoc() - Transform to DOMDocument
XSLTProcessor->transformToURI() - Transform to URI
XSLTProcessor->transformToXML() - Transform to XML
Many examples in this reference require both an XML and an XSL file. We will use collection.xml and collection.xsl that contains the following:
Esempio 2. collection.xsl
|
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)
XSLTProcessor->__construct() -- Creates a new XSLTProcessor object(no version information, might be only in CVS)
XSLTProcessor->getParameter() -- Get value of a parameterGets a parameter if previously set by XSLTProcessor->setParameter().
The namespace URI of the XSLT parameter.
The local name of the XSLT parameter.
(no version information, might be only in CVS)
XSLTProcessor->hasExsltSupport() -- Determine if PHP has EXSLT supportThis method determine if PHP was built with the EXSLT library.
(no version information, might be only in CVS)
XSLTProcessor->importStylesheet() -- Import stylesheetThis method import the stylesheet into the XSLTProcessor for transformations.
(no version information, might be only in CVS)
XSLTProcessor->registerPHPFunctions() -- Enables the ability to use PHP functions as XSLT functionsThis method enables the ability to use PHP functions as XSLT functions within XSL stylesheets.
Use this parameter to only allow certain functions to be called from XSLT.
This parameter can be either a string (a function name) or an array of functions.
Removes a parameter, if set. This will make the processor use the default value for the parameter as specified in the stylesheet.
The namespace URI of the XSLT parameter.
The local name of the XSLT parameter.
(no version information, might be only in CVS)
XSLTProcessor->setParameter() -- Set value for a parameterSets the value of one or more parameters to be used in subsequent transformations with XSLTProcessor. If the parameter doesn't exist in the stylesheet it will be ignored.
The namespace URI of the XSLT parameter.
The local name of the XSLT parameter.
The new value of the XSLT parameter.
An array of name => value pairs. This syntax is available since PHP 5.1.0.
Esempio 1. Changing the owner before the transformation
|
(no version information, might be only in CVS)
XSLTProcessor->transformToDoc() -- Transform to a DOMDocumentTransforms the source node to a DOMDocument applying the stylesheet given by the XSLTProcessor->importStylesheet() method.
Esempio 1. Transforming to a DOMDocument
Il precedente esempio visualizzerà:
|
Transforms the source node to an URI applying the stylesheet given by the XSLTProcessor->importStylesheet() method.
Esempio 1. Transforming to a HTML file
|
Transforms the source node to a string applying the stylesheet given by the XSLTProcessor->importStylesheet() method.
Esempio 1. Transforming to a string
Il precedente esempio visualizzerà:
|
Questo modulo PHP consiste in un processore, basato su API indipendenti, per le trasformazioni XSLT. Attualmente questo modulo supporta la libreria Sablotron di Ginger Alliance. E' previsto di estendere il supporto ad altre librerie, quali Xalan o le librerie libxslt.
XSLT (Extensible Stylesheet Language (XSL) Transformations) è un linguaggio per trasformare documenti XML in altri documenti XML. E' uno standard definito dal World Wide Web consortium (W3C). Informazioni circa l' XSLT e le relative tecnologie possono essere trovate su http://www.w3.org/TR/xslt.
Nota: Questa estensione è differente dall'estensione sablotron distribuita con le versioni del PHP precedenti PHP 4.1, attualmente è supportata nel PHP 4.1 solo la nuova estensione XSLT. Se hai bisogno di supporto per le vecchie estensioni, fai la tua domanda sulla mailing list php-general@lists.php.net.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.0.0.
Nota: Se occorre il supporto xslt in PHP 5 utilizzare il modulo XSL.
Questo modulo utilizza le librerie Sablotron e expat, che possono essere reperite all'indirizzo http://www.gingerall.com/. E' disponibile sia la versione binaria sia la versione con i sorgenti.
Nei sistemi UNIX, eseguire configure con le opzioni --enable-xslt --with-xslt-sablot. La libreria Sablotron deve essere installata in una posizione accessibile al compilatore.
Accertarsi di utilizzare per il PHP le medesime librerie utilizzate per Sablotron. I parametri di configurazione sono: --with-expat-dir=DIR --with-iconv-dir=DIR. Quando si chiede supporto, ricordarsi di citare sempre queste impostazioni, e dove sono installate altre versioni di queste librerie nel sistema. Ovviemente fornire i numeri di versione.
Attenzione |
Accertarsi che la libreria Sablot sia compilata con -lstdc++ altrimenti potrebbe fallire il processo di configurazione oppure il PHP non essere in grado di caricare la libreria. |
Supporto per JavaScript E-XSLT: Se si compila Sablotron con il supporto JavaScript, occorre indicare il parametro: --with-sablot-js=DIR.
Nota per gli utenti Win32: Per potere abilitare questo modulo sui sistemi Windows, occorre copiare diversi file dalla directory PHP/Win32 del rilascio di PHP alla directory SYSTEM32 della macchina. (Es: C:\WINNT\SYSTEM32 oppure C:\WINDOWS\SYSTEM32). In PHP <= 4.2.0 copiare sablot.dll e expat.dll nella cartella SYSTEM32. In PHP >= 4.2.1 copiare sablot.dll, expat.dll e iconv.dll nella cartella SYSTEM32.
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.
Rimuove i messaggi di log e di errore. Questa è una generica opzione che potrà essere aggiunta in futuro.
Indica a Sablotron di considerare tutte le entità pubbliche. Per default è impostata a off.
Non aggiungere i tag "Content-Type" nell'output HTML. Il default viene impostato in fase di compila di Sablotron.
Sopprime la rimozione degli spazi (solo sui file di dati).
Considera non risolti i documenti (la funzione document() ) non letali.
Codice di errore restituito da scheme handlers.
(PHP 4 >= 4.3.0, PECL)
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.
xslt_backend_version() returns the version number of Sablotron if available, FALSE otherwise.
Crea e restituisce un nuovo processore XSLT risorsa per la modifica dalle altre funzioni XSLT.
Esempio 1. Esempio di utilizzo di xslt_create()
|
Restituisce un codice di errore che descrive l'ultimo errore successo sul processore XSLT indicato.
Returns a string describing the last error that occurred on the passed XSLT processor.
Esempio 1. Handling errors using the xslt_error() and xslt_errno() functions.
|
xslt_getopt() returns the options on the given processor.
La funzione xslt_process() è una delle più importanti della nuova estensione XSLT. Permette di eseguire una trasformazione XSLT usando quasi ogni tipo di fonte per l'input - i contenitori. Questa è un completamento mediante l'uso dell'argomento buffers -- un concetto preso dal processore XSLT Sablotron (attualmente l'unico processore XSLT supportato da questa estensione). Il contenituore di input di default è il nome del file del documento trasformato. Se il contenitore di destinaizone non viene fornito, ad esempio è impostato a NULL - alla la funzione restituisce il risultato.
Avvertimento |
Questa funzione ha modifica i propri argomenti dalla versione 4.0.6. Infatti non fornire più il contenuto XML o XSL come secondi e terzi argomenti, poichè questi creano un segmentation fault in Sablotron fino alla versione 0.95 inclusa. |
I contenitori possono essere impostati anche tramite la matrice $arguments (vedere più avanti).
Il più semplice tipo di trasformazione con la funzione xslt_process() è la trasformazione di un file XML con un file XSLT, mettendo il risultato in un terzo file contenente un nuovo documento XML (o HTML). Fare questo con Sablotron è davvero molto semplice...
Esempio 1. Uso di xslt_process() per trasformare un file XML e un file XSL in un nuovo file XML
|
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() rappresenta una matrice di qualsiasi parametro di alto livello che si desidera passare al documento XSLT. Questi parametri possono essere referenziati dal file XSL utilizzando l'istruzione <xsl:param name="parameter_name">. I parametri devono avere la codifica UTF-8 ed i rispettivi valori devono essere interpretati come stringhe dal processore Sablotron. In altre parole non si possono passare come parametri al documento XSLT dei node-set.
Esempio 4. Passaggio di variabili PHP al file XSL
Il precedente esempio visualizzerà:
|
Nota: Please note that file:// is needed in front of path if you use Windows.
Imposta l'URI di base per tutte le trasformazioni XSLT, l'URI di base è usato con le istruzioni Xpath per la risoluzione di document() e di altri comandi che accedono a risorse esterne. Viene utilizzato, inoltre, per risolvere gli URI degli elementi <xsl:include> ed <xsl:import>
Dalla versione 4.3, la base di default per l'URI è la directory di esecuzione dello script. Infatti è la directory indicata dalla costante __FILE__. Prima delle versione 4.3, la base di default per l'URI era meno prevedibile.
Nota: Please note that file:// is needed in front of path if you use Windows.
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).
La funzione utente deve ricevere quattro parametri: il processore XSLT,
il livello di errore, il codice di errore ed una matrice di messaggi. La funzione
potrebbe essere rappresentata come:
error_handler ( resource xh, int error_level, int error_code, array messages )
Esempio 1. Esempio di uso di xslt_set_error_handler()
Il precedente esempio visualizzerà qualcosa simile a:
|
Vedere xslt_set_object() se si desidera utilizzare come handler un medoto di un oggetto.
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:
Nota: Please note that file:// is needed in front of path if you use Windows.
This function allows to use the processor inside an object and to resolve all callback functions in it.
The callback functions can be declared with xml_set_sax_handlers(), xslt_set_scheme_handlers() or xslt_set_error_handler() and are assumed to be methods of object.
Esempio 1. Using your own error handler as a method
|
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, PECL)
xslt_set_sax_handlers -- Imposta gli handler SAX da richiamare quando il document XML viene processatoxslt_set_sax_handlers() registra gli handlers SAX per il documento, dato processor XSLT.
Il parametro handlers dovrebbe essere una matrice del seguente formato:
<?php $handlers = array( "document" => array( "start_doc", "end_doc"), "element" => array( "start_element", "end_element"), "namespace" => array( "start_namespace", "end_namespace"), "comment" => "comment", "pi" => "pi", "character" => "characters" ); ?> |
Nota: La matrice fornita non richiede di essere completa di tutti i differenti handler agli elementi sax (sebbene possa esserlo), ma richiede solo di essere conforme al formato "handler" => "function" descritto in precedenza.
Chiascuno degli handler SAX sono nel formato:
start_doc ( resource processor )
end_doc ( resource processor )
start_element ( resource processor, string name, array attributes )
end_element ( resource processor, string name )
start_namespace ( resource processor, string prefix, string uri )
end_namespace ( resource processor, string prefix )
comment ( resource processor, string contents )
pi ( resource processor, string target, string contents )
characters ( resource processor, string contents )
L'utilizzo di xslt_set_sax_handlers() non è molto differente rispetto ad un parser SAX tipo xml_parse() nelle trasformazioni xslt_process().
Esempio 1. Esempio di uso xslt_set_sax_handlers()
|
Si può anche utilizzare xslt_set_object() per implementare i propri handler in un oggetto.
Esempio 2. Handler orientato agli oggetti
Entrambi gli esempi visualizzeranno:
|
(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):
(PHP 4 >= 4.0.6, PECL)
xslt_set_scheme_handlers -- Imposta lo schema degli handler per un processore XSLT
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
xslt_setopt() sets the options specified by newmask on the given processor. Returns the number of previous mask is possible, TRUE otherwise, FALSE in case of an error.
newmask is a bitmask constructed with the following constants:
XSLT_SABOPT_PARSE_PUBLIC_ENTITIES - Tell the processor to parse public entities. By default this has been turned off.
XSLT_SABOPT_DISABLE_ADDING_META - Do not add the meta tag "Content-Type" for HTML output. The default is set during the compilation of the processor.
XSLT_SABOPT_DISABLE_STRIPPING - Suppress the whitespace stripping (on data files only).
XSLT_SABOPT_IGNORE_DOC_NOT_FOUND - Consider unresolved documents (the document() function) non-lethal.
This extension offers a PHP interface to the YAZ toolkit that implements the Z39.50 Protocol for Information Retrieval. With this extension you can easily implement a Z39.50 origin (client) that searches or scans Z39.50 targets (servers) in parallel.
The module hides most of the complexity of Z39.50 so it should be fairly easy to use. It supports persistent stateless connections very similar to those offered by the various RDB APIs that are available for PHP. This means that sessions are stateless but shared among users, thus saving the connect and initialize phase steps in most cases.
YAZ is available at http://www.indexdata.dk/yaz/. You can find news information, example scripts, etc. for this extension at http://www.indexdata.dk/phpyaz/.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.0.0.
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, YAZ oppure Cyrus. 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 | Changelog |
---|---|---|---|
yaz.max_links | "100" | PHP_INI_ALL | Available since PHP 4.3.0. |
yaz.log_file | NULL | PHP_INI_ALL | Available since PHP 4.3.0. |
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 information for the last request on the server.
With some servers, this function may return the same string as yaz_error().
A string containing additional error information or an empty string if the last operation was successful or if no additional information was provided by the server.
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.
The connection resource returned by yaz_connect().
An array of configuration. Each key of the array is the name of a CCL field and the corresponding value holds a string that specifies a mapping to RPN.
The mapping is a sequence of attribute-type, attribute-value pairs. Attribute-type and attribute-value is separated by an equal sign (=). Each pair is separated by white space.
Additional information can be found on the CCL page.
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.
The connection resource returned by yaz_connect().
The CCL FIND query.
If the function was executed successfully, this will be an array containing the valid RPN query under the key rpn.
Upon failure, three indexes are set in this array to indicate the cause of failure:
errorcode - the CCL error code (integer)
errorstring - the CCL error string
errorpos - approximate position in query of failure (integer is character position)
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.
Nota: This function will only close a non-persistent connection opened by setting the persistent option to FALSE with yaz_connect().
This function returns a connection resource on success, zero on failure.
yaz_connect() prepares for a connection to a Z39.50 server. This function is non-blocking and does not attempt to establish a connection - it merely prepares a connect to be performed later when yaz_wait() is called.
Nota: The YAZ proxy is a freely available Z39.50 proxy.
A string that takes the form host[:port][/database]. If port is omitted, port 210 is used. If database is omitted Default is used.
If given as a string, it is treated as the Z39.50 V2 authentication string (OpenAuth).
If given as an array, the contents of the array serves as options.
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.
Nota: If you open a persistent connection, you won't be able to close it later with yaz_close().
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.
This function allows you to change databases within a session by specifying one or more databases to be used in search, retrieval, etc. - overriding databases specified in call to yaz_connect().
The connection resource returned by yaz_connect().
A string containing one or more databases. Multiple databases are separated by a plus sign +.
This function sets the element set name for retrieval.
Call this function before yaz_search() or yaz_present() to specify the element set name for records to be retrieved.
Nota: If this function seems effectless, see the description of the piggybacking option in yaz_connect().
The connection resource returned by yaz_connect().
Most servers support F (for full records) and B (for brief records).
Returns an error number for the server (last request) identified by id.
yaz_errno() should be called after network activity for each server - (after yaz_wait() returns) to determine the success or failure of the last operation (e.g. search).
Returns an error code. The error code is either a Z39.50 diagnostic code (usually a Bib-1 diagnostic) or a client side error code which is generated by PHP/YAZ itself, such as "Connect failed", "Init Rejected", etc.
yaz_error() returns an English text message corresponding to the last error number as returned by yaz_errno().
Returns an error text message for server (last request), identified by parameter id. An empty string is returned if the last operation was successful.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Returns the value of the option specified with name.
Returns the value of the specified option or an empty string if the option wasn't set.
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 connection resource returned by yaz_connect().
Must be an associative array with information about the Item Order request to be sent. The key of the hash is the name of the corresponding ASN.1 tag path. For example, the ISBN below the Item-ID has the key item-id,ISBN.
The ILL-Request parameters are:
protocol-version-num
transaction-id,initial-requester-id,person-or-institution-symbol,person
transaction-id,initial-requester-id,person-or-institution-symbol,institution
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-person
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-institution
transaction-id,transaction-group-qualifier
transaction-id,transaction-qualifier
transaction-id,sub-transaction-qualifier
service-date-time,this,date
service-date-time,this,time
service-date-time,original,date
service-date-time,original,time
requester-id,person-or-institution-symbol,person
requester-id,person-or-institution-symbol,institution
requester-id,name-of-person-or-institution,name-of-person
requester-id,name-of-person-or-institution,name-of-institution
responder-id,person-or-institution-symbol,person
responder-id,person-or-institution-symbol,institution
responder-id,name-of-person-or-institution,name-of-person
responder-id,name-of-person-or-institution,name-of-institution
transaction-type
delivery-address,postal-address,name-of-person-or-institution,name-of-person
delivery-address,postal-address,name-of-person-or-institution,name-of-institution
delivery-address,postal-address,extended-postal-delivery-address
delivery-address,postal-address,street-and-number
delivery-address,postal-address,post-office-box
delivery-address,postal-address,city
delivery-address,postal-address,region
delivery-address,postal-address,country
delivery-address,postal-address,postal-code
delivery-address,electronic-address,telecom-service-identifier
delivery-address,electronic-address,telecom-service-addreess
billing-address,postal-address,name-of-person-or-institution,name-of-person
billing-address,postal-address,name-of-person-or-institution,name-of-institution
billing-address,postal-address,extended-postal-delivery-address
billing-address,postal-address,street-and-number
billing-address,postal-address,post-office-box
billing-address,postal-address,city
billing-address,postal-address,region
billing-address,postal-address,country
billing-address,postal-address,postal-code
billing-address,electronic-address,telecom-service-identifier
billing-address,electronic-address,telecom-service-addreess
ill-service-type
requester-optional-messages,can-send-RECEIVED
requester-optional-messages,can-send-RETURNED
requester-optional-messages,requester-SHIPPED
requester-optional-messages,requester-CHECKED-IN
search-type,level-of-service
search-type,need-before-date
search-type,expiry-date
search-type,expiry-flag
place-on-hold
client-id,client-name
client-id,client-status
client-id,client-identifier
item-id,item-type
item-id,call-number
item-id,author
item-id,title
item-id,sub-title
item-id,sponsoring-body
item-id,place-of-publication
item-id,publisher
item-id,series-title-number
item-id,volume-issue
item-id,edition
item-id,publication-date
item-id,publication-date-of-component
item-id,author-of-article
item-id,title-of-article
item-id,pagination
item-id,ISBN
item-id,ISSN
item-id,additional-no-letters
item-id,verification-reference-source
copyright-complicance
retry-flag
forward-flag
requester-note
forward-note
There are also a few parameters that are part of the Extended Services Request package and the ItemOrder package:
package-name
user-id
contact-name
contact-phone
contact-email
itemorder-item
This function prepares for retrieval of records after a successful search.
The yaz_range() function should be called prior to this function to specify the range of records to be retrieved.
Specifies a range of records to retrieve.
This function should be called before yaz_search() or yaz_present().
The connection resource returned by yaz_connect().
Specifies the position of the first record to be retrieved. The records numbers goes from 1 to yaz_hits().
Specifies the number of records to be retrieved.
The yaz_record() function inspects a record in the current result set at the position specified by parameter pos.
The connection resource returned by yaz_connect().
The record position. Records 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.
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).
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 afterwards.
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).
Returns the record at position pos or an empty string if no record exists at the given position.
If no database record exists at the given position an empty string is returned.
Esempio 1. Array for GRS-1 record Consider this 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 PHP 5 the XSL extension must 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().
The connection resource returned by yaz_connect().
If given, this array will be modified to hold additional information taken from the Scan Response:
number - Number of entries returned
stepsize - Step size
position - Position of term
status - Scan status
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.
This function prepares for a Z39.50 Scan Request on the specified connection.
To actually transfer the Scan Request to the server and receive the Scan Response, yaz_wait() must be called. Upon completion of yaz_wait() call yaz_error() and yaz_scan_result() to handle the response.
The connection resource returned by yaz_connect().
Currently only type rpn is supported.
Starting term point for the scan.
The form in which the starting term is specified is given by parameter type.
The syntax this parameter is similar to the RPN query as described in yaz_search(). It consists of zero or more @attr-operator specifications, then followed by exactly one token.
This optional parameter specifies additional information to control the behaviour of the scan request. Three indexes are currently read from the flags array: number (number of terms requested), position (preferred position of term) and stepSize (preferred step size).
Esempio 1. PHP function that scans titles
|
yaz_schema() specifies the schema for retrieval.
This function should be called before yaz_search() or yaz_present().
The connection resource returned by yaz_connect().
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, ...
yaz_search() prepares for a search on the given connection.
Like yaz_connect() this function is non-blocking and only prepares for a search to be executed later when yaz_wait() is called.
The connection resource returned by yaz_connect().
This parameter represents the query type - only "rpn" is supported now in which case the third argument specifies a Type-1 query in prefix query notation.
The RPN query is a textual representation of the Type-1 query as defined by the Z39.50 standard. However, in the text representation as used by YAZ a prefix notation is used, that is the operator precedes the operands. The query string is a sequence of tokens where white space is ignored unless surrounded by double quotes. Tokens beginning with an at-character (@) are considered operators, otherwise they are treated as search terms.
Tabella 1. RPN Operators
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. |
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().
Esempio 1. Query Examples You can search for simple terms, like this:
The query
This query applies two attributes for the same phrase.
The query
Another, more complex, one:
|
Sets one or more options on the given connection.
The connection resource returned by yaz_connect().
May be either a string or an array.
If given as a string, this will be the name of the option to set. You'll need to give it's value.
If given as an array, this will be an associative array (option name => option value).
Tabella 1. PHP/YAZ Connection Options
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(). |
The new value of the option. Use this only if the previous argument is a string.
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 connection resource returned by yaz_connect().
A string that takes the form field1 flags1 field2 flags2 where field1 specifies the primary attributes for sort, field2 seconds, etc..
The field specifies either a numerical attribute combinations consisting of type=value pairs separated by comma (e.g. 1=4,2=1) ; or the field may specify a plain string criteria (e.g. title. The flags is a sequence of the following characters which may not be separated by any white space.
Sort Flags
Sort ascending
Sort descending
Case insensitive sorting
Case sensitive sorting
yaz_syntax() specifies the preferred record syntax for retrieval
This function should be called before yaz_search() or yaz_present().
The connection resource returned by yaz_connect().
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 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).
NIS (formerly called Yellow Pages) allows network management of important administrative files (e.g. the password file). For more information refer to the NIS manpage and The Linux NIS(YP)/NYS/NIS+ HOWTO. There is also a book called Managing NFS and NIS by Hal Stern.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.1.0.
Nota: Questo modulo non è disponibile su piattaforme Windows.
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 <= 5.0.4)
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().
(PHP 3 >= 3.0.7, PHP 4, PHP 5 <= 5.0.4)
yp_first -- Returns the first key-value pair from the named mapyp_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().
(PHP 3 >= 3.0.7, PHP 4, PHP 5 <= 5.0.4)
yp_get_default_domain -- Fetches the machine's default NIS domainyp_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 <= 5.0.4)
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 abilita l'accesso trasperente in lettura degli archivi compressi con ZIP e dei file in essi contenuti.
Questo modulo usa le funzioni ZZIPlib della libreria di Guido Draheim. Sono richieste le ZZIPlib versione >= 0.10.6.
Notare che ZZIPlib rende disponbili solo un sottogruppo di quelle funzioni disponibili in una implementazione completa dell'algoritmo di compressione ZIP e può solamente leggere i file in formato ZIP. Una normale utility ZIP è richiesta per creare i file ZIP letti da questa libreria.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/zip.
In PHP 4 this PECL extensions source can be found in the ext/ directory within the PHP source or at the PECL link above. Per utilizzare questo modulo è necessario usare l'opzione di configurazione --with-zip[=DIR] durante la compilazione di PHP.
Per utilizzare queste funzioni, gli utenti Windows dovranno abilitare php_zip.dll all'interno del php.ini. In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Nota: Il supporto Zip precedentemente alla versione 4.1.0 di PHP è sperimentale. Questa sezione riflette l'estensione Zip così come essa esiste in PHP 4.1.0 e successivi.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
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, PECL)
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_... oppure FALSE se non vi sono più files da leggere.
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().
The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().
Returns TRUE if the gz-file pointer is at EOF or an error occurs; otherwise returns FALSE.
This function is identical to readgzfile(), except that it returns the file in an array.
The file name.
You can set this optional parameter to 1, if you want to search for the file in the include_path too.
Returns a string containing a single (uncompressed) character read from the given gz-file pointer.
The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().
Gets a (uncompressed) string of up to length - 1 bytes read from the given file pointer. Reading ends when length - 1 bytes have been read, on a newline, or on EOF (whichever comes first).
The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().
The length of data to get.
Identical to gzgets(), except that gzgetss() attempts to strip any HTML and PHP tags from the text it reads.
The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().
The length of data to get.
You can use this optional parameter to specify tags which should not be stripped.
The data compressed by gzdeflate().
The maximum length of data to decode.
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.
Opens a gzip (.gz) file for reading or writing.
gzopen() can be used to read a file which is not in gzip format; in this case gzread() will directly read from the file without decompression.
The file name.
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.)
You can set this optional parameter to 1, if you want to search for the file in the include_path too.
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.
Reads to EOF on the given gz-file pointer from the current position and writes the (uncompressed) results to standard output.
Nota: You may need to call gzrewind() to reset the file pointer to the beginning of the file if you have already written data to it.
Suggerimento: If you just want to dump the contents of a file to the output buffer, without first modifying it or seeking to a particular offset, you may want to use the readgzfile() function, which saves you the gzopen() call.
The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().
The number of uncompressed characters read from gz and passed through to the input, or FALSE on error.
gzread() reads up to length bytes from the given gz-file pointer. Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.
The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().
The number of bytes to read.
Sets the file position indicator of the given gz-file pointer to the beginning of the file stream.
The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().
Sets the file position indicator for the given file pointer to the given offset byte into the file stream. Equivalent to calling (in C) gzseek(zp, offset, SEEK_SET).
If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek() then compresses a sequence of zeroes up to the new starting position.
The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().
The seeked offset.
Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.
Gets the position of the given file pointer; i.e., its offset into the file stream.
The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().
This function uncompress a compressed string.
The data compressed by gzcompress().
The maximum length of data to decode.
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.
gzwrite() writes the contents of string to the given gz-file.
The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().
The string to write.
The number of uncompressed bytes to write. If supplied, writing will stop after length (uncompressed) bytes have been written or the end of string is reached, whichever comes first.
Nota: Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.
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.
The file name. This file will be opened from the filesystem and its contents written to standard output.
You can set this optional parameter to 1, if you want to search for the file in the include_path too.
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.
If you are about to begin developing PHP or Zend extensions, you need to prepare yourself for the programming environment provided by the various APIs. This part of the documentation tries to introduce the APIs provided by the different PHP and Zend Engine versions available. Since most of the information available here is somewhat outdated, you'll want to read various files found in the PHP source, files such as README.SELF-CONTAINED-EXTENSIONS and README.EXT_SKEL in addition to the manual.
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 44-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 44-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 44-2. How to accept a stream as a parameter
|
Esempio 44-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 44-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 44-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 44-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 44-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 Stream Contexts.
(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.
(no version information, might be only in CVS)
struct php_stream_statbuf -- Holds information about a file or URL(no version information, might be only in CVS)
struct php_stream_dirent -- Holds information about a single file during dir scanning
|
d_name
holds the name of the file, relative to the directory
being scanned.
(no version information, might be only in CVS)
struct php_stream_ops -- Holds member functions for a stream implementationtypedef 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; |
(no version information, might be only in CVS)
struct php_stream_wrapper -- Holds wrapper properties and pointer to operationsstruct _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; |
(no version information, might be only in CVS)
struct php_stream_wrapper_ops -- Holds member functions for a stream wrapper implementationtypedef 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; |
(no version information, might be only in CVS)
struct php_stream_filter -- Holds filter properties and pointer to operationsstruct _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; |
(no version information, might be only in CVS)
struct php_stream_filter_ops -- Holds member functions for a stream filter implementationtypedef 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; |
(no version information, might be only in CVS)
Stream open options -- Affects the operation of stream factory functionsOne 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.
The original version of this PDO driver specification was written by Bill Abt and Rick McGuire of IBM and contributed to the PHP community to assist in the development of drivers for more databases and to encourage the emerging standard for database access in PHP.
The following is list of prerequisites and assumptions needed for writing a PDO database driver:
A working target database, examples, demos, etc. working as per vendor specifications;
A working development environment:
Other Unix: standard development tools supplied by vendor plus the GNU development tool set;
Win32: Visual Studio compiler suite;
Linux: standard development tools, gcc, ld, make, autoconf, automake, etc., versions dependent on distribution;
A working PHP environment version 5.0.3 or higher with a working PEAR extension version 1.3.5 or higher;
A working PDO environment (can be installed using 'sudo pear install PDO'), including the headers which will be needed to access the PDO type definitions and function declarations;
A good working knowledge of the 'C' programming language;
A good working knowledge of the way to write a PHP extension; George Schlossnagle's Advanced PHP Programming (published by Developer's Library, chapters 21 and 22) is recommended;
Finally, a familiarity with the Zend API that forms the heart of PHP, in particular paying attention to the memory management aspects.
The source directory for a typical PDO driver is laid out as follows, where SKEL represents a shortened form of the name of the database that the driver is going to connect to. Even though SKEL is presented here in uppercase (for clarity), the convention is to use lowercase characters.
pdo_SKEL/ config.m4 |
The contents of these files are defined later in this document.
The easiest way to get started is to use the ext_skel shell script found in the PHP build tree in the ext directory. This will build a skeleton directory containing a lot of the files listed above. It can be build by executing the following command from within the ext directory:
./ext_skel --extname=pdo_SKEL |
This will generate a directory called pdo_SKEL containing the skeleton files that you can then modify. This directory should then be moved out of the php extension directory . PDO is a PECL extension and should not be included in the standard extension directory. As long as you have PHP and PDO installed, you should be able to build from any directory.
The header file config.h is generated by the configure process for the platform for the which the driver is being built. If this header is present, the HAVE_CONFIG_H compiler variable is set. This variable should be tested for and if set, the file config.h should be included in the compilation unit.
The following standard public php headers should be included in each source module:
php.h
php_ini.h
ext/standard/info.h
The following standard public PDO header files are also included in each source module:
This header file contains definitions of the initialization and shutdown functions in the main driver as well as definitions of global PDO variables.
This header contains the types and API contracts that are used to write a PDO driver. It also contains method signature for calling back into the PDO layer and registering/unregistering your driver with PDO. Most importantly, this header file contains the type definitions for PDO database handles and statements. The two main structures a driver has to deal with, pdo_dbh_t and pdo_stmt_t, are described in more detail in Appendix A and B.
The typical PDO driver has two header files that are specific to the database implementation. This does not preclude the use of more depending on the implementation. The following two headers are, by convention, standard:
This header file is virtually an exact duplicate in functionality and content of the previously defined pdo/php_pdo.h that has been specifically tailored for your database. If your driver requires the use of global variables they should be defined using the ZEND_BEGIN_MODULE_GLOBALS and ZEND_END_MODULE_GLOBALS macros. Macros are then used to access these variables. This macro is usually named PDO_SKEL_G(v) where v is global variable to be accessed. Consult the Zend programmer documentation for more information.
This header file typically contains type definitions and function declarations specific to the driver implementation. It also should contain the db specicfic definitions of a pdo_SKEL_handle and pdo_SKEL_stmt structures. These are the names of the private data structures that are then referenced by the driver_data members of the handle and statement structures.
Depending on the implementation details for a particular driver it may be necessary to include the following header:
#include <zend_exceptions.h> |
The major structures, pdo_dbh_t and pdo_stmt_t are defined and explained in Appendix A and B respectively. Database and Statement attributes are defined in Appendix C. Error handling is explained in Appendix D.
static function_entry pdo_SKEL_functions[] = { { NULL, NULL, NULL } }; |
This structure is used to register functions into the global php function namespace. PDO drivers should try to avoid doing this, so it is recommended that you leave this structure initialized to NULL, as shown in the synopsis above.
/* {{{ pdo_SKEL_module_entry */ #if ZEND_EXTENSION_API_NO >= 220050617 static zend_module_dep pdo_SKEL_deps[] = { ZEND_MOD_REQUIRED("pdo") {NULL, NULL, NULL} }; #endif /* }}} */ zend_module_entry pdo_SKEL_module_entry = { #if ZEND_EXTENSION_API_NO >= 220050617 STANDARD_MODULE_HEADER_EX, NULL, pdo_SKEL_deps, #else STANDARD_MODULE_HEADER, #endif "pdo_SKEL", pdo_SKEL_functions, PHP_MINIT(pdo_SKEL), PHP_MSHUTDOWN(pdo_SKEL), NULL, NULL, PHP_MINFO(pdo_SKEL), PHP_PDO_<DB>_MODULE_VERSION, STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_PDO_<DB> ZEND_GET_MODULE(pdo_db) #endif |
A structure of type zend_module_entry called pdo_SKEL_module_entry must be declared and should include reference to the pdo_SKEL_functions table defined previously.
/* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(pdo_SKEL) { return php_pdo_register_driver(&pdo_SKEL_driver); } /* }}} */ |
This standard PHP extension function should be used to register your driver with the PDO layer. This is done by calling the php_pdo_register_driver() function passing a pointer to a structure of type pdo_driver_t typically named pdo_SKEL_driver. A pdo_driver_t contains a header that is generated using the PDO_DRIVER_HEADER(SKEL) macro and pdo_SKEL_handle_factory() function pointer. The actual function is described during the discussion of the SKEL_dbh.c unit.
/* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(pdo_SKEL) { php_pdo_unregister_driver(&pdo_SKEL_driver); return SUCCESS; } /* }}} */ |
This standard PHP extension function is used to unregister your driver from the PDO layer. This is done by calling the php_pdo_unregister_driver() function, passing the same pdo_SKEL_driver structure that was passed in the init function above.
This is again a standard PHP extension function. Its purpose is to display information regarding the module when the phpinfo() is called from a script. The convention is to display the version of the module and also what version of the db you are dependent on, along with any other configuration style information that might be relevant.
This unit implements all of the database handling methods that support the PDO database handle object. It also contains the error fetching routines. All of these functions will typically need to access the global variable pool. Therefore, it is necessary to use the Zend macro TSRMLS_DC macro at the end of each of these statements. Consult the Zend programmer documentation for more information on this macro.
static int pdo_SKEL_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt, const char *file, int line TSRMLS_DC) |
The purpose of this function is to be used as a generic error handling function within the driver. It is called by the driver when an error occurs within the driver. If an error occurs that is not related to SQLSTATE, the driver should set either dbh->error_code or stmt->error_code to an SQLSTATE that most closely matches the error or the generic SQLSTATE error "HY000". The file pdo_sqlstate.c in the PDO source contains a table of commonly used SQLSTATE codes that the PDO code explicitly recognizes. This setting of the error code should be done prior to calling this function.; This function should set the global pdo_err variable to the error found in either the dbh or the stmt (if the variable stmt is not NULL).
Pointer to the database handle initialized by the handle factory
Pointer to the current statement or NULL. If NULL, the error is derived by error code found in the dbh.
The source file where the error occurred or NULL if not available.
The line number within the source file if available.
If the dbh member methods is NULL (which implies that the error is being raised from within the PDO constructor), this function should call the zend_throw_exception_ex() function otherwise it should return the error code. This function is usually called using a helper macro that customizes the calling sequence for either database handling errors or statement handling errors.
For more info on error handling, see la Sezione Error handling.
Nota: Despite being documented here, the PDO driver interface does not specify that his function be present; it is merely a convenient way to handle errors, and it just happens to be equally convenient for the majority of database client library APIs to structure your driver implementation in this way.
static int pdo_SKEL_fetch_error_func(pdo_dbh_t *dbh, pdo_stmt_t *stmt, zval *info TSRMLS_DC) |
The purpose of this function is to obtain additional information about the last error that was triggered. This includes the driver specific error code and a human readable string. It may also include additional information if appropriate. This function is called as a result of the PHP script calling the PDO::errorInfo() method.
Pointer to the database handle initialized by the handle factory
Pointer to the most current statement or NULL. If NULL, the error translated is derived by error code found in the dbh.
A hash table containing error codes and messages.
The error_func should return two pieces of information as successive array elements. The first item is expected to be a numeric error code, the second item is a descriptive string. The best way to set this item is by using add_next_index. Note that the type of the first argument need not be long; use whichever type most closely matches the error code returned by the underlying database API.
/* now add the error information. */ /* These need to be added in a specific order */ add_next_index_long(info, error_code); /* driver specific error code */ add_next_index_string(info, message, 0); /* readable error message */ |
This function should return 1 if information is available, 0 if the driver does not have additional info.
static int SKEL_handle_closer(pdo_dbh_t *dbh TSRMLS_DC) |
This function will be called by PDO to close an open database.
Pointer to the database handle initialized by the handle factory
This should do whatever database specific activity that needs to be accomplished to close the open database. PDO ignores the return value from this function.
static int SKEL_handle_preparer(pdo_dbh_t *dbh, const char *sql, long sql_len, pdo_stmt_t *stmt, zval *driver_options TSRMLS_DC) |
This function will be called by PDO in response to PDO::query() and PDO::prepare() calls from the PHP script. The purpose of the function is to prepare raw SQL for execution, storing whatever state is appropriate into the stmt that is passed in.
Pointer to the database handle initialized by the handle factory
Pointer to a character string containing the SQL statement to be prepared.
The length of the SQL statement.
Pointer to the returned statement or NULL if an error occurs.
Any driver specific/defined options.
This function is essentially the constructor for a stmt object. This function is responsible for processing statement options, and setting driver-specific option fields in the pdo_stmt_t structure.
PDO does not process any statement options on the driver's behalf before calling the preparer function. It is your responsibility to process them before you return, raising an error for any unknown options that are passed.
One very important responsibility of this function is the processing of SQL statement parameters. At the time of this call, PDO does not if your driver supports binding parameters into prepared statements, nor does it know if it supports named or positional parameter naming conventions.
Your driver is responsible for setting stmt->supports_placeholders as appropriate for the underlying database. This may involved some run-time determination on the part of your driver, if this setting depends on the version of the database server to which it is connected. If your driver doesn't directly support both named and positional parameter conventions, you should use the pdo_parse_params() API to have PDO rewrite the query to take advantage of the support provided by your database.
Esempio 45-2. Using pdo_parse_params
|
Possible values for supports_placeholders are: PDO_PLACEHOLDER_NAMED, PDO_PLACEHOLDER_POSITIONAL and PDO_PLACEHOLDER_NONE. If the driver doesn't support prepare statements at all, then this function should simply allocate any state that it might need, and then return:
Esempio 45-3. implementing preparer for drivers that don't support native prepared statements
|
This function returns 1 on success or 0 on failure.
static long SKEL_handle_doer(pdo_dbh_t *dbh, const char *sql, long sql_len TSRMLS_DC) |
This function will be called by PDO to execute a raw SQL statement. No pdo_stmt_t is created.
Pointer to the database handle initialized by the handle factory
Pointer to a character string containing the SQL statement to be prepared.
The length of the SQL statement.
This function returns 1 on success or 0 on failure.
static int SKEL_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, int unquoted_len, char **quoted, int quoted_len, enum pdo_param_type param_type TSRMLS_DC) |
This function will be called by PDO to turn an unquoted string into a quoted string for use in a query.
Pointer to the database handle initialized by the handle factory
Pointer to a character string containing the string to be quoted.
The length of the string to be quoted.
Pointer to the address where a pointer to the newly quoted string will be returned.
The length of the new string.
A driver specific hint for driver that have alternate quoting styles
This function is called in response to a call to PDO::quote() or when the driver has set supports_placeholder to PDO_PLACEHOLDER_NONE. The purpose is to quote a parameter when building SQL statements.
If your driver does not support native prepared statements, implementation of this function is required.
This function returns 1 if the quoting process reformatted the string, and 0 if it was not necessary to change the string. The original string will be used unchanged with a 0 return.
static int SKEL_handle_begin(pdo_dbh_t *dbh TSRMLS_DC) |
This function will be called by PDO to begin a database transaction.
Pointer to the database handle initialized by the handle factory
This should do whatever database specific activity that needs to be accomplished to begin a transaction. This function returns 1 for success or 0 if an error occurred.
static int SKEL_handle_commit(pdo_dbh_t *dbh TSRMLS_DC) |
This function will be called by PDO to end a database transaction.
Pointer to the database handle initialized by the handle factory
This should do whatever database specific activity that needs to be accomplished to commit a transaction. This function returns 1 for success or 0 if an error occurred.
static int SKEL_handle_rollback( pdo_dbh_t *dbh TSRMLS_DC) |
This function will be called by PDO to rollback a database transaction.
Pointer to the database handle initialized by the handle factory
This should do whatever database specific activity that needs to be accomplished to rollback a transaction. This function returns 1 for success or 0 if an error occurred.
static int SKEL_handle_get_attribute(pdo_dbh_t *dbh, long attr, zval *return_value TSRMLS_DC) |
This function will be called by PDO to retrieve a database attribute.
Pointer to the database handle initialized by the handle factory
long value of one of the PDO_ATTR_xxxx types. See Tabella 45-1 for valid attributes.
The returned value for the attribute.
It is up to the driver to decide which attributes will be supported for a particular implementation. It is not necessary for a driver to supply this function. PDO driver handles the PDO_ATTR_PERSISTENT, PDO_ATTR_CASE, PDO_ATTR_ORACLE_NULLS, and PDO_ATTR_ERRMODE attributes directly.
This function returns 1 on success or 0 on failure.
static int SKEL_handle_set_attribute(pdo_dbh_t *dbh, long attr, zval *val TSRMLS_DC) |
This function will be called by PDO to set a database attribute, usually in response to a script calling PDO::setAttribute().
Pointer to the database handle initialized by the handle factory
long value of one of the PDO_ATTR_xxxx types. See Tabella 45-1 for valid attributes.
The new value for the attribute.
It is up to the driver to decide which attributes will be supported for a particular implementation. It is not necessary for a driver to provide this function if it does not need to support additional attributes. The PDO driver handles the PDO_ATTR_CASE, PDO_ATTR_ORACLE_NULLS, and PDO_ATTR_ERRMODE attributes directly.
This function returns 1 on success or 0 on failure.
static char * SKEL_handle_last_id(pdo_dbh_t *dbh, const char *name, unsigned int len TSRMLS_DC) |
This function will be called by PDO to retrieve the ID of the last inserted row.
Pointer to the database handle initialized by the handle factory
string representing a table or sequence name.
the length of the name parameter.
This function returns a character string containing the id of the last inserted row on success or NULL on failure. This is an optional function.
static int SKEL_check_liveness(pdo_dbh_t *dbh TSRMLS_DC) |
This function will be called by PDO to test whether or not a persistent connection to a database is alive and ready for use.
Pointer to the database handle initialized by the handle factory
This function returns 1 if the database connection is alive and ready for use, otherwise it should return 0 to indicate failure or lack of support.
Nota: This is an optional function.
static function_entry *SKEL_get_driver_methods(pdo_dbh_t *dbh, int kind TSRMLS_DC) |
This function will be called by PDO in response to a call to any method that is not a part of either the PDO or PDOStatement classes. It's purpose is to allow the driver to provide additional driver specific methods to those classes.
Pointer to the database handle initialized by the handle factory
One of the following:
Set when the method call was attempted on an instance of the PDO class. The driver should return a pointer a function_entry table for any methods it wants to add to that class, or NULL if there are none.
Set when the method call was attempted on an instance of the PDOStatement class. The driver should return a pointer to a function_entry table for any methods it wants to add to that class, or NULL if there are none.
This function returns a pointer to the function_entry table requested, or NULL there are no driver specific methods.
static int SKEL_handle_factory(pdo_dbh_t *dbh, zval *driver_options TSRMLS_DC) |
This function will be called by PDO to create a database handle. For most databases this involves establishing a connection to the database. In some cases, a persistent connection may be requested, in other cases connection pooling may be requested. All of these are database/driver dependent.
Pointer to the database handle initialized by the handle factory
An array of driver options, keyed by integer option number. See Tabella 45-1 for a list of possible attributes.
This function should fill in the passed database handle structure with its driver specific information on success and return 1, otherwise it should return 0 to indicate failure.
PDO processes the AUTOCOMMIT and PERSISTENT driver options before calling the handle_factory. It is the handle factory's responsibility to process other options.
A static structure of type pdo_dbh_methods named SKEL_methods must be declared and initialized to the function pointers for each defined function. If a function is not supported or not implemented the value for that function pointer should be set to NULL.
A structure of type pdo_driver_t named pdo_SKEL_driver should be declared. The PDO_DRIVER_HEADER(SKEL) macro should be used to declare the header and the function pointer to the handle factory function should set.
This unit implements all of the database statement handling methods that support the PDO statement object.
static int SKEL_stmt_dtor(pdo_stmt_t *stmt TSRMLS_DC) |
This function will be called by PDO to destroy a previously constructed statement object.
Pointer to the statement structure initialized by SKEL_handle_preparer.
This should do whatever is necessary to free up any driver specific storage allocated for the statement. The return value from this function is ignored.
static int SKEL_stmt_execute(pdo_stmt_t *stmt TSRMLS_DC) |
This function will be called by PDO to execute the prepared SQL statement in the passed statement object.
Pointer to the statement structure initialized by SKEL_handle_preparer.
This function returns 1 for success or 0 in the event of failure.
static int SKEL_stmt_fetch(pdo_stmt_t *stmt, enum pdo_fetch_orientation ori, long offset TSRMLS_DC) |
This function will be called by PDO to fetch a row from a previously executed statement object.
Pointer to the statement structure initialized by SKEL_handle_preparer.
One of PDO_FETCH_ORI_xxx which will determine which row will be fetched.
If ori is set to PDO_FETCH_ORI_ABS or PDO_FETCH_ORI_REL, offset represents the row desired or the row relative to the current position, respectively. Otherwise, this value is ignored.
The results of this fetch are driver dependent and the data is usually stored in the driver_data member of pdo_stmt_t object. The ori and offset parameters are only meaningful if the statement represents a scrollable cursor. This function returns 1 for success or 0 in the event of failure.
static int SKEL_stmt_param_hook(pdo_stmt_t *stmt, struct pdo_bound_param_data *param, enum pdo_param_event event_type TSRMLS_DC) |
This function will be called by PDO for handling of both bound parameters and bound columns.
Pointer to the statement structure initialized by SKEL_handle_preparer.
The structure describing either a statement parameter or a bound column.
The type of event to occur for this parameter, one of the following:
Called when PDO allocates the binding. Occurs as part of PDOStatement::bindParam(), PDOStatement::bindValue() or as part of an implicit bind when calling PDOStatement::execute(). This is your opportunity to take some action at this point; drivers that implement native prepared statements will typically want to query the parameter information, reconcile the type with that requested by the script, allocate an appropriately sized buffer and then bind the parameter to that buffer. You should not rely on the type or value of the zval at param->parameter at this point in time.
Called once per parameter as part of cleanup. You should release any resources associated with that parameter now.
Called once for each parameter immediately before calling SKEL_stmt_execute; take this opportunity to make any final adjustments ready for execution. In particular, you should note that variables bound via PDOStatement::bindParam() are only legal to touch now, and not any sooner.
Called once for each parameter immediately after calling SKEL_stmt_execute; take this opportunity to make any post-execution actions that might be required by your driver.
Called once for each parameter immediately prior to calling SKEL_stmt_fetch.
Called once for each parameter immediately after calling SKEL_stmt_fetch.
This hook will be called for each bound parameter and bound column in the statement. For ALLOC and FREE events, a single call will be made for each parameter or column. The param structure contains a driver_data field that the driver can use to store implementation specific information about each of the parameters.
For all other events, PDO may call you multple times as the script issues PDOStatement::execute() and PDOStatement::fetch() calls.
If this is a bound parameter, the is_param flag in the param structure, otherwise, the param structure refers to a bound column.
This function returns 1 for success or 0 in the event of failure.
static int SKEL_stmt_describe_col(pdo_stmt_t *stmt, int colno TSRMLS_DC) |
This function will be called by PDO to query information about a particular column.
Pointer to the statement structure initialized by SKEL_handle_preparer.
The column number to be queried.
The driver should populate the pdo_stmt_t member columns(colno) with the appropriate information. This function returns 1 for success or 0 in the event of failure.
static int SKEL_stmt_get_col_data(pdo_stmt_t *stmt, int colno, char **ptr, unsigned long *len, int *caller_frees TSRMLS_DC) |
This function will be called by PDO to retrieve data from the specified column.
Pointer to the statement structure initialized by SKEL_handle_preparer.
The column number to be queried.
Pointer to the retrieved data.
The length of the data pointed to by ptr.
If set, ptr should point to emalloc'd memory and the main PDO driver will free it as soon as it is done with it. Otherwise, it will be the responsibility of the driver to free any allocated memory as a result of this call.
The driver should return the resultant data and length of that data in the ptr and len variables respectively. It should be noted that the main PDO driver expects the driver to manage the lifetime of the data. This function returns 1 for success or 0 in the event of failure.
static int SKEL_stmt_set_attr(pdo_stmt_t *stmt, long attr, zval *val TSRMLS_DC) |
This function will be called by PDO to allow the setting of driver specific attributes for a statement object.
Pointer to the statement structure initialized by SKEL_handle_preparer.
long value of one of the PDO_ATTR_xxxx types. See Tabella 45-1 for valid attributes.
The new value for the attribute.
This function is driver dependent and allows the driver the capability to set database specific attributes for a statement. This function returns 1 for success or 0 in the event of failure. This is an optional function. If the driver does not support additional settable attributes, it can be NULLed in the method table. The PDO driver does not handle any settable attributes on the database driver's behalf.
static int SKEL_stmt_get_attr(pdo_stmt_t *stmt, long attr, zval *return_value TSRMLS_DC) |
This function will be called by PDO to allow the retrieval of driver specific attributes for a statement object.
Pointer to the statement structure initialized by SKEL_handle_preparer.
long value of one of the PDO_ATTR_xxxx types. See Tabella 45-1 for valid attributes.
The returned value for the attribute.
This function is driver dependent and allows the driver the capability to retrieve a previously set database specific attribute for a statement. This function returns 1 for success or 0 in the event of failure. This is an optional function. If the driver does not support additional gettable attributes, it can be NULLed in the method table. The PDO driver does not handle any settable attributes on the database driver's behalf.
static int SKEL_stmt_get_col_meta(pdo_stmt_t *stmt, int colno, zval *return_value TSRMLS_DC) |
Avvertimento |
This function is not well defined and is subject to change. |
This function will be called by PDO to retrieve meta-data from the specified column.
Pointer to the statement structure initialized by SKEL_handle_preparer.
The column number for which data is to be retrieved.
Holds the returned meta data.
The driver author should consult the documentation for this function that can be found in the php_pdo_driver.h header as this will be the most current. This function returns 1 for success or 0 in the event of failure. The database driver does not need to provide this function.
A static structure of type pdo_stmt_methods named SKEL_stmt_methods should be declared and initialized to the function pointers for each defined function. If a function is not supported or not implemented the value for that function pointer should be set to NULL.
The build process is designed to work with PEAR (see http://pear.php.net/ for more information about PEAR). There are two files that are used to assist in configuring your package for building. The first is config.m4 which is the autoconf configuration file for all platforms except Win32. The second is config.w32 which a build configuration file for use on Win32. Skeleton files for these are built for you when you first set up your project. You then need to customize them to fit the needs of your project. Once you've customized your config files, you can build your driver using the following sequence of commands:
Before first build:
$ sudo pear install PDO |
For each build:
$ cd pdo_SKEL $ phpize $ ./configure $ make $ sudo make install |
The process can then be repeated as necessary during the development process.
PDO has a set of "core" tests that all drivers should pass before being released. They're designed to run from the PHP source distribution, so running the tests for your driver requires moving things around a bit. The suggested procedure is to obtain the latest PHP 5.1 snapshot and perform the following step:
$ cp -r pdo_SKEL /path/to/php-5.1/ext |
This will allow the test harness to run your tests. The next thing you need to do is create a test that will redirect into the PDO common core tests. The convention is to name this file common.phpt; it should be placed in the tests subdirectory that was created by ext_skel when you created your extension skeleton. The content of this file should look something like the following:
--TEST-- SKEL --SKIPIF-- <?php # vim:ft=php if (!extension_loaded('pdo_SKEL')) print 'skip'; ?> --REDIRECTTEST-- if (false !== getenv('PDO_SKEL_TEST_DSN')) { # user set them from their shell $config['ENV']['PDOTEST_DSN'] = getenv('PDO_SKEL_TEST_DSN'); $config['ENV']['PDOTEST_USER'] = getenv('PDO_SKEL_TEST_USER'); $config['ENV']['PDOTEST_PASS'] = getenv('PDO_SKEL_TEST_PASS'); if (false !== getenv('PDO_SKEL_TEST_ATTR')) { $config['ENV']['PDOTEST_ATTR'] = getenv('PDO_SKEL_TEST_ATTR'); } return $config; } return array( 'ENV' => array( 'PDOTEST_DSN' => 'SKEL:dsn', 'PDOTEST_USER' => 'username', 'PDOTEST_PASS' => 'password' ), 'TESTS' => 'ext/pdo/tests' ); |
This will cause the common core tests to be run, passing the values of PDOTEST_DSN, PDOTEST_USER and PDOTEST_PASS to the PDO constructor as the dsn, username and password parameters. It will first check the environment, so that appropriate values can be passed in when the test harness is run, rather than hard-coding the database credentials into the test file.
The test harness can be invoked as follows:
$ cd /path/to/php-5.1 $ make TESTS=ext/pdo_SKEL/tests PDO_SKEL_TEST_DSN="skel:dsn" \ PDO_SKEL_TEST_USER=user PDO_SKEL_TEST_PASS=pass test |
PDO drivers are released via PECL; all the usual rules for PECL extensions apply. Packaging is accomplished by creating a valid package.xml file and then running:
$ pear package |
This will create a tarball named PDO_SKEL-X.Y.Z.tgz.
Before releasing the package, you should test that it builds correctly; if you've made a mistake in your config.m4 or package.xml files, the package may not function correctly. You can test the build, without installing anything, using the following invocation:
$ pear build package.xml |
Once this is proven to work, you can test installation:
$ pear package $ sudo pear install PDO_SKEL-X.Y.X.tgz |
Full details about package.xml can be found in the PEAR Programmer's documentation (http://pear.php.net/manual/).
A PDO driver is released via the PHP Extension Community Library (PECL). Information about PECL can be found at http://pecl.php.net/index.php.
All fields should be treated as read-only by the driver, unless explicitly stated otherwise.
Figura 45-1. pdo_dbh_t
/* represents a connection to a database */ struct _pdo_dbh_t { /* driver specific methods */ struct pdo_dbh_methods *methods; |
If, for whatever reason, your driver is not suitable to run persistently, you MUST check this flag in your SKEL_handle_factory() and raise an appropriate error.
If your database client library API simply returns pointers to its own internal buffers for you to copy after each fetch call, you should leave this value set to 0.
All fields should be treated as read-only unless explicitly stated otherwise.
Figura 45-2. pdo_stmt_t
/* represents a prepared statement */ struct _pdo_stmt_t { /* driver specifics */ struct pdo_stmt_methods *methods; |
Tabella 45-1. Database and Statement Attributes Table
Attribute |
Valid value(s) |
PDO_ATTR_AUTOCOMMIT |
BOOL TRUE if autocommit is set, FALSE otherwise. dbh->auto_commit contains value. Processed by PDO directly. |
PDO_ATTR_PREFETCH |
LONG Value of the prefetch size in drivers that support it. |
PDO_ATTR_TIMEOUT |
LONG How long to wait for a db operation before timing out. |
PDO_ATTR_ERRMODE |
LONG Processed and handled by PDO |
PDO_ATTR_SERVER_VERSION |
STRING The "human-readable" string representing the Server/Version this driver is currently connected to. |
PDO_ATTR_CLIENT_VERSION |
STRING The "human-readable" string representing the Client/Version this driver supports. |
PDO_ATTR_SERVER_INFO |
STRING The "human-readable" description of the Server. |
PDO_ATTR_CONNECTION_STATUS |
LONG Values not yet defined |
PDO_ATTR_CASE |
LONG Processed and handled by PDO. |
PDO_ATTR_CURSOR_NAME |
STRING String representing the name for a database cursor for use in "where current in <name>" SQL statements. |
PDO_ATTR_CURSOR |
LONG
|
The values for the attributes above are all defined in terms of the Zend API. The Zend API contains macros that can be used to convert a *zval to a value. These macros are defined in the Zend header file, zend_API.h in the Zend directory of your PHP build directory. Some of these attributes can be used with the statement attribute handlers such as the PDO_ATTR_CURSOR and PDO_ATTR_CURSOR_NAME. See the statement attribute handling functions for more information.
Error handling is implemented using a hand-shaking protocol between PDO and the database driver code. The database driver code signals PDO than an error has occurred via a failure (0) return from any of the interface functions. If a zero is returned, the field error_code in the control block appropriate to the context (either the pdo_dbh_t or pdo_stmt_t block). In practice, it is probably a good idea to set the field in both blocks to the same value to ensure the correct one is getting used.
The error_mode field is a six-byte field containing a 5 character ASCIIZ SQLSTATE identifier code. This code drives the error message process. The SQLSTATE code is used to look up an error message in the internal PDO error message table (see pdo_sqlstate.c for a list of error codes and their messages). If the code is not known to PDO, a default "Unknown Message" value will be used.
In addition to the SQLSTATE code and error message, PDO will call the driver-specific fetch_err() routine to obtain supplemental data for the particular error condition. This routine is passed an array into which the driver may place additional information. This array has slot positions assigned to particular types of supplemental info:
A native error code. This will frequently be an error code obtained from the database API.
A descriptive string. This string can contain anything additional information related to the failure. Database drivers typically include information such as an error message, code location of the failure, and any additional descriptive information the driver developer feels worthy of inclusion. It is generally a good idea to include all diagnostic information obtainable from the database interface at the time of the failure. For driver-detected errors (such as memory allocation problems), the driver developer can define whatever error information that seems appropriate.
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 46-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 46-1 above, PHP can be extended primarily at three points: external modules, built-in modules, and the Zend engine. The following sections discuss these options.
External modules 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 |
php-src | Main PHP source files and main header files; here you'll find all of PHP's API definitions, macros, etc. (important). Everything else is below this directory. |
php-src/ext | Repository for dynamic and built-in modules; by default, these are the "official" PHP modules that have been integrated into the main source tree. From PHP 4.0, it's possible to compile these standard extensions as dynamic loadable modules (at least, those that support it). |
php-src/main | This directory contains the main php macros and definitions. (important) |
php-src/pear | Directory for the PHP Extension and Application Repository. This directory contains core PEAR files. |
php-src/sapi | Contains the code for the different server abstraction layers. |
TSRM | Location of the "Thread Safe Resource Manager" (TSRM) for Zend and PHP. |
ZendEngine2 | Location of the Zend Engine files; here you'll find all of Zend's API definitions, macros, etc. (important). |
Discussing all the files included in the PHP package is beyond the scope of this chapter. However, you should take a close look at the following files:
php-src/main/php.h, located in the main PHP directory. This file contains most of PHP's macro and API definitions.
php-src/Zend/zend.h, located in the main Zend directory. This file contains most of Zend's macros and definitions.
php-src/Zend/zend_API.h, also located in the Zend directory, which defines Zend's API.
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/software/m4/manual/m4.html)
All these stub files are generated automatically, along with .cvsignore, by a little shell script named ext_skel that resides in the ext directory. As argument it takes the name of the module that you want to create. The shell script then creates a directory of the same name, along with the appropriate stub files.
Step by step, the process looks like this:
:~/cvs/php4/ext:> ./ext_skel --extname=my_module Creating directory my_module Creating basic files: config.m4 .cvsignore my_module.c php_my_module.h CREDITS EXPERIMENTAL tests/001.phpt my_module.php [done]. To use your new extension, you will have to execute the following steps: 1. $ cd .. 2. $ vi ext/my_module/config.m4 3. $ ./buildconf 4. $ ./configure --[with|enable]-my_module 5. $ make 6. $ ./php -f ext/my_module/my_module.php 7. $ vi ext/my_module/my_module.c 8. $ make Repeat steps 3-6 until you are satisfied with ext/my_module/config.m4 and step 6 confirms that your module is compiled into PHP. Then, start writing code and repeat the last two steps as often as necessary. |
The default config.m4 shown in Esempio 46-1 is a bit more complex:
Esempio 46-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 46-2 shows the source.
Esempio 46-2. 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 46-2 can be enabled with --enable-first_module or --enable-first_module=yes.
Compiling Manually. To compile your modules manually, you need the following commands:
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 46-3. If you compiled it into the PHP binary, omit the call to dl(), as the module's functionality is instantly available to your scripts.
Avvertimento |
For security reasons, you should not put your dynamic modules into publicly accessible directories. Even though it can be done and it simplifies testing, you should put them into a separate directory in production environments. |
Calling this PHP file in your Web browser should give you the output shown in Figura 46-2.
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 46-1 for descriptions).
Tabella 46-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 46-4.
Esempio 46-4. 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 46-2 shows a list of all the macros that you can use to define functions.
Tabella 46-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 46-5.
Esempio 46-5. 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 46-3. These are not used in our basic example yet, but will be demonstrated later on. You should make use of these macros to declare your startup and shutdown functions, as these require special arguments to be passed (INIT_FUNC_ARGS and SHUTDOWN_FUNC_ARGS), which are automatically included into the function declaration when using the predefined macros. If you declare your functions manually and the PHP developers decide that a change in the argument list is necessary, you'll have to change your module sources to remain compatible.
Tabella 46-3. Macros to Declare Startup and Shutdown Functions
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 > 4) WRONG_PARAM_COUNT; /* argument count is correct, now retrieve arguments */ if(zend_get_parameters_array_ex(argument_count, parameter_array) != SUCCESS) WRONG_PARAM_COUNT; |
A very clever implementation of this can be found in the code handling PHP's fsockopen() located in ext/standard/fsock.c, as shown in Esempio 46-6. Don't worry if you don't know all the functions used in this source yet; we'll get to them shortly.
Esempio 46-6. PHP's implementation of variable arguments in fsockopen().
|
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 46-4).
Note: All conversion functions expect a **zval as parameter.
Tabella 46-4. 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 46-4 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 46-7. 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 46-5, Tabella 46-6 and Tabella 46-7.
Tabella 46-5. Zend zval Structure
Entry | Description |
value | Union containing this variable's contents. See Tabella 46-6 for a description. |
type | Contains this variable's type. For a list of available types, see Tabella 46-7. |
is_ref | 0 means that this variable is not a reference; 1 means that this variable is a reference to another variable. |
refcount | The number of references that exist for this variable. For every new reference to the value stored in this variable, this counter is increased by 1. For every lost reference, this counter is decreased by 1. When the reference counter reaches 0, no references exist to this value anymore, which causes automatic freeing of the value. |
Tabella 46-6. Zend zvalue_value Structure
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 46-7. 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 46-8.
Esempio 46-8. 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 46-9. 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 46-10).
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 46-8, Tabella 46-9 and Tabella 46-10 describe these functions. All functions return FAILURE on failure and SUCCESS on success.
Tabella 46-8. Zend's API for Associative Arrays
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 46-9. 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 46-10. 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 46-11) and zend_hash_index_update() for indexed arrays (see Esempio 46-12):
Esempio 46-11. Adding an element to an associative array.
|
Esempio 46-12. 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 46-11. 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 a unique name within PHP for the resource type so when the user for example calls var_dump($resource); he also gets the name of the resource. |
module_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_list_destructors_ex(my_destruction_handler, NULL, le_myresource_name, module_number); // You can register additional resources, initialize // your global vars, constants, whatever. } |
To actually register a new resource you use can either use the zend_register_resource() function or the ZEND_REGISTER_RESOURE() macro, both defined in zend_list.h . Although the arguments for both map 1:1 it's a good idea to always use macros to be upwards compatible:
int ZEND_REGISTER_RESOURCE(zval *rsrc_result, void *rsrc_pointer, int rsrc_type); |
rsrc_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 46-12 describes macros that do exactly this task. They don't need any zval allocation; you simply have to supply a variable name and value.
Tabella 46-12. Macros for Global Variable Creation
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 46-13. All the macros create a constant with the specified name and value.
You can also specify flags for each constant:
CONST_CS - This constant's name is to be treated as case sensitive.
CONST_PERSISTENT - This constant is persistent and won't be "forgotten" when the current process carrying this constant shuts down.
// register a new constant of type "long" REGISTER_LONG_CONSTANT("NEW_MEANINGFUL_CONSTANT", 324, CONST_CS | CONST_PERSISTENT); |
Tabella 46-13. 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 rvalue (result of the evaluation of the right side of the operator) to the lvalue (same for the left side).
Overloading means assigning a different meaning to this operator, and is usually used to assign a function call to an operator. Whenever this operator would be used on such an object in a program, this function would be called with the lvalue and rvalue as parameters. Equipped with that information, it can perform the operation it intends the "=" operator to have (usually an extended form of copying).
This same form of "extended copying" is also necessary for PHP's zval containers. Again, in the case of an array, this extended copying would imply re-creation of all hash table entries relating to this array. For strings, proper memory allocation would have to be assured, and so on.
Zend ships with such a function, called zend_copy_ctor() (the previous PHP equivalent was pval_copy_constructor()).
A most useful demonstration is a function that accepts a complex type as argument, modifies it, and then returns the argument:
zval *parameter; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", ¶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 46-14 and Tabella 46-15.
Nota: The macros in Tabella 46-14 automatically return from your function, those in Tabella 46-15 only set the return value; they don't return from your function.
Tabella 46-14. Predefined Macros for Returning Values from a Function
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 46-15. 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 46-16. 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 46-13 shows a source example and its output. To print the table footer, use php_info_print_table_end().
Esempio 46-13. Source code and screenshot for output in phpinfo().
|
You can also print execution information, such as the current file being executed. The name of the function currently being executed can be retrieved using the function get_active_function_name(). This function returns a pointer to the function name and doesn't accept any arguments. To retrieve the name of the file currently being executed, use zend_get_executed_filename(). This function accesses the executor globals, which are passed to it using the TSRMLS_C macro. The executor globals are automatically available to every function that's called directly by Zend (they're part of the INTERNAL_FUNCTION_PARAMETERS described earlier in this chapter). If you want to access the executor globals in another function that doesn't have them available automatically, call the macro TSRMLS_FETCH() once in that function; this will introduce them to your local scope.
Finally, the line number currently being executed can be retrieved using the function zend_get_executed_lineno(). This function also requires the executor globals as arguments. For examples of these functions, see Esempio 46-14.
Esempio 46-14. Printing execution information.
|
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 46-15 shows a small demonstration of calling a user function. The code calls a function that's supplied to it as argument and directly passes this function's return value through as its own return value. Note the use of the constructor and destructor calls at the end - it might not be necessary to do it this way here (since they should be separate values, the assignment might be safe), but this is bulletproof.
Esempio 46-15. Calling user functions.
|
<?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 46-17.
Tabella 46-17. 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 46-18.
Tabella 46-18. 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 46-19).
Tabella 46-19. 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 |
#include <zend_API.h>
int _object_and_properties_init ( zval* arg, zend_class_entry* ce, HashTable* properties ZEND_FILE_LINE_DC TSRMLS_DC )...
#include <zend_API.h>
int _object_init_ex ( zval* arg, zend_class_entry* ce ZEND_FILE_LINE_DC TSRMLS_DC )...
#include <zend_API.h>
int _zend_get_parameters_array_ex ( int param_count, zval*** argument_array TSRMLS_DC )...
#include <zend_API.h>
int _zend_get_parameters_array ( int ht, int param_count, zval** argument_array TSRMLS_DC )...
#include <zend_hash.h>
int _zend_hash_add_or_update ( HashTable* ht, char* arKey, uint nKeyLength, void* pData, uint nDataSize, void** pDest, int flag ZEND_FILE_LINE_DC )...
...
...
...
...
...
...
...
#include <zend_hash.h>
int _zend_hash_index_update_or_next_insert ( HashTable* ht, ulong h, void* pData, uint nDataSize, void** pDest, int flag ZEND_FILE_LINE_DC )...
#include <zend_hash.h>
int _zend_hash_init_ex ( HashTable* ht, uint nSize, hash_func_t pHashFunction, dtor_func_t pDestructor, zend_bool persistent, zend_bool bApplyProtection ZEND_FILE_LINE_DC )...
...
...
...
...
...
...
#include <zend_hash.h>
int _zend_hash_init ( HashTable* ht, uint nSize, hash_func_t pHashFunction, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC )...
...
...
...
...
...
#include <zend_hash.h>
void _zend_hash_merge ( HashTable* target, HashTable* source, copy_ctor_func_t pCopyConstructor, void* tmp, uint size, int overwrite ZEND_FILE_LINE_DC )...
...
...
...
...
...
...
#include <zend_hash.h>
int _zend_hash_quick_add_or_update ( HashTable* ht, char* arKey, uint nKeyLength, ulong h, void* pData, uint nDataSize, void** pDest, int flag ZEND_FILE_LINE_DC )...
...
...
...
...
...
...
...
...
(no version information, might be only in CVS)
ZEND_WRONG_PARAM_COUNT_WITH_RETVAL -- Generate standard error message and return custom value#include <zend_API.h>
void ZEND_WRONG_PARAM_COUNT_WITH_RETVAL ( mixed return_value )Nota: This macro is part of the API but not used in any bundled or PECL extension
ZEND_WRONG_PARAM_COUNT_WITH_RETVAL() produces a standard warning message for functions or class methods that have been called with a wrong number of parameters and returns its parameter to the calling function. The macro automaticly puts the right function name and class name (if needed) into the error message.
The return_value parameter is returned to the calling function of the current one.
ZEND_WRONG_PARAM_COUNT_WITH_RETVAL() is actually a convenience wrapper for zend_wrong_param_count().
#include <zend_API.h>
int add_assoc_bool_ex ( zval* arg, char* key, uint key_len, int b )...
#include <zend_API.h>
int add_assoc_double_ex ( zval* arg, char* key, uint key_len, double d )...
#include <zend_API.h>
int add_assoc_function ( zval* arg, char* key, void (*function_ptr)(INTERNAL_FUNCTION_PARAMETERS) )...
#include <zend_API.h>
int add_assoc_long_ex ( zval* arg, char* key, uint key_len, long n )...
#include <zend_API.h>
int add_assoc_resource_ex ( zval* arg, char* key, uint key_len, int r )...
#include <zend_API.h>
int add_assoc_string_ex ( zval* arg, char* key, uint key_len, char* str, int duplicate )...
#include <zend_API.h>
int add_assoc_string ( zval* arg, char* str, uint key_len, int duplicate )...
#include <zend_API.h>
int add_assoc_stringl_ex ( zval* arg, char* key, uint key_len, char* str, uint length, int duplicate )...
#include <zend_API.h>
int add_assoc_zval_ex ( zval* arg, char* key, uint key_len, zval* value )...
#include <zend_API.h>
int add_get_assoc_string_ex ( zval* arg, char* key, uint key_len, char* str, void** dest, int duplicate )...
#include <zend_API.h>
int add_get_assoc_string ( zval* arg, char* key, char* str, void* *dest, int duplicate )...
#include <zend_API.h>
int add_get_assoc_stringl_ex ( zval* arg, char* key, uint key_len, char* str, uint length, void** dest, int duplicate )...
#include <zend_API.h>
int add_get_assoc_stringl ( zval* arg, char* str, uint length, void* *dest, int duplicate )...
#include <zend_API.h>
int add_get_index_double ( zval* arg, uint idx, double d, void** dest )...
#include <zend_API.h>
int add_get_index_long ( zval* arg, uint idx, long l, void** dest )...
#include <zend_API.h>
int add_get_index_string ( zval* arg, uint idx, char* str, void** dest, int duplicate )...
#include <zend_API.h>
int add_get_index_stringl ( zval* arg, uint idx, char* str, uint length, void** dest, int duplicate )...
#include <zend_API.h>
int add_index_string ( zval* arg, uint idx, char* str, int duplicate )...
#include <zend_API.h>
int add_index_stringl ( zval* arg, uint idx, char* str, uint length, int duplicate )...
#include <zend_API.h>
int add_next_index_string ( zval* arg, char* str, int duplicate )...
#include <zend_API.h>
int add_next_index_stringl ( zval* arg, char* str, uint length, int duplicate )...
#include <zend_API.h>
int add_property_bool_ex ( zval* arg, char* key, uint key_len, int b TSRMLS_DC )...
#include <zend_API.h>
int add_property_double_ex ( zval* arg, char* key, uint key_len, double d TSRMLS_DC )...
#include <zend_API.h>
int add_property_long_ex ( zval* arg, char* key, uint key_len, long l TSRMLS_DC )...
#include <zend_API.h>
int add_property_null_ex ( zval* arg, char* key, uint key_len TSRMLS_DC )...
#include <zend_API.h>
int add_property_resource_ex ( zval* arg, char* key, uint key_len, long r TSRMLS_DC )...
#include <zend_API.h>
int add_property_string_ex ( zval* arg, char* key, uint key_len, char* str, int duplicate TSRMLS_DC )...
#include <zend_API.h>
int add_property_string ( zval* arg, char* key, char* str, int duplicate )...
#include <zend_API.h>
int add_property_stringl_ex ( zval* arg, char* key, uint key_len, char* str, uint length, int duplicate TSRMLS_DC )...
#include <zend_API.h>
int add_property_stringl ( zval* arg, char* key, char* str, uint length, int duplicate )...
#include <zend_API.h>
int add_property_zval_ex ( zval* arg, char* key, uint key_len, zval* value TSRMLS_DC )...
#include <zend_API.h>
int call_user_function_ex ( HashTable* function_table, zval** object_pp, zval* function_name, zval** retval_ptr_ptr, zend_uint param_count, zval** params[], int no_separation, HashTable* symbol_table TSRMLS_DC )...
...
...
...
...
...
...
...
...
#include <zend_API.h>
int call_user_function ( HashTable* function_table, zval** object_pp, zval* function_name, zval* retval_ptr, zend_uint param_count, zval* params[] TSRMLS_DC )...
...
...
...
...
...
...
(no version information, might be only in CVS)
ZEND_WRONG_PARAM_COUNT -- Generate standard error message for wrong parameter count in function or method call#include <zend_API.h>
void ZEND_WRONG_PARAM_COUNT ( void )ZEND_WRONG_PARAM_COUNT() produces a standard warning message for functions or class methods that have been called with a wrong number of parameters. The macro automaticly puts the right function name and class name (if needed) into the error message.
ZEND_WRONG_PARAM_COUNT() is actually a convenience wrapper for zend_wrong_param_count().
#include <zend_API.h>
int object_and_properties_init ( zval* arg, zend_class_entry* ce, HashTable* properties )...
#include <zend_API.h>
int zend_call_function ( zend_fcall_info* fci, zend_fcall_info_cache* fci_cache TSRMLS_DC )...
#include <zend_API.h>
void zend_check_magic_method_implementation ( zend_class_entry* ce, zend_function* fptr, int error_type TSRMLS_DC )...
#include <zend_API.h>
void zend_class_implements ( zend_class_entry* class_entry TSRMLS_DC, int num_interfaces, ... )...
#include <zend_API.h>
int zend_copy_parameters_array ( int param_count, zval* argument_array TSRMLS_DC )...
#include <zend_API.h>
int zend_declare_property_bool ( zend_class_entry* ce, char* name, int name_length, long value, int access_type TSRMLS_DC )...
#include <zend_API.h>
int zend_declare_property_double ( zend_class_entry* ce, char* name, int name_length, double value, int access_type TSRMLS_DC )...
#include <zend_API.h>
int zend_declare_property_ex ( zend_class_entry* ce, char* name, int name_length, zval* property, int access_type, char* doc_comment, int doc_comment_len TSRMLS_DC )...
...
...
...
...
...
...
...
#include <zend_API.h>
int zend_declare_property_long ( zend_class_entry* ce, char* name, int name_length, long value, int access_type TSRMLS_DC )...
#include <zend_API.h>
int zend_declare_property_null ( zend_class_entry* ce, char* name, int name_length, int access_type TSRMLS_DC )...
#include <zend_API.h>
int zend_declare_property_string ( zend_class_entry* ce, char* name, int name_length, char* value, int access_type TSRMLS_DC )...
#include <zend_API.h>
int zend_declare_property_stringl ( zend_class_entry* ce, char* name, int name_length, char* value, int value_len, int access_type TSRMLS_DC )...
...
...
...
...
...
...
#include <zend_API.h>
int zend_declare_property ( zend_class_entry* ce, char* name, int name_length, zval* property, int access_type TSRMLS_DC )...
#include <zend_API.h>
int zend_delete_global_variable ( char* name, int name_len TSRMLS_DC )...
#include <zend_API.h>
int zend_disable_class ( char* class_name, uint class_name_length TSRMLS_DC )...
#include <zend_API.h>
int zend_disable_function ( char* function_name, uint function_name_length TSRMLS_DC )...
#include <zend.h>
void zend_error ( int type, const char *format, ...) ZEND_ATTRIBUTE_FORMAT(printf, 2, 3 )...
#include <zend_API.h>
zend_class_entry* zend_get_class_entry ( zval* zobject TSRMLS_DC )...
#include <zend.h>
int zend_get_configuration_directive ( char* name, uint name_length, zval* contents )...
#include <zend_API.h>
int zend_get_object_classname ( zval* object, char** class_name, zend_uint* class_name_len TSRMLS_DC )...
#include <zend_API.h>
int zend_get_parameters_array_ex ( int param_count, zval*** argument_array )...
#include <zend_API.h>
int zend_get_parameters_array ( int ht, int param_count, zval** argument_array )...
#include <zend_hash.h>
int zend_hash_add_empty_element ( HashTable* ht, char* arKey, uint nKeyLength )...
#include <zend_hash.h>
int zend_hash_add ( HashTable* ht, char* arKey, uint nKeyLength, void* pData, uint nDataSize, void** pDest )...
#include <zend_hash.h>
void zend_hash_apply_with_argument ( HashTable* ht, apply_func_arg_t apply_func, void* TSRMLS_DC )...
#include <zend_hash.h>
void zend_hash_apply_with_arguments ( HashTable* ht, apply_func_args_t apply_func, int, ... )...
#include <zend_hash.h>
void zend_hash_apply ( HashTable* ht, apply_func_t apply_func TSRMLS_DC )...
#include <zend_hash.h>
int zend_hash_compare ( HashTable* ht1, HashTable* ht2, compare_func_t compar, zend_bool ordered TSRMLS_DC )...
#include <zend_hash.h>
void zend_hash_copy ( HashTable* target, HashTable* source, copy_ctor_func_t pCopyConstructor, void* tmp, uint size )...
#include <zend_hash.h>
int zend_hash_del_key_or_index ( HashTable* ht, char* arKey, uint nKeyLength, ulong h, int flag )...
#include <zend_hash.h>
int zend_hash_exists ( HashTable* ht, char* arKey, uint nKeyLength )...
#include <zend_hash.h>
int zend_hash_find ( HashTable* ht, char* arKey, uint nKeyLength, void** pData )...
#include <zend_hash.h>
int zend_hash_get_current_data_ex ( HashTable* ht, void** pData, HashPosition* pos )...
#include <zend_hash.h>
int zend_hash_get_current_key_ex ( HashTable* ht, char** str_index, uint* str_length, ulong* num_index, zend_bool duplicate, HashPosition* pos )...
#include <zend_hash.h>
int zend_hash_get_current_key_type_ex ( HashTable* ht, HashPosition* pos )...
#include <zend_hash.h>
int zend_hash_index_find ( HashTable* ht, ulong h, void** pData )...
#include <zend_hash.h>
int zend_hash_init_ex ( HashTable* ht, uint nSize, hash_func_t pHashFunction, dtor_func_t pDestructor, zend_bool persistent, zend_bool bApplyProtection )...
...
...
...
...
...
...
#include <zend_hash.h>
int zend_hash_init ( HashTable* ht, uint nSize, hash_func_t pHashFunction, dtor_func_t pDestructor, zend_bool persistent )...
#include <zend_hash.h>
void zend_hash_internal_pointer_end_ex ( HashTable* ht, HashPosition* pos )...
#include <zend_hash.h>
void zend_hash_internal_pointer_reset_ex ( HashTable* ht, HashPosition* pos )...
#include <zend_hash.h>
void zend_hash_merge_ex ( HashTable* target, HashTable* source, copy_ctor_func_t pCopyConstructor, uint size, merge_checker_func_t pMergeSource, void* pParam )...
...
...
...
...
...
...
#include <zend_hash.h>
int zend_hash_minmax ( HashTable* ht, compare_func_t compar, int flag, void** pData TSRMLS_DC )...
#include <zend_hash.h>
int zend_hash_move_backwards_ex ( HashTable* ht, HashPosition* pos )...
#include <zend_hash.h>
int zend_hash_move_forward_ex ( HashTable* ht, HashPosition* pos )...
#include <zend_hash.h>
int zend_hash_quick_add ( HashTable* ht, char* arKey, uint nKeyLength, ulong h, void* pData, uint nDataSize, void** pDest )...
#include <zend_hash.h>
int zend_hash_quick_exists ( HashTable* ht, char* arKey, uint nKeyLength, ulong h )...
#include <zend_hash.h>
int zend_hash_quick_find ( HashTable* ht, char* arKey, uint nKeyLength, ulong h, void** pData )...
#include <zend_hash.h>
int zend_hash_quick_update ( HashTable* ht, char* arKey, uint nKeyLength, ulong h, void* pData, uint nDataSize, void** pDest )...
#include <zend_hash.h>
void zend_hash_reverse_apply ( HashTable* ht, apply_func_t apply_func TSRMLS_DC )...
#include <zend_hash.h>
int zend_hash_sort ( HashTable* ht, sort_func_t sort_func, compare_func_t compare_func, int renumber TSRMLS_DC )...
#include <zend_hash.h>
int zend_hash_update_current_key_ex ( HashTable* ht, int key_type, char* str_index, uint str_length, ulong num_index, HashPosition* pos )...
#include <zend_hash.h>
int zend_hash_update ( HashTable* ht, char* arKey, uint nKeyLength, void* pData, uint nDataSize, void** pDest )...
#include <zend_API.h>
zend_bool zend_is_callable_ex ( zval* callable, uint check_flags, char** callable_name, int* callable_name_len, zend_function** fptr_ptr, zval*** zobj_ptr_ptr TSRMLS_DC )...
...
...
...
...
...
...
#include <zend_API.h>
zend_bool zend_is_callable ( zval* callable, uint check_flags, char** callable_name )...
#include <zend_API.h>
zend_bool zend_make_callable ( zval* callable, char** callable_name TSRMLS_DC )...
#include <zend.h>
void zend_make_printable_zval ( zval* expr, zval* expr_copy, int* use_copy )...
#include <zend_API.h>
void zend_merge_properties ( zval* obj, HashTable* properties, int destroy_ht TSRMLS_DC )...
#include <zend_objects_API.h>
zval* zend_object_create_proxy ( zval* object, zval* member TSRMLS_DC )...
#include <zend_objects_API.h>
void zend_object_store_ctor_failed ( zval* zobject TSRMLS_DC )...
#include <zend_objects_API.h>
void* zend_object_store_get_object ( zval* object TSRMLS_DC )...
#include <zend_objects_API.h>
void zend_object_store_set_object ( zval* zobject, void* object TSRMLS_DC )...
#include <zend_objects_API.h>
void zend_objects_store_add_ref ( zval* object TSRMLS_DC )...
#include <zend_objects_API.h>
void zend_objects_store_call_destructors ( zend_objects_store* objects TSRMLS_DC )...
#include <zend_objects_API.h>
zend_object_value zend_objects_store_clone_obj ( zval* object TSRMLS_DC )...
#include <zend_objects_API.h>
void zend_objects_store_del_ref ( zval* object TSRMLS_DC )...
#include <zend_objects_API.h>
void zend_objects_store_destroy ( zend_objects_store* objects )...
#include <zend_objects_API.h>
void zend_objects_store_free_object_storage ( zend_objects_store* objects TSRMLS_DC )...
#include <zend_objects_API.h>
void zend_objects_store_init ( zend_objects_store* objects, zend_uint init_size )...
#include <zend_objects_API.h>
void zend_objects_store_mark_destructed ( zend_objects_store* objects TSRMLS_DC )...
#include <zend_objects_API.h>
zend_object_handle zend_objects_store_put ( void* object, zend_objects_store_dtor_t dtor, zend_objects_free_object_storage_t storage, zend_objects_store_clone_t clone TSRMLS_DC )...
#include <zend.h>
void zend_output_debug_string ( zend_bool trigger_break, char* format, ...) ZEND_ATTRIBUTE_FORMAT(printf, 2, 3 )...
#include <zend_API.h>
int zend_parse_method_parameters_ex ( int flags, int num_args TSRMLS_DC, zval* this_ptr, char* type_spec, ... )...
#include <zend_API.h>
int zend_parse_method_parameters ( int num_args TSRMLS_DC, zval* this_ptr, char* type_spec, ... )...
#include <zend_API.h>
int zend_parse_parameters_ex ( int num_args TSRMLS_DC, char* type_spec, ... )...
#include <zend_API.h>
int zend_parse_parameters ( int num_args TSRMLS_DC, char* type_spec, ... )...
#include <zend.h>
int zend_print_zval_ex ( zend_write_func_t write_func, zval* expr, int indent )...
#include <zend.h>
void zend_print_zval_r_ex ( zend_write_func_t write_func, zval* expr, int indent TSRMLS_DC )...
#include <zend_API.h>
zval* zend_read_property ( zend_class_entry* scope, zval* object, char* name, int name_length, zend_bool silent TSRMLS_DC )...
#include <zend_API.h>
int zend_register_functions ( zend_class_entry* scope, zend_function_entry* functions, HashTable* function_table, int type TSRMLS_DC )...
#include <zend_API.h>
zend_class_entry* zend_register_internal_class_ex ( zend_class_entry* class_entry, zend_class_entry* parent_ce, char* parent_name TSRMLS_DC )...
#include <zend_API.h>
zend_class_entry* zend_register_internal_class ( zend_class_entry* class_entry TSRMLS_DC )...
#include <zend_API.h>
zend_class_entry* zend_register_internal_interface ( zend_class_entry* orig_class_entry TSRMLS_DC )...
#include <zend_API.h>
zend_module_entry* zend_register_internal_module ( zend_module_entry* module_entry TSRMLS_DC )...
#include <zend_API.h>
zend_module_entry* zend_register_module_ex ( zend_module_entry* module TSRMLS_DC )...
#include <zend_API.h>
int zend_startup_module_ex ( zend_module_entry* module TSRMLS_DC )...
#include <zend_API.h>
void zend_unregister_functions ( zend_function_entry* functions, int count, HashTable* function_table TSRMLS_DC )...
#include <zend_API.h>
void zend_update_class_constants ( zend_class_entry* class_type TSRMLS_DC )...
#include <zend_API.h>
void zend_update_property_bool ( zend_class_entry* scope, zval* object, char* name, int name_length, long value TSRMLS_DC )...
#include <zend_API.h>
void zend_update_property_double ( zend_class_entry* scope, zval* object, char* name, int name_length, double value TSRMLS_DC )...
#include <zend_API.h>
void zend_update_property_long ( zend_class_entry* scope, zval* object, char* name, int name_length, long value TSRMLS_DC )...
#include <zend_API.h>
void zend_update_property_null ( zend_class_entry* scope, zval* object, char* name, int name_length TSRMLS_DC )...
#include <zend_API.h>
void zend_update_property_string ( zend_class_entry* scope, zval* object, char* name, int name_length, char* value TSRMLS_DC )...
#include <zend_API.h>
void zend_update_property_stringl ( zend_class_entry* scope, zval* object, char* name, int name_length, char* value, int value_length TSRMLS_DC )...
...
...
...
...
...
...
#include <zend_API.h>
void zend_update_property ( zend_class_entry* scope, zval* object, char* name, int name_length, zval* value TSRMLS_DC )...
(no version information, might be only in CVS)
zend_wrong_param_count -- Generate standard error message for wrong parameter count in function or method call#include <zend_API.h>
void zend_wrong_param_count ( TSRMLS_D )zend_wrong_param_count() produces a standard warning message for functions or class methods that have been called with a wrong number of parameters. The function automaticly puts the right function name and class name (if needed) into the error message.
Usually the ZEND_WRONG_PARAM_COUNT() and ZEND_WRONG_PARAM_COUNT_WITH_RETVAL() macros are used to invoke this function instead of calling it immediately as this saves typing the TSRMLS_C argument.
(no version information, might be only in CVS)
zend_zval_type_name -- Returns the PHP type name for a given zvalThis 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.
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 47-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 47-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 47-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.
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 http://www.zend.com/zend/art/intro.php sul sito web di Zend. Inoltre, gran parte del materiale usato per le conferenze sul PHP è liberamente disponibile.
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. Il PHP 5 utilizza il Zend engine 2 che, tra le altre cose offre maggiori funzionalità OOP.
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.
Prima di porre domande, può essere una buona idea per tutti leggere Come fare domande, il metodo migliore .
Messaggi tipo: "Non riesco a installare PHP! Aiuto! Cosa c'è di sbagliato?" non sono di aiuto a nessuno. Se si hanno problemi a installare PHP, si dovrebbero includere il sistema operativo nel quale lo si sta cercando di installare, quale versione di PHP si vuole installare, in quale forma lo si ha a disposizione (pre-compilato, dal CVS, RPM e così via), cosa si è tentato fino ad ora, dove ci si è bloccati e l'esatto messaggio di errore.
Questa regola è applicabile agli altri problemi che si possino incontrare. Si devono includere informazioni su cosa si è fatto, dove si è rimasti bloccati, cosa si sta cercando di fare e , se possibile, fornire gli esatti messaggi di errore. Se avete problemi con il vostro codice sorgente, dovreste includere la parte di codice che non è funzionante. Non includere più codice di quello che è strettamente necessario! Quello renderebbe il messaggio difficile da leggere e molte persone lo salterebbero proprio a causa di questo. Se siete poco sicuri su quante informazioni includere nel messaggio, meglio includerne di più che di meno.
Un'altra cosa importante da ricordare è quella di sintetizzare il vostro problema nell'oggetto del messaggio. Un oggetto del tipo "AIUTATEMIIIIIIIII!!!" oppure "Dove sta problema?" verrà ignorato dalla maggioranza dei lettori.
Infine si incoraggia la lettura di Come fare domande, il metodo migliore , può essere di aiuto per chiunque .
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) : Available locally.
È 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 adding the --with-mysql=/usr option when building PHP. Windows users may enable the extension php_mysql.dll inside php.ini. For more details, see the MySQL Reference for installation instructions. Also, be sure libmysql.dll is available to the systems PATH. For more details on how, read the FAQ on setting up the Windows systems PATH. Because libmysql.dll (and many other PHP related files) exist in the PHP folder, you'll want to add the PHP folder to your systems PATH.
5. After installing shared MySQL support, Apache dumps core as soon as libphp4.so is loaded. Can this be fixed?
If your MySQL libs are linked against pthreads this will happen. Check using ldd. If they are, grab the MySQL tarball and compile from source, or recompile from the source rpm and remove the switch in the spec file that turns on the threaded client code. Either of these suggestions will fix this. Then recompile PHP with the new MySQL libs.
6. Why do I get an error that looks something like this: "Warning: 0 is not a MySQL result index in <file> on line <x>" or "Warning: Supplied argument is not a valid MySQL result resource in <file> on line <x>?
You are trying to use a result identifier that is 0. The 0 indicates that your query failed for some reason. You need to check for errors after submitting a query and before you attempt to use the returned result identifier. The proper way to do this is with code similar to the following:
<?php $result = mysql_query("SELECT * FROM tables_priv"); if (!$result) { echo mysql_error(); exit; } ?> |
<?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=/path/to/apache e non --with-apache=/path/to/apache/src.
3. Durante la configurazione di PHP (./configure), si può incontrare un errore simile al seguente:
checking lex output file root... ./configure: lex: command not found configure: error: cannot find output from lex; giving up |
Leggere attentamente le istruzioni di installazione e ricordarsi che per compilare il PHP occorre disporre sia di flex sia di bison. In base al proprio sistema si dovrà installare bison e flex dai sorgenti o da pacchetti tipo RPM.
4. Quando avvio Apache ottengo il seguente messaggio:
fatal: relocation error: file /path/to/libphp4.so: symbol ap_block_alarms: referenced symbol not found |
Questo errore solitamente accade quando si compila il cuore di Apache come libreria DSO per utilizzo condiviso. Provare a riconfigurare Apache, prestando attenzione all'impostazione dei seguenti flag:
--enable-shared=max --enable-rule=SHARED_CORE |
Per maggiori dettagli leggere INSTALL nella directory principale di Apache, oppure le pagine del manuale DSO.
5. Quando eseguo la configurazione, un messaggio di errore mi dice che non è possibile trovare file inclusi o librerie per GD, gdbm o qualche altro pacchetto!
Puoi ordinare allo script di configurazione di cercare di gli header e le librerie anche in posizioni non standard specificando flag addizionali da passare al preprocessore C, come:
CPPFLAGS=.I/percorso/da/includere LDFLAGS=-L/percorso/per/la/libreria ./configure |
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. Quando si compila il PHP con MySQL, la configurazione viene eseguita correttamente, ma durante il make si ottiene un errore simile al seguente: ext/mysql/libmysql/my_tempnam.o(.text+0x46): In function my_tempnam': /php4/ext/mysql/libmysql/my_tempnam.c:103: the use of tempnam' is dangerous, better use mkstemp', che cosa c'è di sbagliato?
Primo, è importante realizzare che questo è un Warning e non un errore fatale. Poichè spesso questo è l'ultimo messaggio visibile durante il make, sembra indicare un errore fatale, ma non lo è. Certamente, se si imposta il compilatore ad uscire anche sui warning, questo lo farà. Ricordarsi inoltre, che il supporto per MySQL è abilitato per default.
Nota: Dal PHP 4.3.2, sarà visualizzato il seguente testo dopo il completamento della compila (make):
Build complete. (It is safe to ignore warnings about tempnam and tmpnam).
16. Voglio aggiornare il mio PHP. Dove posso trovare la linea di ./configure che è stata usata per creare la mia attuale versione di PHP?
Puoi cercare nel file config.nice nel sorgente della tua attuale installazione di PHP o eseguire questo semplice script:
<?php phpinfo(); ?> |
17. Quando si compila il PHP con la libreria GD, si ottiene dei strani errori di compila oppure dei segfault durante l'esecuzione.
Essere certi che la libreria GD e PHP condividano le medesime librerie (ad esempio libpng).
18. Quando si compila il PHP sembra di avere errori casuali, tipo blocchi. Se interessa sto utilizzando Solaris.
L'uso di utility non GNU per la compila del PHP può creare problemi. Occorre essere certi di utilizzare i tool GNU per essere certi della corretta compila del PHP. Ad esempio, con Solaris, l'utilizzo di SunOS BSD-compatibile con la versione di Solaris di sed crea dei problemi, ma utilizzando la versione GNU o Sun POSIX (xpg4) di sed non si avranno problemi. Riferimenti: GNU sed, GNU flex e GNU bison.
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/kb/q160422/ and the manual section on HTTP Authentication .
You have to change the Go to Internet Information Services. Locate your PHP file and go to its properties. Go to the File Security tab, Edit -< Anonymous access and authentication control.
You can fix the problem either by unticking Anonymous Access and leaving Integrated Window Authentication ticked, or, by ticking Anonymous Access and editing the user as he may not have the access right.
10. My PHP script works on IE and Lynx, but on Netscape some of my output is missing. When I do a "View Source" I see the content in IE but not in Netscape.
Netscape is more strict regarding HTML tags (such as tables) then IE. Running your HTML output through a HTML validator, such as validator.w3.org, might be helpful. For example, a missing </table> might cause this.
Also, both IE and Lynx ignore any NULs (\0) in the HTML stream, Netscape does not. The best way to check for this is to compile the command line version of PHP (also known as the CGI version) and run your script from the command line. In *nix, pipe it through od -c and look for any \0 characters. If you are on Windows you need to find an editor or some other program that lets you look at binary files. When Netscape sees a NUL in a file it will typically not output anything else on that line whereas both IE and Lynx will.
In order to embed <?xml straight into your PHP code, you'll have to turn off short tags by having the PHP directive short_open_tags set to 0. You cannot set this directive with ini_set(). Regardless of short_open_tags being on or off, you can do something like: <?php echo '<?xml'; ?>. The default for this directive is on.
12. How can I use PHP with FrontPage or some other HTML editor that insists on moving my code around?
One of the easiest things to do is to enable using ASP tags in your PHP code. This allows you to use the ASP-style <% and %> code delimiters. Some of the popular HTML editors handle those more intelligently (for now). To enable the ASP-style tags, you need to set the asp_tags php.ini variable, or use the appropriate Apache directive.
Read the manual page on predefined variables as it includes a partial list of predefined variables available to your script. A complete list of available variables (and much more information) can be seen by calling the phpinfo() function. Be sure to read the manual section on variables from outside of PHP as it describes common scenarios for external variables, like from a HTML form, a Cookie, and the URL.
register_globals: nota importante: A partire da PHP 4.2.0, il valore di default per il parametro register_globals è off. La comunità PHP incoraggia tutti a non basarsi su questo parametro, ma, piuttosto, usare altre strutture come superglobals.
14. How can I generate PDF files without using the non-free and commercial libraries ClibPDF and PDFLib? I'd like something that's free and doesn't require external PDF libraries.
There are a few alternatives written in PHP such as http://www.ros.co.nz/pdf/, http://www.fpdf.org/, http://www.gnuvox.com/pdf4php/, and http://www.potentialtech.com/ppl.php. There is also the Panda module.
15. I'm trying to access one of the standard CGI variables (such as $DOCUMENT_ROOT or $HTTP_REFERER) in a user-defined function, and it can't seem to find it. What's wrong?
It's important to realize that the PHP directive register_globals also affects server and environment variables. When register_globals = off (the default is off since PHP 4.2.0), $DOCUMENT_ROOT will not exist. Instead, use $_SERVER['DOCUMENT_ROOT'] . If register_globals = on then the variables $DOCUMENT_ROOT and $GLOBALS['DOCUMENT_ROOT'] will also exist.
If you're sure register_globals = on and wonder why $DOCUMENT_ROOT isn't available inside functions, it's because these are like any other variables and would require global $DOCUMENT_ROOT inside the function. See also the manual page on variable scope. It's preferred to code with register_globals = off.
Matrici superglobali: note di disponibilità: A partire da PHP 4.1.0, sono disponibili le matrici superglobali quali $_GET , $_POST, e $_SERVER, ecc. Per maggiori dettagli, si rimanda al capitolo superglobals del manuale
16. A few PHP directives may also take on shorthand byte values, as opposed to only integer byte values. What are all the available shorthand byte options? And can I use these outside of php.ini?
The available options are K (for Kilobytes), M (for Megabytes) and G (for Gigabytes; available since PHP 5.1.0), these are case insensitive. Anything else assumes bytes. 1M equals one Megabyte or 1048576 bytes. 1K equals one Kilobyte or 1024 bytes. You may not use these shorthand notations outside of php.ini, instead use an integer value of bytes. See the ini_get() documentation for an example on how to convert these values.
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'].
Nota: Spaces in request variable names are converted to underscores.
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.
In PHP 5, il modulo COM genera un'eccezione com_exception, che può essere catturata per determinare come comporstarsi.
In PHP 4 non è possibile bloccare gli errori COM nei soliti modi disponibili in PHP (@, track_errors, ...).
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:
<?php $word = new COM("C:\docs\word.doc"); ?> |
Questo creerà una nuova istanza se non esistono istanza in esecuzione disponibili, o ritornerà un handle, se disponibile, dell'istanza in esecuzione.
Si possono creare i event sink e collegarli tramite com_event_sink(). Inoltre si può utilizzare com_print_typeinfo() per fare generare al PHP lo scheletro di una classe per gestire un event sink.
13. Sto riscontrando dei problemi quando provo a invocare un metodo di un oggetto COM che espone più di una interfaccia. Che cosa posso fare?
La risposta è semplice. Non so bene il perchè, ma non puoi farci niente. Se qualcuno avesse informazioni specifiche riguardo a ciò, è pregato di farle pervenire a questo indirizzo :)
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.
Sebbene in PHP 3non esista il supporto nativo alle sessioni, esistono moduli di terze parti che offrono funzionalità di sessione. Il modulo più noto era PHPLIB.
This faq section will help you migrate from PHP 4 to PHP 5.
Although PHP 5 offers many new features, it's designed to be as compatible with earlier versions of PHP as possible with little functionality being broken in the process.
Be sure to read the appropriate PHP 5 migration appendix of this manual as it contains even more information on the topic of migrating to PHP 5.
MySQL is supported with the only change being that MySQL support is no longer enabled by default in PHP 5. This essentially means that PHP doesn't include the --with-mysql option in the configure line so that you must now manually do this when compiling PHP. Windows users will edit php.ini and enable the php_mysql.dll DLL as in PHP 4 no such DLL existed, it was simply built into your Windows PHP binaries.
Also, the MySQL client libraries are no longer bundled with PHP. More details on this topic are covered in the following FAQ and be sure to read the MySQL section for details on installing MySQL. An example configure line would be --with-mysql=/usr while Windows users will need the libmySQL.dll available to the system.
3. I hear PHP 5 has an entirely new OOP model, will my existing OOP code work? Where do I find information on these new OOP features?
The main change in PHP 5 is to the OOP model as PHP 5 now uses the Zend Engine 2.0. The zend.ze1_compatibility_mode directive enables compatability with the Zend Engine 1.0 (PHP 4).
The new OOP model is documented in the OOP language reference and OOP migration appendix sections.
4. So besides the new OOP model, what else has changed in PHP 5? Also, is there a PHP 5 specific version of the PHP manual?
Few other changes exist, see the migration 5 appendix for details. There won't be a PHP 5 specific version of the manual as the bulk of PHP remains the same.
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.
Today, PHP is being used by hundreds of thousands of developers (estimated), and several million sites report as having it installed, which accounts for over 20% of the domains on the Internet.
PHP's development team includes dozens of developers, as well as dozens others working on PHP-related projects such as PEAR and the documentation project.
PHP 5 was released in July 2004 after long development and several pre-releases. It is mainly driven by its core, the Zend Engine 2.0 with a new object model and dozens of other new features. To get more information on this engine, see its webpage.
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:
There are some new reserved keywords.
strrpos() and strripos() now use the entire string as a needle.
Illegal use of string offsets causes E_ERROR instead of E_WARNING. An example illegal use is: $str = 'abc'; unset($str[0]);.
array_merge() was changed to accept only arrays. If a non-array variable is passed, a E_WARNING will be thrown for every such parameter. Be careful because your code may start emitting E_WARNING out of the blue.
PATH_TRANSLATED server variable is no longer set implicitly under Apache2 SAPI in contrast to the situation in PHP 4, where it is set to the same value as the SCRIPT_FILENAME server variable when it is not populated by Apache. This change was made to comply with the CGI specification. Please refer to bug #23610 for further information, and see also the $_SERVER['PATH_TRANSLATED'] description in the manual. This issue also affects PHP versions >= 4.3.2.
The T_ML_COMMENT constant is no longer defined by the Tokenizer extension. If error_reporting is set to E_ALL, PHP will generate a notice. Although the T_ML_COMMENT was never used at all, it was defined in PHP 4. In both PHP 4 and PHP 5 // and /* */ are resolved as the T_COMMENT constant. However the PHPDoc style comments /** */, which starting PHP 5 are parsed by PHP, are recognized as T_DOC_COMMENT.
$_SERVER should be populated with argc and argv if variables_order includes "S". If you have specifically configured your system to not create $_SERVER, then of course it shouldn't be there. The change was to always make argc and argv available in the CLI version regardless of the variables_order setting. As in, the CLI version will now always populate the global $argc and $argv variables.
An object with no properties is no longer considered "empty".
In some cases classes must be declared before used. It only happens only if some of the new features of PHP 5 are used. Otherwise the behaviour is the old.
get_class(), get_parent_class() and get_class_methods() now return the name of the classes/methods as they were declared (case-sensitive) which may lead to problems in older scripts that rely on the previous behaviour (the class/method name was always returned lowercased). A possible solution is to search for those functions in all your scripts and use strtolower().
This case sensitivity change also applies to the magical predefined constants __CLASS__, __METHOD__, and __FUNCTION__. The values are returned exactly as they're declared (case-sensitive).
ip2long() now returns FALSE when an invalid IP address is passed as argument to the function, and no longer -1.
If there are functions defined in the included file, they can be used in the main file independent if they are before return() or after. If the file is included twice, PHP 5 issues fatal error because functions were already declared, while PHP 4 doesn't complain about it. It is recommended to use include_once() instead of checking if the file was already included and conditionally return inside the included file.
include_once() and require_once() first normalize the path of included file on Windows so that including A.php and a.php include the file just once.
Esempio B-1. strrpos() and strripos() now use the entire string as a needle
|
In PHP 5 there were some changes in CLI and CGI filenames. In PHP 5, the CGI version was renamed to php-cgi.exe (previously php.exe) and the CLI version now sits in the main directory (previously cli/php.exe).
In PHP 5 it was also introduced a new mode: php-win.exe. This is equal to the CLI version, except that php-win doesn't output anything and thus provides no console (no "dos box" appears on the screen). This behavior is similar to php-gtk.
In PHP 5, the CLI version will always populate the global $argv and $argc variables regardless of any php.ini directive setting. Even having register_argc_argv set to off will have no affect in CLI.
See also the commandline reference.
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:
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:
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:
array_combine() - Creates an array by using one array for keys and another for its values
array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
array_udiff() - Computes the difference of arrays by using a callback function for data comparison
array_udiff_assoc() - Computes the difference of arrays with additional index check. The data is compared by using a callback function
array_udiff_uassoc() - Computes the difference of arrays with additional index check. The data is compared by using a callback function. The index check is done by a callback function also
array_walk_recursive() - Apply a user function recursively to every member of an array
array_uintersect_assoc() - Computes the intersection of arrays with additional index check. The data is compared by using a callback function
array_uintersect_uassoc() - Computes the intersection of arrays with additional index check. Both the data and the indexes are compared by using a callback functions
array_uintersect() - Computes the intersection of arrays. The data is compared by using a callback function
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_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
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
idate() - Format a local time/date as integer
date_sunset() - Time of sunset for a given day and location
date_sunrise() - Time of sunrise for a given day and location
time_nanosleep() - Delay for a number of seconds and nano seconds
str_split() - Convert a string to an array
strpbrk() - Search a string for any of a set of characters
substr_compare() - Binary safe optionally case insensitive comparison of two strings from an offset, up to length characters
Other:
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
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
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.
The new Object Model is documented at the Language Reference.
See also the zend.ze1_compatibility_mode directive for compatability with PHP 4.
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: modalità sicura (if you could override safe mode settings in .htaccess files, it would defeat modalità sicura's purpose). In contrast, Admin values can modify the value of any PHP directive.
To make the transition process easier, PHP 4 is bundled with scripts that automatically convert your Apache configuration and .htaccess files to work with both PHP 3 and PHP 4. These scripts do NOT convert the mime type lines! You have to convert these yourself.
To convert your Apache configuration files, run the apconf-conv.sh script (available in the scripts/apache/ directory). For example:
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.
L'istruzione old_function permette di dichiarare una funzione utilizzando una sintassi simile a PHP/FI2 (tranne che occorre sostituire 'function' con 'old_function').
Questa è un'opzione sconsigliata e dovrebbe essere utilizzata solo dal convertitore PHP/FI2->PHP 3.
Avvertimento |
Funzioni dichiarate come old_function non possono essere chiamata dal codice interno al PHP. Tra le altre cose, questo significa che si possono utilizzare queste funzioni in usort(), array_walk(), e register_shutdown_function(). Si può aggirare questa limitazione scrivendo un proprio wrapper (nel normale metodo PHP 3) e da qui chiamare la old_function. |
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
|
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.
Questo elenco include tutte le impostazioni del php.ini che possono essere impostate in fase di setup del PHP.
Tabella G-1. Opzioni di configurazione
Nome | Default | Modificabile | Modifiche |
---|---|---|---|
allow_call_time_pass_reference | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.0.0. |
allow_url_fopen | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.3.4. Disponibile da PHP 4.0.4. |
always_populate_raw_post_data | "0" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. Disponibile da PHP 4.1.0. |
apc.cache_by_default | "1" | PHP_INI_SYSTEM | |
apc.enabled | "1" | PHP_INI_SYSTEM | |
apc.filters | "" | PHP_INI_SYSTEM | |
apc.gc_ttl | "3600" | PHP_INI_SYSTEM | |
apc.mmap_file_mask | NULL | PHP_INI_SYSTEM | |
apc.num_files_hint | "1000" | PHP_INI_SYSTEM | |
apc.optimization | "0" | PHP_INI_SYSTEM | |
apc.shm_segments | "1" | PHP_INI_SYSTEM | |
apc.shm_size | "30" | PHP_INI_SYSTEM | |
apc.slam_defense | "0" | PHP_INI_SYSTEM | |
apc.ttl | "0" | PHP_INI_SYSTEM | |
apc.user_entries_hint | "100" | PHP_INI_SYSTEM | |
apc.user_ttl | "0" | PHP_INI_SYSTEM | |
apd.dumpdir | NULL | PHP_INI_ALL | |
apd.statement_tracing | "0" | PHP_INI_ALL | |
arg_separator.input | "&" | PHP_INI_PERDIR | Disponibile da PHP 4.0.5. |
arg_separator.output | "&" | PHP_INI_ALL | Disponibile da PHP 4.0.5. |
asp_tags | "0" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.0.0. |
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 | PHP_INI_ALL in PHP <= 4.2.3. |
auto_detect_line_endings | "0" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
auto_globals_jit | "1" | PHP_INI_PERDIR | Disponibile da PHP 5.0.0. |
auto_prepend_file | NULL | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. |
bcmath.scale | "0" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
blenc.key_file | "/usr/local/etc/blenckeys" | PHP_INI_ALL | |
browscap | NULL | PHP_INI_SYSTEM | |
child_terminate | "0" | PHP_INI_ALL | Disponibile da PHP 4.0.5. |
com.allow_dcom | "0" | PHP_INI_SYSTEM | Disponibile da PHP 4.0.5. |
com.autoregister_casesensitive | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Disponibile da PHP 4.1.0. |
com.autoregister_typelib | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Disponibile da PHP 4.1.0. |
com.autoregister_verbose | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Disponibile da PHP 4.1.0. |
com.code_page | "" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
com.typelib_file | "" | PHP_INI_SYSTEM | Disponibile da PHP 4.0.5. |
crack.default_dictionary | NULL | PHP_INI_SYSTEM | Disponibile da PHP 4.0.5. |
daffodildb.default_host | "localhost" | PHP_INI_ALL | |
daffodildb.default_password | "daffodil" | PHP_INI_ALL | |
daffodildb.default_socket | NULL | PHP_INI_ALL | |
daffodildb.default_user | "DAFFODIL" | PHP_INI_ALL | |
daffodildb.port | "3456" | PHP_INI_ALL | |
date.default_latitude | "31.7667" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
date.default_longitude | "35.2333" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
date.sunrise_zenith | "90.83" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
date.sunset_zenith | "90.83" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
dba.default_handler | "" | PHP_INI_ALL | Disponibile da PHP 4.3.3. |
dbx.colnames_case | "unchanged" | PHP_INI_SYSTEM | Disponibile da PHP 4.3.0. |
default_charset | "" | PHP_INI_ALL | |
default_mimetype | "text/html" | PHP_INI_ALL | |
default_socket_timeout | "60" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
define_syslog_variables | "0" | PHP_INI_ALL | |
disable_classes | "" | php.ini only | Disponibile da PHP 4.3.2. |
disable_functions | "" | php.ini only | Disponibile da PHP 4.0.1. |
display_errors | "1" | PHP_INI_ALL | |
display_startup_errors | "0" | PHP_INI_ALL | Disponibile da PHP 4.0.3. |
docref_ext | "" | PHP_INI_ALL | Disponibile da PHP 4.3.2. |
docref_root | "" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
doc_root | NULL | PHP_INI_SYSTEM | |
enable_dl | "1" | PHP_INI_SYSTEM | |
engine | "1" | PHP_INI_ALL | Disponibile da PHP 4.0.5. |
error_append_string | NULL | PHP_INI_ALL | |
error_log | NULL | PHP_INI_ALL | |
error_prepend_string | NULL | PHP_INI_ALL | |
error_reporting | NULL | PHP_INI_ALL | |
exif.decode_jis_intel | "JIS" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
exif.decode_jis_motorola | "JIS" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
exif.decode_unicode_intel | "UCS-2LE" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
exif.decode_unicode_motorola | "UCS-2BE" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
exif.encode_jis | "" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
exif.encode_unicode | "ISO-8859-15" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
expose_php | "1" | php.ini only | |
extension_dir | "/path/to/php" | PHP_INI_SYSTEM | |
fbsql.allow_persistent | "1" | PHP_INI_SYSTEM | Disponibile da PHP 4.2.0. |
fbsql.autocommit | "1" | PHP_INI_SYSTEM | Disponibile da PHP 4.0.6. |
fbsql.batchsize | "1000" | PHP_INI_ALL | Disponibile da PHP 5-cvs. |
fbsql.default_database | "" | PHP_INI_SYSTEM | Disponibile da PHP 4.0.6. |
fbsql.default_database_password | "" | PHP_INI_SYSTEM | Disponibile da PHP 4.0.6. |
fbsql.default_host | NULL | PHP_INI_SYSTEM | Disponibile da PHP 4.0.6. |
fbsql.default_password | "" | PHP_INI_SYSTEM | Disponibile da PHP 4.0.6. |
fbsql.default_user | "_SYSTEM" | PHP_INI_SYSTEM | Disponibile da PHP 4.0.6. |
fbsql.generate_warnings | "0" | PHP_INI_SYSTEM | Disponibile da PHP 4.0.6. |
fbsql.max_connections | "128" | PHP_INI_SYSTEM | Disponibile da PHP 4.0.6. |
fbsql.max_links | "128" | PHP_INI_SYSTEM | Disponibile da PHP 4.0.6. |
fbsql.max_persistent | "-1" | PHP_INI_SYSTEM | Disponibile da PHP 4.0.6. |
fbsql.max_results | "128" | PHP_INI_SYSTEM | Disponibile da PHP 4.0.6. |
file_uploads | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.2.3. Disponibile da PHP 4.0.3. |
filter.default | "notags" | PHP_INI_ALL | |
highlight.bg | "#FFFFFF" | PHP_INI_ALL | |
highlight.comment | "#FF8000" | PHP_INI_ALL | |
highlight.default | "#0000BB" | PHP_INI_ALL | |
highlight.html | "#000000" | PHP_INI_ALL | |
highlight.keyword | "#007700" | PHP_INI_ALL | |
highlight.string | "#DD0000" | PHP_INI_ALL | |
html_errors | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP <= 4.2.3. Disponibile da PHP 4.0.2. |
http.allowed_methods | "GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE, CONNECT, " | PHP_INI_ALL | |
hyperwave.allow_persistent | "0" | PHP_INI_SYSTEM | Disponibile da PHP 4.3.2. |
hyperwave.default_port | "418" | PHP_INI_ALL | |
ibase.allow_persistent | "1" | PHP_INI_SYSTEM | |
ibase.dateformat | "%Y-%m-%d" | PHP_INI_ALL | |
ibase.default_charset | NULL | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
ibase.default_db | NULL | PHP_INI_SYSTEM | Disponibile da PHP 5.0.0. |
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 | |
ibm_db2.binmode | "0" | PHP_INI_ALL | |
iconv.input_encoding | "ISO-8859-1" | PHP_INI_ALL | Disponibile da PHP 4.0.5. |
iconv.internal_encoding | "ISO-8859-1" | PHP_INI_ALL | Disponibile da PHP 4.0.5. |
iconv.output_encoding | "ISO-8859-1" | PHP_INI_ALL | Disponibile da PHP 4.0.5. |
ifx.allow_persistent | "1" | PHP_INI_SYSTEM | |
ifx.blobinfile | "1" | PHP_INI_ALL | |
ifx.byteasvarchar | "0" | PHP_INI_ALL | |
ifx.charasvarchar | "0" | PHP_INI_ALL | |
ifx.default_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 | Disponibile da PHP 4.3.0. |
ignore_repeated_source | "0" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
ignore_user_abort | "0" | PHP_INI_ALL | |
implicit_flush | "0" | PHP_INI_ALL | PHP_INI_PERDIR in PHP <= 4.2.3. |
include_path | ".;/path/to/php/pear" | PHP_INI_ALL | |
ingres.allow_persistent | "1" | PHP_INI_SYSTEM | Disponibile da PHP 4.0.2. |
ingres.default_database | NULL | PHP_INI_ALL | Disponibile da PHP 4.0.2. |
ingres.default_password | NULL | PHP_INI_ALL | Disponibile da PHP 4.0.2. |
ingres.default_user | NULL | PHP_INI_ALL | Disponibile da PHP 4.0.2. |
ingres.max_links | "-1" | PHP_INI_SYSTEM | Disponibile da PHP 4.0.2. |
ingres.max_persistent | "-1" | PHP_INI_SYSTEM | Disponibile da PHP 4.0.2. |
ircg.control_user | "nobody" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
ircg.keep_alive_interval | "60" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
ircg.max_format_message_sets | "12" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
ircg.shared_mem_size | "6000000" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
ircg.work_dir | "/tmp/ircg" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
last_modified | "0" | PHP_INI_ALL | Disponibile da PHP 4.0.5. |
ldap.max_links | "-1" | PHP_INI_SYSTEM | |
log_errors | "0" | PHP_INI_ALL | |
log_errors_max_len | "1024" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
magic_quotes_gpc | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. |
magic_quotes_runtime | "0" | PHP_INI_ALL | |
magic_quotes_sybase | "0" | PHP_INI_ALL | |
mail.force_extra_parameters | NULL | PHP_INI_PERDIR | Disponibile da PHP 5.0.0. |
mailparse.def_charset | "us-ascii" | PHP_INI_ALL | Disponibile da PHP 4.1.0. |
maxdb.default_db | NULL | PHP_INI_ALL | |
maxdb.default_host | NULL | PHP_INI_ALL | |
maxdb.default_pw | NULL | PHP_INI_ALL | |
maxdb.default_user | NULL | PHP_INI_ALL | |
maxdb.long_readlen | "200" | PHP_INI_ALL | |
max_execution_time | "30" | PHP_INI_ALL | |
max_input_time | "-1" | PHP_INI_PERDIR | Disponibile da PHP 4.3.0. |
mbstring.detect_order | NULL | PHP_INI_ALL | Disponibile da PHP 4.0.6. |
mbstring.encoding_translation | "0" | PHP_INI_PERDIR | Disponibile da PHP 4.3.0. |
mbstring.func_overload | "0" | PHP_INI_PERDIR | PHP_INI_SYSTEM in PHP <= 4.2.3. Disponibile da PHP 4.2.0. |
mbstring.http_input | "pass" | PHP_INI_ALL | Disponibile da PHP 4.0.6. |
mbstring.http_output | "pass" | PHP_INI_ALL | Disponibile da PHP 4.0.6. |
mbstring.internal_encoding | NULL | PHP_INI_ALL | Disponibile da PHP 4.0.6. |
mbstring.language | "neutral" | PHP_INI_PERDIR | Disponibile da PHP 4.3.0. |
mbstring.script_encoding | NULL | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
mbstring.substitute_character | NULL | PHP_INI_ALL | Disponibile da PHP 4.0.6. |
mcrypt.algorithms_dir | NULL | PHP_INI_ALL | Disponibile da PHP 4.0.2. |
mcrypt.modes_dir | NULL | PHP_INI_ALL | Disponibile da PHP 4.0.2. |
memory_limit | "8M" | PHP_INI_ALL | |
mime_magic.debug | "0" | PHP_INI_SYSTEM | Disponibile da PHP 5.0.0. |
mime_magic.magicfile | "/path/to/php/magic.mime" | PHP_INI_SYSTEM | Disponibile da PHP 4.3.0. |
mssql.allow_persistent | "1" | PHP_INI_SYSTEM | |
mssql.batchsize | "0" | PHP_INI_ALL | Disponibile da PHP 4.0.4. |
mssql.compatability_mode | "0" | PHP_INI_ALL | |
mssql.connect_timeout | "5" | PHP_INI_ALL | |
mssql.datetimeconvert | "1" | PHP_INI_ALL | Disponibile da PHP 4.2.0. |
mssql.max_links | "-1" | PHP_INI_SYSTEM | |
mssql.max_persistent | "-1" | PHP_INI_SYSTEM | |
mssql.max_procs | "25" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
mssql.min_error_severity | "10" | PHP_INI_ALL | |
mssql.min_message_severity | "10" | PHP_INI_ALL | |
mssql.secure_connection | "0" | PHP_INI_SYSTEM | Disponibile da PHP 4.3.0. |
mssql.textlimit | "-1" | PHP_INI_ALL | |
mssql.textsize | "-1" | PHP_INI_ALL | |
mssql.timeout | "60" | PHP_INI_ALL | Disponibile da PHP 4.1.0. |
mysql.allow_persistent | "1" | PHP_INI_SYSTEM | |
mysql.connect_timeout | "60" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP <= 4.3.2. Disponibile da PHP 4.3.0. |
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 | Disponibile da PHP 4.0.1. |
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 | Disponibile da PHP 4.3.0. |
mysqli.default_host | NULL | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
mysqli.default_port | "3306" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
mysqli.default_pw | NULL | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
mysqli.default_socket | NULL | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
mysqli.default_user | NULL | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
mysqli.max_links | "-1" | PHP_INI_SYSTEM | Disponibile da PHP 5.0.0. |
mysqli.reconnect | "0" | PHP_INI_SYSTEM | Disponibile da PHP 5.0.0. |
namazu.debugmode | "0" | PHP_INI_ALL | |
namazu.lang | NULL | PHP_INI_ALL | |
namazu.loggingmode | "0" | PHP_INI_ALL | |
namazu.sortmethod | NULL | PHP_INI_ALL | |
namazu.sortorder | NULL | PHP_INI_ALL | |
nsapi.read_timeout | "60" | PHP_INI_ALL | Disponibile da PHP 4.3.3. |
odbc.allow_persistent | "1" | PHP_INI_SYSTEM | |
odbc.check_persistent | "1" | PHP_INI_SYSTEM | |
odbc.defaultbinmode | "1" | PHP_INI_ALL | |
odbc.defaultlrl | "4096" | PHP_INI_ALL | |
odbc.default_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 | |
opendirectory.max_refs | "-1" | PHP_INI_ALL | |
opendirectory.separator | "/" | PHP_INI_ALL | |
open_basedir | NULL | PHP_INI_SYSTEM | |
output_buffering | "0" | PHP_INI_PERDIR | |
output_handler | NULL | PHP_INI_PERDIR | Disponibile da PHP 4.0.4. |
pfpro.defaulthost | "test-payflow.verisign.com" | PHP_INI_ALL | Disponibile da PHP 4.0.2. |
pfpro.defaultport | "443" | PHP_INI_ALL | Disponibile da PHP 4.0.2. |
pfpro.defaulttimeout | "30" | PHP_INI_ALL | Disponibile da PHP 4.0.2. |
pfpro.proxyaddress | "" | PHP_INI_ALL | Disponibile da PHP 4.0.2. |
pfpro.proxylogon | "" | PHP_INI_ALL | Disponibile da PHP 4.0.2. |
pfpro.proxypassword | "" | PHP_INI_ALL | Disponibile da PHP 4.0.2. |
pfpro.proxyport | "" | PHP_INI_ALL | Disponibile da PHP 4.0.2. |
pgsql.allow_persistent | "1" | PHP_INI_SYSTEM | |
pgsql.auto_reset_persistent | "0" | PHP_INI_SYSTEM | Disponibile da PHP 4.2.0. |
pgsql.ignore_notice | "0" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
pgsql.log_notice | "0" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
pgsql.max_links | "-1" | PHP_INI_SYSTEM | |
pgsql.max_persistent | "-1" | PHP_INI_SYSTEM | |
post_max_size | "8M" | PHP_INI_PERDIR | PHP_INI_SYSTEM in PHP <= 4.2.3. Disponibile da PHP 4.0.3. |
precision | "14" | PHP_INI_ALL | |
printer.default_printer | "" | PHP_INI_ALL | |
realpath_cache_size | "16K" | PHP_INI_SYSTEM | Disponibile da PHP 5-cvs. |
realpath_cache_ttl | "120" | PHP_INI_SYSTEM | Disponibile da PHP 5-cvs. |
register_argc_argv | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. |
register_globals | "0" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. |
register_long_arrays | "1" | PHP_INI_PERDIR | Disponibile da PHP 5.0.0. |
report_memleaks | "1" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
report_zend_debug | "1" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
safe_mode | "0" | PHP_INI_SYSTEM | |
safe_mode_allowed_env_vars | "PHP_" | PHP_INI_SYSTEM | |
safe_mode_exec_dir | "" | PHP_INI_SYSTEM | |
safe_mode_gid | "0" | PHP_INI_SYSTEM | Disponibile da PHP 4.1.0. |
safe_mode_include_dir | NULL | PHP_INI_SYSTEM | Disponibile da PHP 4.1.0. |
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 | Disponibile da PHP 4.3.2. |
session.auto_start | "0" | PHP_INI_ALL | |
session.bug_compat_42 | "1" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
session.bug_compat_warn | "1" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
session.cache_expire | "180" | PHP_INI_ALL | |
session.cache_limiter | "nocache" | PHP_INI_ALL | |
session.cookie_domain | "" | PHP_INI_ALL | |
session.cookie_lifetime | "0" | PHP_INI_ALL | |
session.cookie_path | "/" | PHP_INI_ALL | |
session.cookie_secure | "" | PHP_INI_ALL | Disponibile da PHP 4.0.4. |
session.entropy_file | "" | PHP_INI_ALL | |
session.entropy_length | "0" | PHP_INI_ALL | |
session.gc_divisor | "100" | PHP_INI_ALL | Disponibile da PHP 4.3.2. |
session.gc_maxlifetime | "1440" | PHP_INI_ALL | |
session.gc_probability | "1" | PHP_INI_ALL | |
session.hash_bits_per_character | "4" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
session.hash_function | "0" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
session.name | "PHPSESSID" | PHP_INI_ALL | |
session.referer_check | "" | PHP_INI_ALL | |
session.save_handler | "files" | PHP_INI_ALL | |
session.save_path | "" | PHP_INI_ALL | |
session.serialize_handler | "php" | PHP_INI_ALL | |
session.use_cookies | "1" | PHP_INI_ALL | |
session.use_only_cookies | "0" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
session.use_trans_sid | "0" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.2.3. PHP_INI_PERDIR in PHP < 5. Disponibile da PHP 4.0.3. |
session_pgsql.create_table | "1" | PHP_INI_SYSTEM | |
session_pgsql.db | "host=localhost dbname=php_session user=nobody" | PHP_INI_SYSTEM | |
session_pgsql.disable | "0" | PHP_INI_SYSTEM | |
session_pgsql.failover_mode | "0" | PHP_INI_SYSTEM | |
session_pgsql.gc_interval | "3600" | PHP_INI_SYSTEM | |
session_pgsql.keep_expired | "0" | PHP_INI_SYSTEM | |
session_pgsql.sem_file_name | "/tmp/php_session_pgsql" | PHP_INI_SYSTEM | |
session_pgsql.serializable | "0" | PHP_INI_SYSTEM | |
session_pgsql.short_circuit | "0" | PHP_INI_SYSTEM | |
session_pgsql.use_app_vars | "0" | PHP_INI_SYSTEM | |
session_pgsql.vacuum_interval | "21600" | PHP_INI_SYSTEM | |
short_open_tag | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.0.0. |
simple_cvs.authMethod | "0" | PHP_INI_ALL | |
simple_cvs.compressionLevel | "0" | PHP_INI_ALL | |
simple_cvs.cvsRoot | "0" | PHP_INI_ALL | |
simple_cvs.host | "0" | PHP_INI_ALL | |
simple_cvs.moduleName | "0" | PHP_INI_ALL | |
simple_cvs.userName | "0" | PHP_INI_ALL | |
simple_cvs.workingDir | "0" | PHP_INI_ALL | |
SMTP | "localhost" | PHP_INI_ALL | |
smtp_port | "25" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
soap.wsdl_cache_dir | "/tmp" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
soap.wsdl_cache_enabled | "1" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
soap.wsdl_cache_ttl | "86400" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
sql.safe_mode | "0" | PHP_INI_SYSTEM | |
sqlite.assoc_case | "0" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
sybct.allow_persistent | "1" | PHP_INI_SYSTEM | Disponibile da PHP 4.0.4. |
sybct.deadlock_retry_count | "0" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
sybct.hostname | NULL | PHP_INI_ALL | Disponibile da PHP 4.0.4. |
sybct.login_timeout | "-1" | PHP_INI_ALL | Disponibile da PHP 4.3.5. |
sybct.max_links | "-1" | PHP_INI_SYSTEM | Disponibile da PHP 4.0.4. |
sybct.max_persistent | "-1" | PHP_INI_SYSTEM | Disponibile da PHP 4.0.4. |
sybct.min_client_severity | "10" | PHP_INI_ALL | Disponibile da PHP 4.0.4. |
sybct.min_server_severity | "10" | PHP_INI_ALL | Disponibile da PHP 4.0.4. |
tidy.clean_output | "0" | PHP_INI_PERDIR | Disponibile da PHP 5.0.0. |
tidy.default_config | "" | PHP_INI_SYSTEM | Disponibile da PHP 5.0.0. |
track_errors | "0" | PHP_INI_ALL | |
unserialize_callback_func | NULL | PHP_INI_ALL | Disponibile da PHP 4.2.0. |
upload_max_filesize | "2M" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. |
upload_tmp_dir | NULL | PHP_INI_SYSTEM | |
url_rewriter.tags | "a=href,area=href,frame=src,form=,fieldset=" | PHP_INI_ALL | Disponibile da PHP 4.0.4. |
user_agent | NULL | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
user_dir | NULL | PHP_INI_SYSTEM | |
valkyrie.auto_validate | "0" | PHP_INI_ALL | |
valkyrie.config_path | NULL | PHP_INI_ALL | |
variables_order | "EGPCS" | PHP_INI_ALL | |
xbithack | "0" | PHP_INI_ALL | Disponibile da PHP 4.0.5. |
xmlrpc_errors | "0" | PHP_INI_SYSTEM | Disponibile da PHP 4.1.0. |
xmlrpc_error_number | "0" | PHP_INI_ALL | Disponibile da PHP 4.1.0. |
xmms.path | "/usr/bin/xmms" | PHP_INI_ALL | |
xmms.session | "0" | PHP_INI_ALL | |
y2k_compliance | "1" | PHP_INI_ALL | |
yaz.keepalive | "120" | PHP_INI_ALL | |
yaz.log_file | NULL | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
yaz.log_mask | NULL | PHP_INI_ALL | |
yaz.max_links | "100" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
zend.ze1_compatibility_mode | "0" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
zlib.output_compression | "0" | PHP_INI_ALL | Disponibile da PHP 4.0.5. |
zlib.output_compression_level | "-1" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
zlib.output_handler | "" | PHP_INI_ALL | Disponibile da PHP 4.3.0. |
Tabella G-2. Definizione delle costanti PHP_INI_*
Costante | Valore | Significato |
---|---|---|
PHP_INI_USER | 1 | Parametro che può essere impostato nello script utente o nelregistry di Winwos |
PHP_INI_PERDIR | 2 | Parametro che può essere impostato in php.ini, .htaccess oppure in httpd.conf |
PHP_INI_SYSTEM | 4 | Parametro che può essere impostato in php.ini o httpd.conf |
PHP_INI_ALL | 7 | Parametro che può essere impostato ovunque |
Questo elenco contiene i parametri 'core' del php.ini che sono utilizzati per configurare il PHP. Le impostazioni gestite dai vari moduli sono elencate e dettagliate nelle pagine di documentazione dei rispettivi moduli; informazioni sui parametri per le sessioni, ad esempio, possono essere troavte nelle pagine delle sessioni.
Tabella G-4. Parametri del linguaggio e configurazioni varie
Nome | Default | Modificabile | Variazioni |
---|---|---|---|
short_open_tag | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.0.0. |
asp_tags | "0" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.0.0. |
precision | "14" | PHP_INI_ALL | |
y2k_compliance | "1" | PHP_INI_ALL | |
allow_call_time_pass_reference | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.0.0. |
expose_php | "1" | php.ini only | |
zend.ze1_compatibility_mode | "0" | PHP_INI_ALL | Disponibile da PHP 5.0.0. |
Breve descrizione dei parametri di configurazione.
Indica se abilitare o meno la forma abbreviata dei tag di apertura del PHP <? ?>). Se si desidera utilizzare il PHP in combinazione con l'XML, occorre disabilitare questa opzione per potere abilitare la riga <?xml ?>. In alternativa occorre stampare il testo con il PHP, ad esempio: <?php echo '<?xml version="1.0"'; ?>. Inoltre, se disabilitato, occorre utilizzare la versione lunga dei tag di apertura del PHP (<?php ?>).
Nota: Questo parametro influisce anche su <?=, la quale è identica a <? echo. L'uso di questa abbreviazione richiede l'abilitazione di short_open_tag.
Abilita l'uso dei tags tipo ASP <% %> in aggiunta agli usuali <?php ?>. Questi includono la scorciatoia per scrivere il valore delle variabili <%= $value %>. Per maggiori informazioni vedere Escaping from HTML.
Nota: Il supporto per i tag stile ASP è sttao aggiunto nella versione 3.0.4.
Il numero di cifre significative usato nella visualizzazione dei numeri in virgola mobile.
Forza la compatibilità con l'anno 2000 (ciò causa problemi con browser non compatibili)
Abilita o meno la possibilità di forzare gli argomenti delle funzioni ad essere passati per riferimento. Questo parametro è deprecato e potrebbe non essere più supportato nelle versioni future di PHP/Zend. Si incoraggia il metodo di specificare quale parametro debba essere passato per riferimento al momento della dichiarazione della funzione. Si suggerisce di impostare l'opzione a off per essere certi che lo script funzioni correttamente con questa impostazione, in modo da predisporsi ad eventuali modifiche future del linguaggio (si riceverà un warning ogni volta che si utilizza questa opzione e i valori saranno passati per valore anzichè per riferimento).
Passare i valori per riferimento al momento della chiamata della funzione viene sconsigliato per motivi di chiarezza del codice. La funzione può modificare il parametro in modo non previsto se non indica questo come passato per riferimento. Per evitare effetti secondari inattesi, è meglio indicare soltanto al momento della dichiarazione della funzione quali parametri saranno passati per riferimento.
Vedere anche Spiegazioni sui riferimenti.
Indica se il PHP deve indicare il fatto che è installato su un server (ad esempi9o aggiungendo una propria sigla all'intestazione del server web). Non vi sono insiti problemi di sicurezza, ma ciò indica che si sta utilizzando il PHP su quel server.
Abilita la compatibilità con lo Zend Engine 1 (PHP 4). Ciò influisce sulle funzioni di clonazione, di cast e di confronto degli oggetti.
Vedere anche la sezione intitolata Migrazione da PHP 4 a PHP 5.
Breve descrizione dei parametri di configurazione.
Questo parametro imposta la dimensione massima in byte di memoria occupabile dallo script. Questo aiuta a impedire che script scritti male utilizzino tutta la memoria del server. Per potere utilizzare questo parametro occorre abilitarlo al momento della compila. Pertanto occorrerà includere nella configurazione la linea: --enable-memory-limit. Si noti che occorre impostare il parametro a -1 se non si desidera impostare limiti di memoria.
Dal PHP 4.3.2, e quando è abilitato il parametro memory_limit, il PHP rende disponibile la funzione memory_get_usage().
When an integer is used, the value is measured in bytes. You may also use shorthand notation as described in this FAQ.
See also: max_execution_time.
Tabella G-6. Parametri di configurazione per la gestione dei dati
Nome | Default | Modificabile | Variazioni |
---|---|---|---|
track_vars | "On" | PHP_INI_?? | |
arg_separator.output | "&" | PHP_INI_ALL | Disponibile da PHP 4.0.5. |
arg_separator.input | "&" | PHP_INI_PERDIR | Disponibile da PHP 4.0.5. |
variables_order | "EGPCS" | PHP_INI_ALL | |
auto_globals_jit | "1" | PHP_INI_PERDIR | Disponibile da PHP 5.0.0. |
register_globals | "0" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. |
register_argc_argv | "1" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. |
register_long_arrays | "1" | PHP_INI_PERDIR | Disponibile da PHP 5.0.0. |
post_max_size | "8M" | PHP_INI_PERDIR | PHP_INI_SYSTEM in PHP <= 4.2.3. Disponibile da PHP 4.0.3. |
gpc_order | "GPC" | PHP_INI_ALL | |
auto_prepend_file | NULL | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. |
auto_append_file | NULL | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. |
default_mimetype | "text/html" | PHP_INI_ALL | |
default_charset | "" | PHP_INI_ALL | |
always_populate_raw_post_data | "0" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. Disponibile da PHP 4.1.0. |
allow_webdav_methods | "0" | PHP_INI_PERDIR |
Breve descrizione dei parametri di configurazione.
Se abilitato, le variabili Environment, GET, POST, Cookie, e Server sono recuperabili nelle rispettive matrici $_ENV, $_GET, $_POST, $_COOKIE e $_SERVER.
Nota: dal PHP 4.0.3, track_vars è sempre impostato a on.
Il separatore degli argomenti utilizzato nelle URL genarate dal PHP.
Lista dei separatori utilizzati dal PHP per la siddivisione dell'URL di input nelle veriabili.
Nota: Qualsiasi carattere inserito in questo parametro sarà considerato un separatore!
Imposta l'ordine di parsing delle variabili EGPCS (Enviroment, GET, POST, Cookie e Server). Per default l'impostazione di questo parametro è "EGPCS". Impostare questo a "GP", ad esempio, per ignorare completamente le variabili di ambiente, i cookie e le variabili del server, e per sovrascrivere qualsiasi variabile GET con una eventuale variabile POST con lo stesso nome.
Vedere anche register_globals.
Quando abilitato, le varaibili SERVER ed ENV sono create al momento del primo utilizzo (Just In Time) invece che all'avvio dello script. Se queste variabili non sono utilizzate dallo script, impostanto questo parametro ad on si ha un beneficio in termini di performance.
I parametri di PHP register_globals, register_long_arrays e register_argc_argv devono essere disabilitati affinché questa impostazione abbia effetto.
Indica se registrare o meno le variabili EGPCS (Environment, GET, POST, Cookie, Server) come variabili globali.
Dal PHP 4.2.0, questo parametro è impostato per default a off.
Guardare il capitolo della sicurezza riguardante l'uso di register_globals per maggiori informazioni.
Si ricorda che register_globals non può essere impostato a runtime da (ini_set()). In alternativa, se permesso dal proprio host, si può utilizzare .htaccess. Un esempio di riga .htaccess: php_flag register_globals off.
Nota: Il parametro register_globals è influenzato da variables_order directive.
Indica al PHP se dichiarare le variabili argv & argc (che contengono le informazioni GET).
Vedere anche command line. Infine, questo parametro è stato introdotto in PHP 4.0.0 ed era sempre impostato a"on" nelle versioni precedenti.
Indica al PHP se registrare o meno le deprecate variabili lunghe $HTTP_*_VARS, vedere variabili predefinite. Quando viene impostato ad On (default), vengono definite le variabili lunghe, tipo $HTTP_GET_VARS, del PHP. Se non si utilizzano, si consiglia di impostare il parametro ad off per motivi di performance. Al posto di queste, utilizzare le matrici $_GET.
Questa impostazione è disponibile dal PHP 5.0.0.
Imposta la dimensione massima dei dati post. Questa impostazione influenza anche gli upload dei file. Per permettere upload di file di grandi dimensioni, il valore impostato deve essere maggiore di upload_max_filesize.
Anche il limite di memoria, memory_limit, se abilitato, può limitare gli upload di file. In termini generali memory_limit dovrebbe essere maggiore di post_max_size.
When an integer is used, the value is measured in bytes. You may also use shorthand notation as described in this FAQ.
Se la dimensione dei dati post è maggiore di post_max_size, le variabili superglobale $_POST e $_FILES sono vuote. Questo può essere rilevato in diversi modi, ad esempio passando una variabile $_GET allo script che processa i dati, tipo <form action="edit.php?processed=1">, e verificare se $_GET['processed'] è impostata.
Imposta l'ordine di parsing delle variabili GET/POST/COOKIE. l'impostazione di default per questo parametro è "GPC". Impostare questo a "GP", ad esempio, farà ignorare i cookie al PHP e farà sovrascrivere qualsiasi variabile GET dalla eventuale omonima variabile POST.
Nota: Questo parametro non è disponibil in PHP 4. Al suo posto utilizzare variables_order.
Indica il nome del file che deve essere parsato prima del file principale. Quetso file viene incluso come se fosse chiamato dalla funzione include(), pertanto si utilizza il parametro include_path.
Il valore speciale none disabilita la funzione.
Specifica il file che deve essere parsato in automatico dopo il file principale. Il file è incluso come se fosse chiamato dalla funzione include() pertanto si utilizza il parametro include_path.
The special value none disables auto-appending.
Nota: Se lo script termina con exit(), l'auto-accodamento non viene eseguito.
Dalla versione 4.0b4, il PHP invia, per default, la codifica del carattere nell'intestazione Content-type:. Per disabilitare questo invio, lasciare vuoto il parametro.
Valorizza sempre la variabile $HTTP_RAW_POST_DATA.
Permette la gestione delle richieste http di WebDAV all'interno di script PHP (ad esempio. PROPFIND, PROPPATCH, MOVE, COPY, etc.). Questo parametro non esisteva prima di PHP 4.3.2. Se si vuole ricevere i dati post di queste richieste, occorre impostare anche always_populate_raw_post_data.
Vedere anche: magic_quotes_gpc, magic_quotes_runtime e magic_quotes_sybase.
Tabella G-7. Parametri di configurazione per percorsi e directory
Nome | Default | Modificabile | Log delle variazioni |
---|---|---|---|
include_path | ".;/path/to/php/pear" | PHP_INI_ALL | |
doc_root | NULL | PHP_INI_SYSTEM | |
user_dir | NULL | PHP_INI_SYSTEM | |
extension_dir | "/path/to/php" | PHP_INI_SYSTEM | |
cgi.fix_pathinfo | "0" | PHP_INI_SYSTEM | |
cgi.force_redirect | "1" | PHP_INI_SYSTEM | |
cgi.redirect_status_env | "" | PHP_INI_SYSTEM | |
fastcgi.impersonate | "0" | PHP_INI_SYSTEM | |
cgi.rfc2616_headers | "0" | PHP_INI_SYSTEM |
Breve descrizione dei parametri di configurazione.
Elenco di directory in cui le funzioni require(), include() e fopen_with_path() cercheranno i files. Il formato è tipo la variabile d'ambiente PATH: una lista di directory separate da due punti in Unix, punto e virgola in Widnows.
L'uso di . nel percorso di include indica, negli include relativi, la directory corrente.
La directory radice (root directory) del PHP sul server. Utilizzata solo se compilata. Se il PHP è configurato con il modalità sicura, ignorerà tutti i file al di fuori di questa directory. Se il PHP non è compilato con il parametro FORCE_REDIRECT, si dovrebbe impostare doc_root se si utilizza il PHP come CGI in qualsiasi web server (oltre che IIS). In alternativa utilizzare il seguente parametro cgi.force_redirect.
Il nome di base della directory utilizzata come home directory degli utenti per i file PHP, ad esempio public_html .
Directory in cui il PHP cerca i moduli caricabili dinamicamente. Vedere anche: enable_dl, e dl().
Quale modulo dinamico caricare quando il PHP parte.
Fornisce il reale PATH_INFO/PATH_TRANSLATED per il CGI. Il precedente comportamento del PHP era di impostare PATH_TRANSLATED a SCRIPT_FILENAME, non curarsi di quale sia PATH_INFO. Per maggiori dettagli su PATH_INFO, vedere le specifiche cgi. Impostare il parametro a 1, si forza il PHP CGI a correggere il percorso in modo conforme alle specifiche. Impostare il parametro a 0 si forza il PHP a comportarsi come solito. Il valore di default è zero. Si dovrebbe correggere gli script affinchè utilizzino SCRIPT_FILENAME piuttosto che PATH_TRANSLATED.
cgi.force_redirect è necessario per garantire maggiore sicurezza al PHP quando gira come CGI in diversi web server. Non impostando il parametro, il PHP lo imposta a on per default. Può essere impostato ad off a proprio rischio.
Nota: Nota per gli utenti di Windows: si può tranquillamente impostare questo parametro a off con IIS, infatti è obbligatorio. Anche con OmniHTTPD o Xitami occorre impostare il parametro a off.
Se cgi.force_redirect è impostato ad on, e non si utilizza i web server Apache o Netscape (iPlanet), può essere necessario impostare il nome di una variabile di ambiente the il PHP verificherà per sapere se può continuare l'esecuzione.
Nota: L'impostazione di questa variabile può portare a problemi di sicurezza, fare attenzione a quello che si fa.
FastCGI con IIS (su OS basati su WINNT) offre la possibilità di attivare il contesto di sicurezza del client chiamante. Questo permette a IIS di definire un contesto di sicurezza in cui fare girare la richiesta. Attualmente mod_fastcgi di Apache non supporta questa caratteristica (17/03/2002). Impostare a 1 se si utilizza IIS. Il default è zero.
Indica al PHP quale tipo di intesazione utilizzare quando si invia risposte HTTP. Se impostato a 0, il PHP invia una intestazione Status:, che è supportata da Apache ed altri server web. Quando il parametro è impostato a 1, il PHP invia una intestazione conforme alle specifiche indicate in RFC 2616. Lasciare il parametro a 0 a meno che non si sappia cosa si sta facendo.
Tabella G-8. File Uploads Configuration Options
Nome | Default | Modificabile | Variazioni |
---|---|---|---|
file_uploads | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 4.2.3. Disponibile da PHP 4.0.3. |
upload_tmp_dir | NULL | PHP_INI_SYSTEM | |
upload_max_filesize | "2M" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 4.2.3. |
Breve descrizione dei parametri di configurazione.
Indica se abilitare o meno gli upload di file. Vedere anche i parametri upload_max_filesize, upload_tmp_dir e post_max_size.
When an integer is used, the value is measured in bytes. You may also use shorthand notation as described in this FAQ.
Directory temporanea utilizzata per il transito dei file durante l'upload. Deve avere i permessi di scrittura per gli utenti utilizzati dal PHP per girare. Se non indicata il PHP utilizzerà il default di sistema.
La dimensione massima di un file inviato.
When an integer is used, the value is measured in bytes. You may also use shorthand notation as described in this FAQ.
Tabella G-9. Parametri di configurazione generali per SQL
Nome | Default | Modificabile | Variazioni |
---|---|---|---|
sql.safe_mode | "0" | PHP_INI_SYSTEM |
Breve descrizione dei parametri di configurazione.
Attenzione |
Soltanto il PHP 3 possiede un debugger di default, per maggiori dettagli vedere Appendice E. |
Tabella H-1. Africa
Africa/Abidjan | Africa/Accra | Africa/Addis_Ababa | Africa/Algiers | Africa/Asmera |
Africa/Bamako | Africa/Bangui | Africa/Banjul | Africa/Bissau | Africa/Blantyre |
Africa/Brazzaville | Africa/Bujumbura | Africa/Cairo | Africa/Casablanca | Africa/Ceuta |
Africa/Conakry | Africa/Dakar | Africa/Dar_es_Salaam | Africa/Djibouti | Africa/Douala |
Africa/El_Aaiun | Africa/Freetown | Africa/Gaborone | Africa/Harare | Africa/Johannesburg |
Africa/Kampala | Africa/Khartoum | Africa/Kigali | Africa/Kinshasa | Africa/Lagos |
Africa/Libreville | Africa/Lome | Africa/Luanda | Africa/Lubumbashi | Africa/Lusaka |
Africa/Malabo | Africa/Maputo | Africa/Maseru | Africa/Mbabane | Africa/Mogadishu |
Africa/Monrovia | Africa/Nairobi | Africa/Ndjamena | Africa/Niamey | Africa/Nouakchott |
Africa/Ouagadougou | Africa/Porto-Novo | Africa/Sao_Tome | Africa/Timbuktu | Africa/Tripoli |
Africa/Tunis | Africa/Windhoek |
Tabella H-2. America
America/Adak | America/Anchorage | America/Anguilla | America/Antigua | America/Araguaina |
America/Argentina/Buenos_Aires | America/Argentina/Catamarca | America/Argentina/ComodRivadavia | America/Argentina/Cordoba | America/Argentina/Jujuy |
America/Argentina/La_Rioja | America/Argentina/Mendoza | America/Argentina/Rio_Gallegos | America/Argentina/San_Juan | America/Argentina/Tucuman |
America/Argentina/Ushuaia | America/Aruba | America/Asuncion | America/Atka | America/Bahia |
America/Barbados | America/Belem | America/Belize | America/Boa_Vista | America/Bogota |
America/Boise | America/Buenos_Aires | America/Cambridge_Bay | America/Campo_Grande | America/Cancun |
America/Caracas | America/Catamarca | America/Cayenne | America/Cayman | America/Chicago |
America/Chihuahua | America/Coral_Harbour | America/Cordoba | America/Costa_Rica | America/Cuiaba |
America/Curacao | America/Danmarkshavn | America/Dawson | America/Dawson_Creek | America/Denver |
America/Detroit | America/Dominica | America/Edmonton | America/Eirunepe | America/El_Salvador |
America/Ensenada | America/Fort_Wayne | America/Fortaleza | America/Glace_Bay | America/Godthab |
America/Goose_Bay | America/Grand_Turk | America/Grenada | America/Guadeloupe | America/Guatemala |
America/Guayaquil | America/Guyana | America/Halifax | America/Havana | America/Hermosillo |
America/Indiana/Indianapolis | America/Indiana/Knox | America/Indiana/Marengo | America/Indiana/Vevay | America/Indianapolis |
America/Inuvik | America/Iqaluit | America/Jamaica | America/Jujuy | America/Juneau |
America/Kentucky/Louisville | America/Kentucky/Monticello | America/Knox_IN | America/La_Paz | America/Lima |
America/Los_Angeles | America/Louisville | America/Maceio | America/Managua | America/Manaus |
America/Martinique | America/Mazatlan | America/Mendoza | America/Menominee | America/Merida |
America/Mexico_City | America/Miquelon | America/Monterrey | America/Montevideo | America/Montreal |
America/Montserrat | America/Nassau | America/New_York | America/Nipigon | America/Nome |
America/Noronha | America/North_Dakota/Center | America/Panama | America/Pangnirtung | America/Paramaribo |
America/Phoenix | America/Port-au-Prince | America/Port_of_Spain | America/Porto_Acre | America/Porto_Velho |
America/Puerto_Rico | America/Rainy_River | America/Rankin_Inlet | America/Recife | America/Regina |
America/Rio_Branco | America/Rosario | America/Santiago | America/Santo_Domingo | America/Sao_Paulo |
America/Scoresbysund | America/Shiprock | America/St_Johns | America/St_Kitts | America/St_Lucia |
America/St_Thomas | America/St_Vincent | America/Swift_Current | America/Tegucigalpa | America/Thule |
America/Thunder_Bay | America/Tijuana | America/Toronto | America/Tortola | America/Vancouver |
America/Virgin | America/Whitehorse | America/Winnipeg | America/Yakutat | America/Yellowknife |
Brazil/Acre | Brazil/DeNoronha | Brazil/East | Brazil/West | Canada/Atlantic |
Canada/Central | Canada/East-Saskatchewan | Canada/Eastern | Canada/Mountain | Canada/Newfoundland |
Canada/Pacific | Canada/Saskatchewan | Canada/Yukon | Chile/Continental | Chile/EasterIsland |
Mexico/BajaNorte | Mexico/BajaSur | Mexico/General | US/Alaska | US/Aleutian |
US/Arizona | US/Central | US/East-Indiana | US/Eastern | US/Hawaii |
US/Indiana-Starke | US/Michigan | US/Mountain | US/Pacific | US/Pacific-New |
US/Samoa |
Tabella H-5. Asia
Asia/Aden | Asia/Almaty | Asia/Amman | Asia/Anadyr | Asia/Aqtau |
Asia/Aqtobe | Asia/Ashgabat | Asia/Ashkhabad | Asia/Baghdad | Asia/Bahrain |
Asia/Baku | Asia/Bangkok | Asia/Beirut | Asia/Bishkek | Asia/Brunei |
Asia/Calcutta | Asia/Choibalsan | Asia/Chongqing | Asia/Chungking | Asia/Colombo |
Asia/Dacca | Asia/Damascus | Asia/Dhaka | Asia/Dili | Asia/Dubai |
Asia/Dushanbe | Asia/Gaza | Asia/Harbin | Asia/Hong_Kong | Asia/Hovd |
Asia/Irkutsk | Asia/Istanbul | Asia/Jakarta | Asia/Jayapura | Asia/Jerusalem |
Asia/Kabul | Asia/Kamchatka | Asia/Karachi | Asia/Kashgar | Asia/Katmandu |
Asia/Krasnoyarsk | Asia/Kuala_Lumpur | Asia/Kuching | Asia/Kuwait | Asia/Macao |
Asia/Macau | Asia/Magadan | Asia/Makassar | Asia/Manila | Asia/Muscat |
Asia/Nicosia | Asia/Novosibirsk | Asia/Omsk | Asia/Oral | Asia/Phnom_Penh |
Asia/Pontianak | Asia/Pyongyang | Asia/Qatar | Asia/Qyzylorda | Asia/Rangoon |
Asia/Riyadh | Asia/Saigon | Asia/Sakhalin | Asia/Samarkand | Asia/Seoul |
Asia/Shanghai | Asia/Singapore | Asia/Taipei | Asia/Tashkent | Asia/Tbilisi |
Asia/Tehran | Asia/Tel_Aviv | Asia/Thimbu | Asia/Thimphu | Asia/Tokyo |
Asia/Ujung_Pandang | Asia/Ulaanbaatar | Asia/Ulan_Bator | Asia/Urumqi | Asia/Vientiane |
Asia/Vladivostok | Asia/Yakutsk | Asia/Yekaterinburg | Asia/Yerevan | Indian/Antananarivo |
Indian/Chagos | Indian/Christmas | Indian/Cocos | Indian/Comoro | Indian/Kerguelen |
Indian/Mahe | Indian/Maldives | Indian/Mauritius | Indian/Mayotte | Indian/Reunion |
Tabella H-7. Australia
Australia/ACT | Australia/Adelaide | Australia/Brisbane | Australia/Broken_Hill | Australia/Canberra |
Australia/Currie | Australia/Darwin | Australia/Hobart | Australia/LHI | Australia/Lindeman |
Australia/Lord_Howe | Australia/Melbourne | Australia/North | Australia/NSW | Australia/Perth |
Australia/Queensland | Australia/South | Australia/Sydney | Australia/Tasmania | Australia/Victoria |
Australia/West | Australia/Yancowinna |
Tabella H-8. Europe
Europe/Amsterdam | Europe/Andorra | Europe/Athens | Europe/Belfast | Europe/Belgrade |
Europe/Berlin | Europe/Bratislava | Europe/Brussels | Europe/Bucharest | Europe/Budapest |
Europe/Chisinau | Europe/Copenhagen | Europe/Dublin | Europe/Gibraltar | Europe/Helsinki |
Europe/Istanbul | Europe/Kaliningrad | Europe/Kiev | Europe/Lisbon | Europe/Ljubljana |
Europe/London | Europe/Luxembourg | Europe/Madrid | Europe/Malta | Europe/Mariehamn |
Europe/Minsk | Europe/Monaco | Europe/Moscow | Europe/Nicosia | Europe/Oslo |
Europe/Paris | Europe/Prague | Europe/Riga | Europe/Rome | Europe/Samara |
Europe/San_Marino | Europe/Sarajevo | Europe/Simferopol | Europe/Skopje | Europe/Sofia |
Europe/Stockholm | Europe/Tallinn | Europe/Tirane | Europe/Tiraspol | Europe/Uzhgorod |
Europe/Vaduz | Europe/Vatican | Europe/Vienna | Europe/Vilnius | Europe/Warsaw |
Europe/Zagreb | Europe/Zaporozhye | Europe/Zurich |
Tabella H-9. Pacific
Pacific/Apia | Pacific/Auckland | Pacific/Chatham | Pacific/Easter | Pacific/Efate |
Pacific/Enderbury | Pacific/Fakaofo | Pacific/Fiji | Pacific/Funafuti | Pacific/Galapagos |
Pacific/Gambier | Pacific/Guadalcanal | Pacific/Guam | Pacific/Honolulu | Pacific/Johnston |
Pacific/Kiritimati | Pacific/Kosrae | Pacific/Kwajalein | Pacific/Majuro | Pacific/Marquesas |
Pacific/Midway | Pacific/Nauru | Pacific/Niue | Pacific/Norfolk | Pacific/Noumea |
Pacific/Pago_Pago | Pacific/Palau | Pacific/Pitcairn | Pacific/Ponape | Pacific/Port_Moresby |
Pacific/Rarotonga | Pacific/Saipan | Pacific/Samoa | Pacific/Tahiti | Pacific/Tarawa |
Pacific/Tongatapu | Pacific/Truk | Pacific/Wake | Pacific/Wallis | Pacific/Yap |
Tabella H-10. Others
CET | CST6CDT | Cuba | EET | Egypt |
Eire | EST | EST5EDT | Etc/GMT | Etc/GMT+0 |
Etc/GMT+1 | Etc/GMT+10 | Etc/GMT+11 | Etc/GMT+12 | Etc/GMT+2 |
Etc/GMT+3 | Etc/GMT+4 | Etc/GMT+5 | Etc/GMT+6 | Etc/GMT+7 |
Etc/GMT+8 | Etc/GMT+9 | Etc/GMT-0 | Etc/GMT-1 | Etc/GMT-10 |
Etc/GMT-11 | Etc/GMT-12 | Etc/GMT-13 | Etc/GMT-14 | Etc/GMT-2 |
Etc/GMT-3 | Etc/GMT-4 | Etc/GMT-5 | Etc/GMT-6 | Etc/GMT-7 |
Etc/GMT-8 | Etc/GMT-9 | Etc/GMT0 | Etc/Greenwich | Etc/UCT |
Etc/Universal | Etc/UTC | Etc/Zulu | Factory | GB |
GB-Eire | GMT | GMT+0 | GMT-0 | GMT0 |
Greenwich | Hongkong | HST | Iceland | Iran |
Israel | Jamaica | Japan | Kwajalein | Libya |
MET | MST | MST7MDT | Navajo | NZ |
NZ-CHAT | Poland | Portugal | PRC | PST8PDT |
ROC | ROK | Singapore | Turkey | UCT |
Universal | UTC | W-SU | WET | Zulu |
This appendix categorizes more than 150 extensions documented in the PHP Manual by several criteria.
These are not actual extensions. They are part of the PHP core and cannot be left out of a PHP binary with compilation options.
These extensions are bundled with PHP.
Riferimento VII, Funzioni Matematiche BCMath a precisione arbitraria
Riferimento XXIV, Database (dbm-style) Abstraction Layer Functions
Riferimento LXXXII, Mohawk Software Session Handler Functions
Riferimento LXXXIX, Ncurses Terminal Screen Control Functions
Riferimento CVIII, Funzioni per le espressioni regolari (Perl compatibili)
Riferimento LXXXI, Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Riferimento CXXXI, Funzioni per i semafori, la memoria condivisa ed IPC
In order to compile these extensions, external libraries will be needed.
These extensions are available from PECL. More PECL extensions exist but they are not documented in the PHP manual yet.
This part lists extensions not intended for the production use - they are either too "old" (deprecated) or "new" (experimental).
These extensions have been deprecated usually in the favor of some other extensions.
The behaviour of these extensions - including the names of their functions and anything else documented about these extensions - may change without notice in a future release of PHP. Use these extensions at your own risk.
Esistono diverse funzioni in PHP che si possono richiamare con diversi nomi. In alcuni casi non esistono nomi preferenziali, ad esempio is_int() e is_integer() sono entrambi validi. Tuttavia esistono funzioni che hanno cambiato nomi per via di una pulizia delle API o per qualche altro motivo e si è mantenuto il vecchio nome solo compatibilità con il passato. É solitamente una cattiva idea utilizzare questo tipo di sinonimi, in quanto possono esser soggetti a ridenominazione ed invecchiamento, e quindi il loro uso può indurre alla scrittura di script non portabili. Quest'elenco è fornito per aiutare coloro che vogliono trasformare i vecchi script nella nuova sintassi.
Quest'elenco è consistente con la versione 4.0.6 del PHP. Per avere la lista completa aggiornata quotidianamente, guardare http://zend.com/phpfunc/all_aliases.php.
Tabella J-1. Sinonimi
Sinonimi (alias) | Funzione Master | Estensione utilizzata |
---|---|---|
_ | gettext() | Gettext |
add | swfmovie_add() | Ming (flash) |
add | swfsprite_add() | Ming (flash) |
add_root | domxml_add_root() | DOM XML |
addaction | swfbutton_addAction() | Ming (flash) |
addcolor | swfdisplayitem_addColor() | Ming (flash) |
addentry | swfgradient_addEntry() | Ming (flash) |
addfill | swfshape_addfill() | Ming (flash) |
addshape | swfbutton_addShape() | Ming (flash) |
addstring | swftext_addString() | Ming (flash) |
addstring | swftextfield_addString() | Ming (flash) |
align | swftextfield_align() | Ming (flash) |
attributes | domxml_attributes() | DOM XML |
children | domxml_children() | DOM XML |
chop | rtrim() | Base syntax |
close | closedir() | Base syntax |
com_get | com_propget() | COM |
com_propset | com_propput() | COM |
com_set | com_propput() | COM |
cv_add | ccvs_add() | CCVS |
cv_auth | ccvs_auth() | CCVS |
cv_command | ccvs_command() | CCVS |
cv_count | ccvs_count() | CCVS |
cv_delete | ccvs_delete() | CCVS |
cv_done | ccvs_done() | CCVS |
cv_init | ccvs_init() | CCVS |
cv_lookup | ccvs_lookup() | CCVS |
cv_new | ccvs_new() | CCVS |
cv_report | ccvs_report() | CCVS |
cv_return | ccvs_return() | CCVS |
cv_reverse | ccvs_reverse() | CCVS |
cv_sale | ccvs_sale() | CCVS |
cv_status | ccvs_status() | CCVS |
cv_textvalue | ccvs_textvalue() | CCVS |
cv_void | ccvs_void() | CCVS |
die | exit() | Miscellaneous functions |
dir | getdir() | Base syntax |
diskfreespace | disk_free_space() | Filesystem |
domxml_getattr | domxml_get_attribute() | DOM XML |
domxml_setattr | domxml_set_attribute() | DOM XML |
doubleval | floatval() | Base syntax |
drawarc | swfshape_drawarc() | Ming (flash) |
drawcircle | swfshape_drawcircle() | Ming (flash) |
drawcubic | swfshape_drawcubic() | Ming (flash) |
drawcubicto | swfshape_drawcubicto() | Ming (flash) |
drawcurve | swfshape_drawcurve() | Ming (flash) |
drawcurveto | swfshape_drawcurveto() | Ming (flash) |
drawglyph | swfshape_drawglyph() | Ming (flash) |
drawline | swfshape_drawline() | Ming (flash) |
drawlineto | swfshape_drawlineto() | Ming (flash) |
dtd | domxml_intdtd() | DOM XML |
dumpmem | domxml_dumpmem() | DOM XML |
fbsql | fbsql_db_query() | FrontBase |
fputs | fwrite() | Base syntax |
get_attribute | domxml_get_attribute() | DOM XML |
getascent | swffont_getAscent() | Ming (flash) |
getascent | swftext_getAscent() | Ming (flash) |
getattr | domxml_get_attribute() | DOM XML |
getdescent | swffont_getDescent() | Ming (flash) |
getdescent | swftext_getDescent() | Ming (flash) |
getheight | swfbitmap_getHeight() | Ming (flash) |
getleading | swffont_getLeading() | Ming (flash) |
getleading | swftext_getLeading() | Ming (flash) |
getshape1 | swfmorph_getShape1() | Ming (flash) |
getshape2 | swfmorph_getShape2() | Ming (flash) |
getwidth | swfbitmap_getWidth() | Ming (flash) |
getwidth | swffont_getWidth() | Ming (flash) |
getwidth | swftext_getWidth() | Ming (flash) |
gzputs | gzwrite() | Zlib |
i18n_convert | mb_convert_encoding() | Multi-bytes Strings |
i18n_discover_encoding | mb_detect_encoding() | Multi-bytes Strings |
i18n_http_input | mb_http_input() | Multi-bytes Strings |
i18n_http_output | mb_http_output() | Multi-bytes Strings |
i18n_internal_encoding | mb_internal_encoding() | Multi-bytes Strings |
i18n_ja_jp_hantozen | mb_convert_kana() | Multi-bytes Strings |
i18n_mime_header_decode | mb_decode_mimeheader() | Multi-bytes Strings |
i18n_mime_header_encode | mb_encode_mimeheader() | Multi-bytes Strings |
imap_create | imap_createmailbox() | IMAP |
imap_fetchtext | imap_body() | IMAP |
imap_getmailboxes | imap_list_full() | IMAP |
imap_getsubscribed | imap_lsub_full() | IMAP |
imap_header | imap_headerinfo() | IMAP |
imap_listmailbox | imap_list() | IMAP |
imap_listsubscribed | imap_lsub() | IMAP |
imap_rename | imap_renamemailbox() | IMAP |
imap_scan | imap_listscan() | IMAP |
imap_scanmailbox | imap_listscan() | IMAP |
ini_alter | ini_set() | Base syntax |
is_double | is_float() | Base syntax |
is_integer | is_int() | Base syntax |
is_long | is_int() | Base syntax |
is_real | is_float() | Base syntax |
is_writeable | is_writable() | Base syntax |
join | implode() | Base syntax |
labelframe | swfmovie_labelFrame() | Ming (flash) |
labelframe | swfsprite_labelFrame() | Ming (flash) |
last_child | domxml_last_child() | DOM XML |
lastchild | domxml_last_child() | DOM XML |
ldap_close | ldap_unbind() | LDAP |
magic_quotes_runtime | set_magic_quotes_runtime() | Base syntax |
mbstrcut | mb_strcut() | Multi-bytes Strings |
mbstrlen | mb_strlen() | Multi-bytes Strings |
mbstrpos | mb_strpos() | Multi-bytes Strings |
mbstrrpos | mb_strrpos() | Multi-bytes Strings |
mbsubstr | mb_substr() | Multi-bytes Strings |
ming_setcubicthreshold | ming_setCubicThreshold() | Ming (flash) |
ming_setscale | ming_setScale() | Ming (flash) |
move | swfdisplayitem_move() | Ming (flash) |
movepen | swfshape_movepen() | Ming (flash) |
movepento | swfshape_movepento() | Ming (flash) |
moveto | swfdisplayitem_moveTo() | Ming (flash) |
moveto | swffill_moveTo() | Ming (flash) |
moveto | swftext_moveTo() | Ming (flash) |
msql | msql_db_query() | mSQL |
msql_createdb | msql_create_db() | mSQL |
msql_dbname | msql_result() | mSQL |
msql_dropdb | msql_drop_db() | mSQL |
msql_fieldflags | msql_field_flags() | mSQL |
msql_fieldlen | msql_field_len() | mSQL |
msql_fieldname | msql_field_name() | mSQL |
msql_fieldtable | msql_field_table() | mSQL |
msql_fieldtype | msql_field_type() | mSQL |
msql_freeresult | msql_free_result() | mSQL |
msql_listdbs | msql_list_dbs() | mSQL |
msql_listfields | msql_list_fields() | mSQL |
msql_listtables | msql_list_tables() | mSQL |
msql_numfields | msql_num_fields() | mSQL |
msql_numrows | msql_num_rows() | mSQL |
msql_regcase | sql_regcase() | mSQL |
msql_selectdb | msql_select_db() | mSQL |
msql_tablename | msql_result() | mSQL |
mssql_affected_rows | sybase_affected_rows() | Sybase |
mssql_affected_rows | sybase_affected_rows() | Sybase |
mssql_close | sybase_close() | Sybase |
mssql_close | sybase_close() | Sybase |
mssql_connect | sybase_connect() | Sybase |
mssql_connect | sybase_connect() | Sybase |
mssql_data_seek | sybase_data_seek() | Sybase |
mssql_data_seek | sybase_data_seek() | Sybase |
mssql_fetch_array | sybase_fetch_array() | Sybase |
mssql_fetch_array | sybase_fetch_array() | Sybase |
mssql_fetch_field | sybase_fetch_field() | Sybase |
mssql_fetch_field | sybase_fetch_field() | Sybase |
mssql_fetch_object | sybase_fetch_object() | Sybase |
mssql_fetch_object | sybase_fetch_object() | Sybase |
mssql_fetch_row | sybase_fetch_row() | Sybase |
mssql_fetch_row | sybase_fetch_row() | Sybase |
mssql_field_seek | sybase_field_seek() | Sybase |
mssql_field_seek | sybase_field_seek() | Sybase |
mssql_free_result | sybase_free_result() | Sybase |
mssql_free_result | sybase_free_result() | Sybase |
mssql_get_last_message | sybase_get_last_message() | Sybase |
mssql_get_last_message | sybase_get_last_message() | Sybase |
mssql_min_client_severity | sybase_min_client_severity() | Sybase |
mssql_min_error_severity | sybase_min_error_severity() | Sybase |
mssql_min_message_severity | sybase_min_message_severity() | Sybase |
mssql_min_server_severity | sybase_min_server_severity() | Sybase |
mssql_num_fields | sybase_num_fields() | Sybase |
mssql_num_fields | sybase_num_fields() | Sybase |
mssql_num_rows | sybase_num_rows() | Sybase |
mssql_num_rows | sybase_num_rows() | Sybase |
mssql_pconnect | sybase_pconnect() | Sybase |
mssql_pconnect | sybase_pconnect() | Sybase |
mssql_query | sybase_query() | Sybase |
mssql_query | sybase_query() | Sybase |
mssql_result | sybase_result() | Sybase |
mssql_result | sybase_result() | Sybase |
mssql_select_db | sybase_select_db() | Sybase |
mssql_select_db | sybase_select_db() | Sybase |
multcolor | swfdisplayitem_multColor() | Ming (flash) |
mysql | mysql_db_query() | MySQL |
mysql_createdb | mysql_create_db() | MySQL |
mysql_db_name | mysql_result() | MySQL |
mysql_dbname | mysql_result() | MySQL |
mysql_dropdb | mysql_drop_db() | MySQL |
mysql_fieldflags | mysql_field_flags() | MySQL |
mysql_fieldlen | mysql_field_len() | MySQL |
mysql_fieldname | mysql_field_name() | MySQL |
mysql_fieldtable | mysql_field_table() | MySQL |
mysql_fieldtype | mysql_field_type() | MySQL |
mysql_freeresult | mysql_free_result() | MySQL |
mysql_listdbs | mysql_list_dbs() | MySQL |
mysql_listfields | mysql_list_fields() | MySQL |
mysql_listtables | mysql_list_tables() | MySQL |
mysql_numfields | mysql_num_fields() | MySQL |
mysql_numrows | mysql_num_rows() | MySQL |
mysql_selectdb | mysql_select_db() | MySQL |
mysql_tablename | mysql_result() | MySQL |
name | domxml_attrname() | DOM XML |
new_child | domxml_new_child() | DOM XML |
new_xmldoc | domxml_new_xmldoc() | DOM XML |
nextframe | swfmovie_nextFrame() | Ming (flash) |
nextframe | swfsprite_nextFrame() | Ming (flash) |
node | domxml_node() | DOM XML |
oci8append | ocicollappend() | OCI8 |
oci8assign | ocicollassign() | OCI8 |
oci8assignelem | ocicollassignelem() | OCI8 |
oci8close | ocicloselob() | OCI8 |
oci8free | ocifreecoll() | OCI8 |
oci8free | ocifreedesc() | OCI8 |
oci8getelem | ocicollgetelem() | OCI8 |
oci8load | ociloadlob() | OCI8 |
oci8max | ocicollmax() | OCI8 |
oci8ocifreecursor | ocifreestatement() | OCI8 |
oci8save | ocisavelob() | OCI8 |
oci8savefile | ocisavelobfile() | OCI8 |
oci8size | ocicollsize() | OCI8 |
oci8trim | ocicolltrim() | OCI8 |
oci8writetemporary | ociwritetemporarylob() | OCI8 |
oci8writetofile | ociwritelobtofile() | OCI8 |
odbc_do | odbc_exec() | OCI8 |
odbc_field_precision | odbc_field_len() | OCI8 |
output | swfmovie_output() | Ming (flash) |
parent | domxml_parent() | DOM XML |
pdf_add_outline | pdf_add_bookmark() | |
pg_clientencoding | pg_client_encoding() | PostgreSQL |
pg_setclientencoding | pg_set_client_encoding() | PostgreSQL |
pos | current() | Base syntax |
recode | recode_string() | Recode |
remove | swfmovie_remove() | Ming (flash) |
remove | swfsprite_remove() | Ming (flash) |
rewind | rewinddir() | Base syntax |
root | domxml_root() | DOM XML |
rotate | swfdisplayitem_rotate() | Ming (flash) |
rotateto | swfdisplayitem_rotateTo() | Ming (flash) |
rotateto | swffill_rotateTo() | Ming (flash) |
save | swfmovie_save() | Ming (flash) |
savetofile | swfmovie_saveToFile() | Ming (flash) |
scale | swfdisplayitem_scale() | Ming (flash) |
scaleto | swfdisplayitem_scaleTo() | Ming (flash) |
scaleto | swffill_scaleTo() | Ming (flash) |
set_attribute | domxml_set_attribute() | DOM XML |
set_content | domxml_set_content() | DOM XML |
setaction | swfbutton_setAction() | Ming (flash) |
setattr | domxml_set_attribute() | DOM XML |
setbackground | swfmovie_setBackground() | Ming (flash) |
setbounds | swftextfield_setBounds() | Ming (flash) |
setcolor | swftext_setColor() | Ming (flash) |
setcolor | swftextfield_setColor() | Ming (flash) |
setdepth | swfdisplayitem_setDepth() | Ming (flash) |
setdimension | swfmovie_setDimension() | Ming (flash) |
setdown | swfbutton_setDown() | Ming (flash) |
setfont | swftext_setFont() | Ming (flash) |
setfont | swftextfield_setFont() | Ming (flash) |
setframes | swfmovie_setFrames() | Ming (flash) |
setframes | swfsprite_setFrames() | Ming (flash) |
setheight | swftext_setHeight() | Ming (flash) |
setheight | swftextfield_setHeight() | Ming (flash) |
sethit | swfbutton_setHit() | Ming (flash) |
setindentation | swftextfield_setIndentation() | Ming (flash) |
setleftfill | swfshape_setleftfill() | Ming (flash) |
setleftmargin | swftextfield_setLeftMargin() | Ming (flash) |
setline | swfshape_setline() | Ming (flash) |
setlinespacing | swftextfield_setLineSpacing() | Ming (flash) |
setmargins | swftextfield_setMargins() | Ming (flash) |
setmatrix | swfdisplayitem_setMatrix() | Ming (flash) |
setname | swfdisplayitem_setName() | Ming (flash) |
setname | swftextfield_setName() | Ming (flash) |
setover | swfbutton_setOver() | Ming (flash) |
setrate | swfmovie_setRate() | Ming (flash) |
setratio | swfdisplayitem_setRatio() | Ming (flash) |
setrightfill | swfshape_setrightfill() | Ming (flash) |
setrightmargin | swftextfield_setRightMargin() | Ming (flash) |
setspacing | swftext_setSpacing() | Ming (flash) |
setup | swfbutton_setUp() | Ming (flash) |
show_source | highlight_file() | Base syntax |
sizeof | count() | Base syntax |
skewx | swfdisplayitem_skewX() | Ming (flash) |
skewxto | swfdisplayitem_skewXTo() | Ming (flash) |
skewxto | swffill_skewXTo() | Ming (flash) |
skewy | swfdisplayitem_skewY() | Ming (flash) |
skewyto | swfdisplayitem_skewYTo() | Ming (flash) |
skewyto | swffill_skewYTo() | Ming (flash) |
snmpwalkoid | snmprealwalk() | SNMP |
strchr | strstr() | Base syntax |
streammp3 | swfmovie_streamMp3() | Ming (flash) |
swfaction | swfaction_init() | Ming (flash) |
swfbitmap | swfbitmap_init() | Ming (flash) |
swfbutton | swfbutton_init() | Ming (flash) |
swffill | swffill_init() | Ming (flash) |
swffont | swffont_init() | Ming (flash) |
swfgradient | swfgradient_init() | Ming (flash) |
swfmorph | swfmorph_init() | Ming (flash) |
swfmovie | swfmovie_init() | Ming (flash) |
swfshape | swfshape_init() | Ming (flash) |
swfsprite | swfsprite_init() | Ming (flash) |
swftext | swftext_init() | Ming (flash) |
swftextfield | swftextfield_init() | Ming (flash) |
unlink | domxml_unlink_node() | DOM XML |
xptr_new_context | xpath_new_context() | DOM XML |
Questa è la lista delle parole riservate nel PHP. Nessuno di questi identificatori deve essere utilizzato negli script. Questa lista include parole chiave e variabili predefinite, costanti e nomi di classi. Questa lista non è né esaustiva né completa.
Queste parole hanno significato speciale per il PHP. Alcune di esse rappresentano cose che assomigliano a funzioni, altri a costanti, e così via. Ma non lo sono, in verità : sono costrutti del linguaggi. non si deve utilizzare nessuna di queste parole come costante, nome di classe, funzione o nome di metodo. L'utilizzo come nomi di variabili normalmente funziona, ma questo può generare confusione.
Tabella K-1. Parole chiave
and | or | xor | __FILE__ | exception (PHP 5) |
__LINE__ | array() | as | break | case |
class | const | continue | declare | default |
die() | do | echo() | else | elseif |
empty() | enddeclare | endfor | endforeach | endif |
endswitch | endwhile | eval() | exit() | extends |
for | foreach | function | global | if |
include() | include_once() | isset() | list() | new |
print() | require() | require_once() | return() | static |
switch | unset() | use | var | while |
__FUNCTION__ | __CLASS__ | __METHOD__ | final (PHP 5) | php_user_filter (PHP 5) |
interface (PHP 5) | implements (PHP 5) | extends | public (PHP 5) | private (PHP 5) |
protected (PHP 5) | abstract (PHP 5) | clone (PHP 5) | try (PHP 5) | catch (PHP 5) |
throw (PHP 5) | cfunction (PHP 4 only) | old_function (PHP 4 only) |
A partire dal PHP 4.1.0, il metodo raccomandato per ottenere le variabili esterne è quello di usare i superglobals, come spiegato più sotto. In precedenza, gli sviluppatori si appoggiavano ai register_globals o agli array predefiniti ($HTTP_*_VARS). As of PHP 5.0.0, the long PHP predefined variable arrays may be disabled with the register_long_arrays directive.
Nota: Introdotta dal PHP 4.1.0. Nelle versioni precedenti, utilizzare $HTTP_SERVER_VARS.
$_SERVER è un array che contiene informazioni quali header, percorsi e posizioni degli script. Le voci in questo array sono create dal server web. non c'è garanzia che ogni server web fornisca queste informazioni; i server possono ometterne alcune, oppure fornirne altre non contemplate qui. Detto questo, gran parte di queste variabili sono contemplate nelle specifiche CGI 1.1, quindi è molto probabile ritrovarle in questo array.
Questo array è una variabile 'superglobal', o globale automatica. Ciò siginifica che è disponibile in tutti gli scope all'interno di uno script. Non è necessario scrivere global $_SERVER; per accedervi in una funzione o metodo, come invece occorreva fare con $HTTP_SERVER_VARS.
$HTTP_SERVER_VARS contiene le stesse informazioni, ma non è autoglobal. (si noti che $HTTP_SERVER_VARS e $_SERVER sono variabili distinte e che PHP le tratta di conseguenza)
Se la direttiva register_globals è impostata, queste informazioni saranno rese disponibili anche nello scope globale dello script; quindi in variabili diverse da $_SERVER e $HTTP_SERVER_VARS arrays. Per la documentazione correlata, vedere il capitolo sulla sicurezza intitolato Utilizzo dei Register Globals. Queste variabili globali individuali non sono autoglobal.
You may or may not find any of the following elements in $_SERVER. Note that few, if any, of these will be available (or indeed have any meaning) if running PHP on the command line.
The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar would be /test.php/foo.bar. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.
If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available.
Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string.
Contains the number of command line parameters passed to the script (if run on the command line).
What revision of the CGI specification the server is using; i.e. 'CGI/1.1'.
The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.
Server identification string, given in the headers when responding to requests.
Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0';
Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.
The timestamp of the start of the request. Available since PHP 5.1.0.
The query string, if any, via which the page was accessed.
The document root directory under which the current script is executing, as defined in the server's configuration file.
Contents of the Accept: header from the current request, if there is one.
Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso-8859-1,*,utf-8'.
Contents of the Accept-Encoding: header from the current request, if there is one. Example: 'gzip'.
Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'.
Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'.
Contents of the Host: header from the current request, if there is one.
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with get_browser() to tailor your page's output to the capabilities of the user agent.
The IP address from which the user is viewing the current page.
The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user.
Nota: Your web server must be configured to create this variable. For example in Apache you'll need HostnameLookups On inside httpd.conf for it to exist. See also gethostbyaddr().
The port being used on the user's machine to communicate with the web server.
The absolute pathname of the currently executing script.
Nota: If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user.
The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host.
The port on the server machine being used by the web server for communication. For default setups, this will be '80'; using SSL, for instance, will change this to whatever your defined secure HTTP port is.
String containing the server version and virtual host name which are added to server-generated pages, if enabled.
Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.
Nota: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it's set to the same value as the SCRIPT_FILENAME server variable when it's not populated by Apache. This change was made to comply with the CGI specification that PATH_TRANSLATED should only exist if PATH_INFO is defined.
Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO.
Contains the current script's path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.
The URI which was given in order to access this page; for instance, '/index.html'.
When running under Apache as module doing HTTP authentication this variable is set to the username provided by the user.
When running under Apache as module doing HTTP authentication this variable is set to the password provided by the user.
When running under Apache as module doing HTTP authenticated this variable is set to the authentication type.
Nota: Introduced in 4.1.0. In earlier versions, use $HTTP_ENV_VARS.
These variables are imported into PHP's global namespace from the environment under which the PHP parser is running. Many are provided by the shell under which PHP is running and different systems are likely running different kinds of shells, a definitive list is impossible. Please see your shell's documentation for a list of defined environment variables.
Other environment variables include the CGI variables, placed there regardless of whether PHP is running as a server module or CGI processor.
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_ENV; to access it within functions or methods, as you do with $HTTP_ENV_VARS.
$HTTP_ENV_VARS contains the same initial information, but is not an autoglobal. (Note that $HTTP_ENV_VARS and $_ENV are different variables and that PHP handles them as such)
If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_ENV and $HTTP_ENV_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.
Nota: Introduced in 4.1.0. In earlier versions, use $HTTP_COOKIE_VARS.
An associative array of variables passed to the current script via HTTP cookies. Automatically global in any scope.
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_COOKIE; to access it within functions or methods, as you do with $HTTP_COOKIE_VARS.
$HTTP_COOKIE_VARS contains the same initial information, but is not an autoglobal. (Note that $HTTP_COOKIE_VARS and $_COOKIE are different variables and that PHP handles them as such)
If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_COOKIE and $HTTP_COOKIE_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.
Nota: Introduced in 4.1.0. In earlier versions, use $HTTP_GET_VARS.
An associative array of variables passed to the current script via the HTTP GET method. Automatically global in any scope.
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_GET; to access it within functions or methods, as you do with $HTTP_GET_VARS.
$HTTP_GET_VARS contains the same initial information, but is not an autoglobal. (Note that $HTTP_GET_VARS and $_GET are different variables and that PHP handles them as such)
If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_GET and $HTTP_GET_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.
Nota: Introduced in 4.1.0. In earlier versions, use $HTTP_POST_VARS.
An associative array of variables passed to the current script via the HTTP POST method. Automatically global in any scope.
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_POST; to access it within functions or methods, as you do with $HTTP_POST_VARS.
$HTTP_POST_VARS contains the same initial information, but is not an autoglobal. (Note that $HTTP_POST_VARS and $_POST are different variables and that PHP handles them as such)
If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_POST and $HTTP_POST_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.
Nota: Introduced in 4.1.0. In earlier versions, use $HTTP_POST_FILES.
An associative array of items uploaded to the current script via the HTTP POST method. Automatically global in any scope.
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_FILES; to access it within functions or methods, as you do with $HTTP_POST_FILES.
$HTTP_POST_FILES contains the same information, but is not an autoglobal. (Note that $HTTP_POST_FILES and $_FILES are different variables and that PHP handles them as such)
If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_FILES and $HTTP_POST_FILES arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.
Nota: Introduced in 4.1.0. There is no equivalent array in earlier versions.
Nota: Prior to PHP 4.3.0, $_FILES information was also included in $_REQUEST.
An associative array consisting of the contents of $_GET, $_POST, and $_COOKIE.
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_REQUEST; to access it within functions or methods.
If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_REQUEST array. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.
Nota: Introduced in 4.1.0. In earlier versions, use $HTTP_SESSION_VARS.
An associative array containing session variables available to the current script. See the Session functions documentation for more information on how this is used.
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $_SESSION; to access it within functions or methods, as you do with $HTTP_SESSION_VARS.
$HTTP_SESSION_VARS contains the same information, but is not an autoglobal. (Note that $HTTP_SESSION_VARS and $_SESSION are different variables and that PHP handles them as such)
If the register_globals directive is set, then these variables will also be made available in the global scope of the script; i.e., separate from the $_SESSION and $HTTP_SESSION_VARS arrays. For related information, see the security chapter titled Using Register Globals. These individual globals are not autoglobals.
Nota: $GLOBALS has been available since PHP 3.0.0.
An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $GLOBALS; to access it within functions or methods.
$php_errormsg is a variable containing the text of the last error message generated by PHP. This variable will only be available within the scope in which the error occurred, and only if the track_errors configuration option is turned on (it defaults to off).
These classes are defined in the standard set of functions included in the PHP build.
The class from which dir is instantiated.
These additional predefined classes were introduced in PHP 5.0.0
These classes are defined in the Ming extension, and will only be available when that extension has either been compiled into PHP or dynamically loaded at runtime.
These constants are defined by the PHP core. This includes PHP, the Zend engine, and SAPI modules.
Available since PHP 4.3.10 and PHP 5.0.2
Available since PHP 4.4.0 and PHP 5.0.5
Available since PHP 4.4.0 and PHP 5.0.5
Available since PHP 5.0.0
Available since PHP 5.1.0
See also: Magic constants.
These constants are defined in PHP by default.
The following is a list of functions which create, use or destroy PHP resources. The function is_resource() can be used to determine if a variable is a resource and get_resource_type() will return the type of resource it is.
Tabella L-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_copy_handle(), curl_init() | curl_copy_handle(), curl_errno(), curl_error(), curl_exec(), curl_getinfo(), curl_setopt() | curl_close() | Curl session |
dbm | dbmopen() | dbmexists(), dbmfetch(), dbminsert(), dbmreplace(), dbmdelete(), dbmfirstkey(), dbmnextkey() | dbmclose() | Link to DBM database |
dba | dba_open() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | dba_close() | Link to DBA database |
dba persistent | dba_popen() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | None | Persistent link to DBA database |
dbase | dbase_open() | dbase_pack(), dbase_add_record(), dbase_replace_record(), dbase_delete_record(), dbase_get_record(), dbase_get_record_with_names(), dbase_numfields(), dbase_numrecords() | dbase_close() | Link to Dbase database |
dbx_link_object | dbx_connect() | dbx_query() | dbx_close() | dbx connection |
dbx_result_object | dbx_query() | None | dbx result | |
domxml attribute | ||||
domxml document | ||||
domxml node | ||||
xpath context | ||||
xpath object | ||||
fbsql link | fbsql_change_user(), fbsql_connect() | fbsql_autocommit(), fbsql_blob_size(), fbsql_clob_size(), fbsql_commit(), fbsql_change_user(), fbsql_create_blob(), fbsql_create_db(), fbsql_create_clob(), fbsql_data_seek(), fbsql_database_password(), fbsql_database(), fbsql_db_query(), fbsql_db_status(), fbsql_drop_db(), fbsql_errno(), fbsql_error(), fbsql_get_autostart_info(), fbsql_hostname(), fbsql_insert_id(), fbsql_list_dbs(), fbsql_password(), fbsql_read_blob(), fbsql_read_clob(), fbsql_rollback(), fbsql_select_db(), fbsql_set_password(), fbsql_set_transaction(), fbsql_start_db(), fbsql_stop_db(), fbsql_username() | fbsql_close() | Link to fbsql database |
fbsql plink | fbsql_change_user(), fbsql_pconnect() | fbsql_autocommit(), fbsql_change_user(), fbsql_create_db(), fbsql_data_seek(), fbsql_db_query(), fbsql_drop_db(), fbsql_select_db(), fbsql_errno(), fbsql_error(), fbsql_insert_id(), fbsql_list_dbs() | None | Persistent link to fbsql database |
fbsql result | fbsql_db_query(), fbsql_list_dbs(), fbsql_query(), fbsql_list_fields(), fbsql_list_tables(), fbsql_tablename() | fbsql_affected_rows(), fbsql_fetch_array(), fbsql_fetch_assoc(), fbsql_fetch_field(), fbsql_fetch_lengths(), fbsql_fetch_object(), fbsql_fetch_row(), fbsql_field_flags(), fbsql_field_name(), fbsql_field_len(), fbsql_field_seek(), fbsql_field_table(), fbsql_field_type(), fbsql_next_result(), fbsql_num_fields(), fbsql_num_rows(), fbsql_result(), fbsql_num_rows() | fbsql_free_result() | fbsql result |
fdf | fdf_open() | fdf_create(), fdf_save(), fdf_get_value(), fdf_set_value(), fdf_next_field_name(), fdf_set_ap(), fdf_set_status(), fdf_get_status(), fdf_set_file(), fdf_get_file(), fdf_set_flags(), fdf_set_opt(), fdf_set_submit_form_action(), fdf_set_javascript_action() | fdf_close() | FDF File |
ftp | ftp_connect(), ftp_ssl_connect() | ftp_login(), ftp_pwd(), ftp_cdup(), ftp_chdir(), ftp_mkdir(), ftp_rmdir(), ftp_nlist(), ftp_rawlist(), ftp_systype(), ftp_pasv(), ftp_get(), ftp_fget(), ftp_put(), ftp_fput(), ftp_size(), ftp_mdtm(), ftp_rename(), ftp_delete(), ftp_site(), ftp_alloc(), ftp_chmod(), ftp_exec(), ftp_get_option(), ftp_nb_continue(), ftp_nb_fget(), ftp_nb_fput(), ftp_nb_get(), ftp_nb_put(), ftp_raw(), ftp_set_option() | ftp_close() | FTP stream |
gd | imagecreate(), imagecreatefromgd(), imagecreatefromgd2(), imagecreatefromgd2part(), imagecreatefromgif(), imagecreatefromjpeg(), imagecreatefrompng(), imagecreatefromwbmp(), imagecreatefromstring(), imagecreatefromxbm(), imagecreatefromxpm(), imagecreatetruecolor(), imagerotate() | imagearc(), imagechar(), imagecharup(), imagecolorallocate(), imagecolorat(), imagecolorclosest(), imagecolorexact(), imagecolorresolve(), imagegammacorrect(), imagegammacorrect(), imagecolorset(), imagecolorsforindex(), imagecolorstotal(), imagecolortransparent(), imagecopy(), imagecopyresized(), imagedashedline(), imagefill(), imagefilledpolygon(), imagefilledrectangle(), imagefilltoborder(), imagegif(), imagepng(), imagejpeg(), imagewbmp(), imageinterlace(), imageline(), imagepolygon(), imagepstext(), imagerectangle(), imagerotate(), imagesetpixel(), imagestring(), imagestringup(), imagesx(), imagesy(), imagettftext(), imagefilledarc(), imageellipse(), imagefilledellipse(), imagecolorclosestalpha(), imagecolorexactalpha(), imagecolorresolvealpha(), imagecopymerge(), imagecopymergegray(), imagecopyresampled(), imagetruecolortopalette(), imagesetbrush(), imagesettile(), imagesetthickness(), image2wbmp(), imagealphablending(), imageantialias(), imagecolorallocatealpha(), imagecolorclosesthwb(), imagecolordeallocate(), imagecolormatch(), imagefilter(), imagefttext(), imagegd(), imagegd2(), imageistruecolor(), imagelayereffect(), imagepalettecopy(), imagesavealpha(), imagesetstyle(), imagexbm() | imagedestroy() | GD Image |
gd font | imageloadfont() | imagechar(), imagecharup(), imagefontheight() | None | Font for GD |
gd PS encoding | ||||
gd PS font | imagepsloadfont() | imagepstext(), imagepsslantfont(), imagepsextendfont(), imagepsencodefont(), imagepsbbox() | imagepsfreefont() | PS font for GD |
GMP integer | gmp_init() | gmp_intval(), gmp_strval(), gmp_add(), gmp_sub(), gmp_mul(), gmp_div_q(), gmp_div_r(), gmp_div_qr(), gmp_div(), gmp_mod(), gmp_divexact(), gmp_cmp(), gmp_neg(), gmp_abs(), gmp_sign(), gmp_fact(), gmp_sqrt(), gmp_sqrtrm(), gmp_perfect_square(), gmp_pow(), gmp_powm(), gmp_prob_prime(), gmp_gcd(), gmp_gcdext(), gmp_invert(), gmp_legendre(), gmp_jacobi(), gmp_random(), gmp_and(), gmp_or(), gmp_xor(), gmp_setbit(), gmp_clrbit(), gmp_scan0(), gmp_scan1(), gmp_popcount(), gmp_hamdist() | None | GMP Number |
hyperwave document | hw_cp(), hw_docbyanchor(), hw_getremote(), hw_getremotechildren() | hw_children(), hw_childrenobj(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getsrcbydestobj(), hw_getandlock(), hw_gettext(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_inscoll(), hw_pipedocument(), hw_unlock() | hw_deleteobject() | Hyperwave object |
hyperwave link | hw_connect() | hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() | hw_close(), hw_free_document() | Link to Hyperwave server |
hyperwave link persistent | hw_pconnect() | hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() | None | Persistent link to Hyperwave server |
icap | icap_open() | icap_fetch_event(), icap_list_events(), icap_store_event(), icap_snooze(), icap_list_alarms(), icap_delete_event() | icap_close() | Link to icap server |
imap | imap_open() | imap_append(), imap_body(), imap_check(), imap_createmailbox(), imap_delete(), imap_deletemailbox(), imap_expunge(), imap_fetchbody(), imap_fetchstructure(), imap_headerinfo(), imap_header(), imap_headers(), imap_listmailbox(), imap_getmailboxes(), imap_get_quota(), imap_status(), imap_listsubscribed(), imap_set_quota(), imap_set_quota(), imap_getsubscribed(), imap_mail_copy(), imap_mail_move(), imap_num_msg(), imap_num_recent(), imap_ping(), imap_renamemailbox(), imap_reopen(), imap_subscribe(), imap_undelete(), imap_unsubscribe(), imap_scanmailbox(), imap_mailboxmsginfo(), imap_fetchheader(), imap_uid(), imap_msgno(), imap_search(), imap_fetch_overview() | imap_close() | Link to IMAP, POP3 server |
imap chain persistent | ||||
imap persistent | ||||
ingres | ingres_connect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | ingres_close() | Link to ingresII base |
ingres persistent | ingres_pconnect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | None | Persistent link to ingresII base |
interbase blob | ||||
interbase link | ibase_connect() | ibase_query(), ibase_prepare(), ibase_trans() | ibase_close() | Link to Interbase database |
interbase link persistent | ibase_pconnect() | ibase_query(), ibase_prepare(), ibase_trans() | None | Persistent link to Interbase database |
interbase query | ibase_prepare() | ibase_execute() | ibase_free_query() | Interbase query |
interbase result | ibase_query() | ibase_fetch_row(), ibase_fetch_object(), ibase_field_info(), ibase_num_fields() | ibase_free_result() | Interbase Result |
interbase transaction | ibase_trans() | ibase_commit() | ibase_rollback() | Interbase transaction |
java | ||||
ldap link | ldap_connect(), ldap_search() | ldap_count_entries(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_next_attribute(), ldap_next_entry() | ldap_close() | ldap connection |
ldap result | ldap_read() | ldap_add(), ldap_compare(), ldap_bind(), ldap_count_entries(), ldap_delete(), ldap_errno(), ldap_error(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_get_option(), ldap_list(), ldap_modify(), ldap_mod_add(), ldap_mod_replace(), ldap_next_attribute(), ldap_next_entry(), ldap_mod_del(), ldap_set_option(), ldap_unbind() | ldap_free_result() | ldap search result |
ldap result entry | ||||
mcal | mcal_open(), mcal_popen() | mcal_create_calendar(), mcal_rename_calendar(), mcal_rename_calendar(), mcal_delete_calendar(), mcal_fetch_event(), mcal_list_events(), mcal_append_event(), mcal_store_event(), mcal_delete_event(), mcal_list_alarms(), mcal_event_init(), mcal_event_set_category(), mcal_event_set_title(), mcal_event_set_description(), mcal_event_set_start(), mcal_event_set_end(), mcal_event_set_alarm(), mcal_event_set_class(), mcal_next_recurrence(), mcal_event_set_recur_none(), mcal_event_set_recur_daily(), mcal_event_set_recur_weekly(), mcal_event_set_recur_monthly_mday(), mcal_event_set_recur_monthly_wday(), mcal_event_set_recur_yearly(), mcal_fetch_current_stream_event(), mcal_event_add_attribute(), mcal_expunge() | mcal_close() | Link to calendar server |
SWFAction | ||||
SWFBitmap | ||||
SWFButton | ||||
SWFDisplayItem | ||||
SWFFill | ||||
SWFFont | ||||
SWFGradient | ||||
SWFMorph | ||||
SWFMovie | ||||
SWFShape | ||||
SWFSprite | ||||
SWFText | ||||
SWFTextField | ||||
mnogosearch agent | ||||
mnogosearch result | ||||
msql link | msql_connect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | msql_close() | Link to mSQL database |
msql link persistent | msql_pconnect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | None | Persistent link to mSQL |
msql query | msql_db_query(), msql_list_dbs(), msql_list_fields(), msql_list_tables(), msql_query() | msql(), msql_affected_rows(), msql_data_seek(), msql_dbname(), msql_fetch_array(), msql_fetch_field(), msql_fetch_object(), msql_fetch_row(), msql_field_seek(), msql_field_table(), msql_field_flags(), msql_field_len(), msql_field_name(), msql_field_type(), msql_num_fields(), msql_num_rows(), msql_numfields(), msql_numrows(), msql_result() | msql_free_result(), msql_free_result() | mSQL result |
mssql link | mssql_connect() | mssql_query(), mssql_select_db() | mssql_close() | Link to Microsoft SQL Server database |
mssql link persistent | mssql_pconnect() | mssql_query(), mssql_select_db() | None | Persistent link to Microsoft SQL Server |
mssql result | mssql_query() | mssql_data_seek(), mssql_fetch_array(), mssql_fetch_field(), mssql_fetch_object(), mssql_fetch_row(), mssql_field_length(), mssql_field_name(), mssql_field_seek(), mssql_field_type(), mssql_num_fields(), mssql_num_rows(), mssql_result() | mssql_free_result() | Microsoft SQL Server result |
mysql link | mysql_connect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | mysql_close() | Link to MySQL database |
mysql link persistent | mysql_pconnect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | None | Persistent link to MySQL database |
mysql result | mysql_db_query(), mysql_list_dbs(), mysql_list_fields(), mysql_list_processes(), mysql_list_tables(), mysql_query(), mysql_unbuffered_query() | mysql_data_seek(), mysql_db_name(), mysql_fetch_array(), mysql_fetch_assoc(), mysql_fetch_field(), mysql_fetch_lengths(), mysql_fetch_object(), mysql_fetch_row(), mysql_fetch_row(), mysql_field_flags(), mysql_field_name(), mysql_field_len(), mysql_field_seek(), mysql_field_table(), mysql_field_type(), mysql_num_fields(), mysql_num_rows(), mysql_result(), mysql_tablename() | mysql_free_result() | MySQL result |
oci8 collection | ||||
oci8 connection | ocilogon(), ociplogon(), ocinlogon() | ocicommit(), ociserverversion(), ocinewcursor(), ociparse(), ocierror() | ocilogoff() | Link to Oracle database |
oci8 descriptor | ||||
oci8 server | ||||
oci8 session | ||||
oci8 statement | ocinewdescriptor() | ocirollback(), ocinewdescriptor(), ocirowcount(), ocidefinebyname(), ocibindbyname(), ociexecute(), ocinumcols(), ociresult(), ocifetch(), ocifetchinto(), ocifetchstatement(), ocicolumnisnull(), ocicolumnname(), ocicolumnsize(), ocicolumntype(), ocistatementtype(), ocierror() | ocifreestatement() | Oracle Cursor |
odbc link | odbc_connect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | odbc_close() | Link to ODBC database |
odbc link persistent | odbc_pconnect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | None | Persistent link to ODBC database |
odbc result | odbc_prepare() | odbc_binmode(), odbc_cursor(), odbc_execute(), odbc_fetch_into(), odbc_fetch_row(), odbc_field_name(), odbc_field_num(), odbc_field_type(), odbc_field_len(), odbc_field_precision(), odbc_field_scale(), odbc_longreadlen(), odbc_num_fields(), odbc_num_rows(), odbc_result(), odbc_result_all(), odbc_setoption() | odbc_free_result() | ODBC result |
birdstep link | ||||
birdstep result | ||||
OpenSSL key | openssl_get_privatekey(), openssl_get_publickey() | openssl_sign(), openssl_seal(), openssl_open(), openssl_verify() | openssl_free_key() | OpenSSL key |
OpenSSL X.509 | openssl_x509_read() | openssl_x509_parse(), openssl_x509_checkpurpose() | openssl_x509_free() | Public Key |
oracle Cursor | ora_open() | ora_bind(), ora_columnname(), ora_columnsize(), ora_columntype(), ora_error(), ora_errorcode(), ora_exec(), ora_fetch(), ora_fetch_into(), ora_getcolumn(), ora_numcols(), ora_numrows(), ora_parse() | ora_close() | Oracle cursor |
oracle link | ora_logon() | ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() | ora_logoff() | Link to oracle database |
oracle link persistent | ora_plogon() | ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() | None | Persistent link to oracle database |
pdf document | pdf_new() | pdf_add_bookmark(), pdf_add_launchlink(), pdf_add_locallink(), pdf_add_note(), pdf_add_pdflink(), pdf_add_weblink(), pdf_arc(), pdf_attach_file(), pdf_begin_page(), pdf_circle(), pdf_clip(), pdf_closepath(), pdf_closepath_fill_stroke(), pdf_closepath_stroke(), pdf_concat(), pdf_continue_text(), pdf_curveto(), pdf_end_page(), pdf_endpath(), pdf_fill(), pdf_fill_stroke(), pdf_findfont(), pdf_get_buffer(), pdf_get_image_height(), pdf_get_image_width(), pdf_get_parameter(), pdf_get_value(), pdf_lineto(), pdf_moveto(), pdf_open_ccitt(), pdf_open_file(), pdf_open_image_file(), pdf_place_image(), pdf_rect(), pdf_restore(), pdf_rotate(), pdf_save(), pdf_scale(), pdf_setdash(), pdf_setflat(), pdf_setfont(), pdf_setgray(), pdf_setgray_fill(), pdf_setgray_stroke(), pdf_setlinecap(), pdf_setlinejoin(), pdf_setlinewidth(), pdf_setmiterlimit(), pdf_setpolydash(), pdf_setrgbcolor(), pdf_setrgbcolor_fill(), pdf_setrgbcolor_stroke(), pdf_set_border_color(), pdf_set_border_dash(), pdf_set_border_style(), pdf_set_char_spacing(), pdf_set_duration(), pdf_set_font(), pdf_set_horiz_scaling(), pdf_set_parameter(), pdf_set_text_pos(), pdf_set_text_rendering(), pdf_set_value(), pdf_set_word_spacing(), pdf_show(), pdf_show_boxed(), pdf_show_xy(), pdf_skew(), pdf_stringwidth(), pdf_stroke(), pdf_translate(), pdf_add_thumbnail(), pdf_arcn(), pdf_begin_pattern(), pdf_begin_template(), pdf_end_pattern(), pdf_end_template(), pdf_initgraphics(), pdf_makespotcolor(), pdf_set_info(), pdf_setcolor(), pdf_setmatrix(), pdf_open_memory_image() | pdf_close(), pdf_delete() | PDF document |
pdf image | pdf_open_image(), pdf_open_image_file(), pdf_open_memory_image() | pdf_get_image_height(), pdf_get_image_width(), pdf_open_CCITT(), pdf_place_image() | pdf_close_image() | Image in PDF file |
pdf object | ||||
pdf outline | ||||
pgsql large object | pg_lo_open() | pg_lo_open(), pg_lo_create(), pg_lo_read(), pg_lo_read_all(), pg_lo_seek(), pg_lo_tell(), pg_lo_unlink(), pg_lo_write() | pg_lo_close() | PostgreSQL Large Object |
pgsql link | pg_connect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | pg_close() | Link to PostgreSQL database |
pgsql link persistent | pg_pconnect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | None | Persistent link to PostgreSQL database |
pgsql result | pg_execute(), pg_query(), pg_query_params(), pg_get_result() | pg_fetch_array(), pg_fetch_object(), pg_fetch_result(), pg_fetch_row(), pg_field_is_null(), pg_field_name(), pg_field_num(), pg_field_prtlen(), pg_field_size(), pg_field_type(), pg_last_oid(), pg_num_fields(), pg_num_rows(), pg_result_error(), pg_result_status() | pg_free_result() | PostgreSQL result |
pgsql string | ||||
printer | ||||
printer brush | ||||
printer font | ||||
printer pen | ||||
pspell | pspell_new(), pspell_new_config(), pspell_new_personal() | pspell_add_to_personal(), pspell_add_to_session(), pspell_check(), pspell_clear_session(), pspell_config_ignore(), pspell_config_mode(), pspell_config_personal(), pspell_config_repl(), pspell_config_runtogether(), pspell_config_save_repl(), pspell_save_wordlist(), pspell_store_replacement(), pspell_suggest() | None | pspell dictionary |
pspell config | pspell_config_create() | pspell_new_config() | None | pspell configuration |
Sablotron XSLT | xslt_create() | xslt_closelog(), xslt_openlog(), xslt_run(), xslt_set_sax_handler(), xslt_errno(), xslt_error(), xslt_fetch_result(), xslt_free() | xslt_free() | XSLT parser |
shmop | shmop_open() | shmop_read(), shmop_write(), shmop_size(), shmop_delete() | shmop_close() | |
sockets file descriptor set | socket() | accept_connect(), bind(), connect(), listen(), read(), write() | close() | Socket |
sockets i/o vector | ||||
dir | opendir() | readdir(), rewinddir() | closedir() | Dir handle |
stream | fopen(), tmpfile() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), flock(), fpassthru(), fputs(), fwrite(), fread(), fseek(), ftell(), fstat(), ftruncate(), set_file_buffer(), rewind() | fclose() | File handle |
pipe | popen() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | pclose() | Process handle |
socket | fsockopen(), pfsockopen() | fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | fclose() | Socket handle |
sybase-db link | sybase_connect() | sybase_query(), sybase_select_db() | sybase_close() | Link to Sybase database using DB library |
sybase-db link persistent | sybase_pconnect() | sybase_query(), sybase_select_db() | None | Persistent link to Sybase database using DB library |
sybase-db result | sybase_query(), sybase_unbuffered_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Sybase result using DB library |
sybase-ct link | sybase_connect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | sybase_close() | Link to Sybase database using CT library |
sybase-ct link persistent | sybase_pconnect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | None | Persistent link to Sybase database using CT library |
sybase-ct result | sybase_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Sybase result using CT library |
sysvsem | sem_get() | sem_acquire() | sem_release() | System V Semaphore |
sysvshm | shm_attach() | shm_remove(), shm_put_var(), shm_get_var(), shm_remove_var() | shm_detach() | System V Shared Memory |
wddx | wddx_packet_start() | wddx_add_vars() | wddx_packet_end() | WDDX packet |
xml | xml_parser_create(), xml_parser_create_ns() | xml_set_object(), xml_set_element_handler(), xml_set_character_data_handler(), xml_set_processing_instruction_handler(), xml_set_default_handler(), xml_set_unparsed_entity_decl_handler(), xml_set_notation_decl_handler(), xml_set_external_entity_ref_handler(), xml_parse(), xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number(), xml_get_current_byte_index(), xml_parse_into_struct(), xml_parser_set_option(), xml_parser_get_option() | xml_parser_free() | XML parser |
zlib | gzopen() | gzeof(), gzgetc(), gzgets(), gzgetss(), gzpassthru(), gzputs(), gzread(), gzrewind(), gzseek(), gztell(), gzwrite() | gzclose() | gz-compressed file |
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.
This section contains the context options supported by the wrappers that work over sockets, like tcp, http or ftp.
As of PHP 5.1.0 only one option is supported, bindto, which can be used to specify the IP address (either IPv4 or IPv6) and/or the port number that PHP will use to access the network. The syntax is ip:port (you can set the IP or the port number to 0 if you want to let the system choose them for you).
Nota: As FTP creates two socket connections during normal operation, you cannot specify the port number in the bindto option. So, the only supported syntax is ip:0 for the FTP wrapper.
Esempio M-1. Some examples of how to use the bindto option
|
PHP 3, PHP 4, PHP 5. https:// since PHP 4.3.0
http://example.com
http://example.com/file.php?var1=val1&var2=val2
http://user:password@example.com
https://example.com
https://example.com/file.php?var1=val1&var2=val2
https://user:password@example.com
Allows read-only access to files/resources via HTTP 1.0, using the HTTP GET method. A Host: header is sent with the request to handle name-based virtual hosts. If you have configured a user_agent string using your ini file or the stream context, it will also be included in the request.
Avvertimento |
When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To workaround this, you should lower your error_reporting level not to include warnings. PHP 4.3.7 and higher can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning for you. If you are using fsockopen() to create an ssl:// socket, you are responsible for detecting and suppressing the warning yourself. |
Redirects have been supported since PHP 4.0.5; if you are using an earlier version you will need to include trailing slashes in your URLs. If it's important to know the URL of the resource where your document came from (after all redirects have been processed), you'll need to process the series of response headers returned by the stream.
<?php $url = 'http://www.example.com/redirecting_page.php'; $fp = fopen($url, 'r'); /* Prior to PHP 4.3.0 use $http_response_header instead of stream_get_meta_data() */ $meta_data = stream_get_meta_data($fp); foreach($meta_data['wrapper_data'] as $response) { /* Were we redirected? */ if (substr(strtolower($response), 0, 18) == 'content-location: ') { /* update $url with where we were redirected to */ $url = substr($response, 18); } } ?> |
The stream allows access to the body of the resource; the headers are stored in the $http_response_header variable. Since PHP 4.3.0, the headers are available using stream_get_meta_data().
HTTP connections are read-only; you cannot write data or copy files to an HTTP resource.
Nota: HTTPS is supported starting from PHP 4.3.0, if you have compiled in support for OpenSSL.
Tabella M-2. Wrapper Summary
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 M-3. Context options
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). HTTPS proxying (through HTTP proxies) only works in PHP 5.1.0 or greater. | |
request_fulluri | When set to TRUE, the entire URI will be used when constructing the request. (i.e. GET http://www.example.com/path/to/file.html HTTP/1.0). While this is a non-standard request format, some proxy servers require it. | FALSE |
max_redirects | The max number of redirects to follow. Added in PHP 5.1.0. | 20 |
Underlying socket stream context options: Additional context options may be supported by the underlying transport For http:// streams, refer to context options for the tcp:// transport. For https:// streams, refer to context options for the ssl:// transport.
PHP 3, PHP 4, PHP 5. ftps:// since PHP 4.3.0
ftp://example.com/pub/file.txt
ftp://user:password@example.com/pub/file.txt
ftps://example.com/pub/file.txt
ftps://user:password@example.com/pub/file.txt
Allows read access to existing files and creation of new files via FTP. If the server does not support passive mode ftp, the connection will fail.
You can open files for either reading or writing, but not both simultaneously. If the remote file already exists on the ftp server and you attempt to open it for writing but have not specified the context option overwrite, the connection will fail. If you need to overwrite existing files over ftp, specify the overwrite option in the context and open the file for writing. Alternatively, you can use the FTP extension.
Appending: As of PHP 5.0.0 files may be appended via the ftp:// URL wrapper. In prior versions, attempting to append to a file via ftp:// will result in failure.
ftps:// was introduced in PHP 4.3.0. It is the same as ftp://, but attempts to negotiate a secure connection with the ftp server. If the server does not support SSL, then the connection falls back to regular unencrypted ftp.
Nota: FTPS is supported starting from PHP 4.3.0, if you have compiled in support for OpenSSL.
Tabella M-4. Wrapper Summary
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 | As of PHP 5.0.0: filesize(), filetype(), file_exists(), is_file(), and is_dir() elements only. As of PHP 5.1.0: filemtime(). |
Supports unlink() | No | Yes |
Supports rename() | No | Yes |
Supports mkdir() | No | Yes |
Supports rmdir() | No | Yes |
Tabella M-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) |
proxy (PHP 5.1.0 or greater) | Proxy FTP request via http proxy server. Applies to file read operations only. Ex: tcp://squid.example.com:8000 |
Underlying socket stream context options: Additional context options may be supported by the underlying transport For ftp:// streams, refer to context options for the tcp:// transport. For ftps:// streams, refer to context options for the ssl:// transport.
PHP 3.0.13 and up, php://output and php://input since PHP 4.3.0, php://filter since PHP 5.0.0.
php://stdin
php://stdout
php://stderr
php://output
php://input
php://filter
php://stdin, php://stdout and php://stderr allow access to the corresponding input or output stream of the PHP process.
php://output allows you to write to the output buffer mechanism in the same way as print() and echo().
php://input allows you to read raw POST data. It is a less memory intensive alternative to $HTTP_RAW_POST_DATA and does not need any special php.ini directives. php://input is not available with enctype="multipart/form-data".
php://stdin and php://input are read-only, whereas php://stdout, php://stderr and php://output are write-only.
php://filter is a kind of meta-wrapper designed to permit the application of filters to a stream at the time of opening. This is useful with all-in-one file functions such as readfile(), file(), and file_get_contents() where there is otherwise no opportunity to apply a filter to the stream prior the contents being read.
The php://filter target takes the following 'parameters' as parts of its 'path'.
/resource=<stream to be filtered> (required) This parameter must be located at the end of your php://filter specification and should point to the stream which you want filtered.
/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 M-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 M-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 |
ssh2.shell:// ssh2.exec:// ssh2.tunnel:// ssh2.sftp:// ssh2.scp:// PHP 4.3.0 and up (PECL)
ssh2.shell://user:pass@example.com:22/xterm
ssh2.exec://user:pass@example.com:22/usr/local/bin/somecmd
ssh2.tunnel://user:pass@example.com:22/192.168.0.1:14
ssh2.sftp://user:pass@example.com:22/path/to/filename
This wrapper is not enabled by default: In order to use the ssh2.*:// wrappers you must install the SSH2 extension available from PECL.
In addition to accepting traditional URI login details, the ssh2 wrappers will also reuse open connections by passing the connection resource in the host portion of the URL.
Tabella M-8. Wrapper Summary
Attribute | ssh2.shell | ssh2.exec | ssh2.tunnel | ssh2.sftp | ssh2.scp |
---|---|---|---|---|---|
Restricted by allow_url_fopen. | Yes | Yes | Yes | Yes | Yes |
Allows Reading | Yes | Yes | Yes | Yes | Yes |
Allows Writing | Yes | Yes | Yes | Yes | No |
Allows Appending | No | No | No | Yes (When supported by server) | No |
Allows Simultaneous Reading and Writing | Yes | Yes | Yes | Yes | No |
Supports stat() | No | No | No | Yes | No |
Supports unlink() | No | No | No | Yes | No |
Supports rename() | No | No | No | Yes | No |
Supports mkdir() | No | No | No | Yes | No |
Supports rmdir() | No | No | No | Yes | No |
Tabella M-9. Context options
Name | Usage | Default |
---|---|---|
session | Preconnected ssh2 resource to be reused | |
sftp | Preallocated sftp resource to be reused | |
methods | Key exchange, hostkey, cipher, compression, and MAC methods to use | |
callbacks | ||
username | Username to connect as | |
password | Password to use with password authentication | |
pubkey_file | Name of public key file to use for authentication | |
privkey_file | Name of private key file to use for authentication | |
env | Associate array of environment variables to set | |
term | Terminal emulation type to request when allocating a pty | |
term_width | Width of terminal requested when allocating a pty | |
term_height | Height of terminal requested when allocating a pty | |
term_units | Units to use with term_width and term_height | SSH2_TERM_UNIT_CHARS |
ogg:// PHP 4.3.0 and up (PECL)
ogg://soundfile.ogg
ogg:///path/to/soundfile.ogg
ogg://http://www.example.com/path/to/soundstream.ogg
This wrapper is not enabled by default: In order to use the ogg:// wrapper you must install the OGG/Vorbis extension available from PECL.
Files opened for reading via the ogg:// wrapper are treated as compressed audio encoded using the OGG/Vorbis codec. Similarly, files opened for writing or appending via the ogg:// wrapper are writen as compressed audio data. stream_get_meta_data(), when used on an OGG/Vorbis file opened for reading will return various details about the stream including the vendor tag, any included comments, the number of channels, the sampling rate, and the encoding rate range described by: bitrate_lower, bitrate_upper, bitrate_nominal, and bitrate_window.
Tabella M-10. Wrapper Summary
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 |
Supports unlink() | No |
Supports rename() | No |
Supports mkdir() | No |
Supports rmdir() | No |
Tabella M-11. Context options
Name | Usage | Default | Mode |
---|---|---|---|
pcm_mode | PCM encoding to apply while reading, one of: OGGVORBIS_PCM_U8, OGGVORBIS_PCM_S8, OGGVORBIS_PCM_U16_BE, OGGVORBIS_PCM_S16_BE, OGGVORBIS_PCM_U16_LE, and OGGVORBIS_PCM_S16_LE. (8 vs 16 bit, signed or unsigned, big or little endian) | OGGVORBIS_PCM_S16_LE | Read |
rate | Sampling rate of input data, expressed in Hz | 44100 | Write/Append |
bitrate | When given as an integer, the fixed bitrate at which to encode. (16000 to 131072) When given as a float, the variable bitrate quality to use. (-1.0 to 1.0) | 128000 | Write/Append |
channels | The number of audio channels to encode, typically 1 (Mono), or 2 (Stero). May range as high as 16. | 2 | Write/Append |
comments | An array of string values to encode into the track header. | Write/Append |
expect:// PHP 4.3.0 and up (PECL)
expect://command
This wrapper is not enabled by default: In order to use the expect:// wrapper you must install the Expect extension available from PECL.
Streams opened via the expect:// wrapper provide access to process'es stdio, stdout and stderr via PTY.
The following is a list of a few built-in stream filters for use with stream_filter_append(). Your version of PHP may have more filters (or fewer) than those listed here.
It is worth noting a slight asymmetry between stream_filter_append() and stream_filter_prepend(). Every PHP stream contains a small read buffer where it stores blocks of data retrieved from the filesystem or other resource in order to process data in the most efficient manner. As soon as data is pulled from the resource into the stream's internal buffer, it is immediately processed through any attached filters whether the PHP application is actually ready for the data or not. If data is sitting in the read buffer when a filter is appended, this data will be immediately processed through that filter making the fact that it was sitting in the buffer seem transparent. However, if data is sitting in the read buffer when a filter is prepended, this data will NOT be processed through that filter. It will instead wait until the next block of data is retrieved from the resource.
For a list of filters installed in your version of PHP use stream_get_filters().
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 N-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 N-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 Compression Wrappers provide a way of creating gzip and bz2 compatible files on the local filesystem, they do not provide a means for generalized compression over network streams, nor do they provide a means to begin with a non-compressed stream and transition to a compressed one. For this, a compression filter may be applied to any stream resource at any time.
Nota: Compression filters do not generate headers and trailers used by commandline utilites such as gzip. They only compress and decompress the payload portions of compressed data streams.
zlib.deflate (compression) and zlib.inflate (decompression) are implementations of the compression methods described in RFC 1951. The deflate filter takes up to three parameters passed as an associative array. level describes the compression strength to use (1-9). Higher numbers will generally yield smaller payloads at the cost of additional processing time. Two special compression levels also exist: 0 (for no compression at all), and -1 (zlib internal default -- currently 6). window is the base-2 log of the compression loopback window size. Higher values (up to 15 -- 32768 bytes) yield better compression at a cost of memory, while lower values (down to 9 -- 512 bytes) yield worse compression in a smaller memory footprint. Default window size is currently 15. memory is a scale indicating how much work memory should be allocated. Valid values range from 1 (minimal allocation) to 9 (maximum allocation). This memory allocation affects speed only and does not impact the size of the generated payload.
Nota: Because compression level is the most commonly used parameter, it may be alternatively provided as a simple integer value (rather than an array element).
zlib.* compression filters are available with PHP as of version 5.1.0 if zlib support is enabled. They are also available as a backport in version 5.0.x by installing the zlib_filter package from PECL. These filters are not available for PHP 4.
Esempio N-7. zlib.deflate and zlib.inflate
|
Esempio N-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, or as the small element of an associative array. small, when set to a TRUE value, instructs the bzip library to perform decompression in a minimal memory footprint at the cost of speed.
bzip2.* compression filters are available with PHP as of version 5.1.0 if bz2 support is enabled. They are also available as a backport in version 5.0.x by installing the bz2_filter package from PECL. These filters are not available for PHP 4.
Esempio N-9. bzip2.compress and bzip2.decompress
|
mcrypt.* and mdecrypt.* provide symmetric encryption and decryption using libmcrypt. Both sets of filters support the same algorithms available to mcrypt extension in the form of mcrypt.ciphername where ciphername is the name of the cipher as it would be passed to mcrypt_module_open(). The following five filter parameters are also available:
Tabella N-1. mcrypt filter parameters
Parameter | Required? | Default | Sample Values |
---|---|---|---|
mode | Optional | cbc | cbc, cfb, ecb, nofb, ofb, stream |
algorithms_dir | Optional | ini_get('mcrypt.algorithms_dir') | Location of algorithms modules |
modes_dir | Optional | ini_get('mcrypt.modes_dir') | Location of modes modules |
iv | Required | N/A | Typically 8, 16, or 32 bytes of binary data. Depends on cipher |
key | Required | N/A | Typically 8, 16, or 32 bytes of binary data. Depends on cipher |
Esempio N-10. Encrypting file output using 3DES
|
Esempio N-11. Reading an encrypted file
|
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.0 sslv2:// & sslv3:// since PHP 5.0.2
Nota: If no transport is specified, tcp:// will be assumed.
127.0.0.1
fe80::1
www.example.com
tcp://127.0.0.1
tcp://fe80::1
tcp://www.example.com
udp://www.example.com
ssl://www.example.com
sslv2://www.example.com
sslv3://www.example.com
tls://www.example.com
Internet Domain sockets expect a port number in addition to a target address. In the case of fsockopen() this is specified in a second parameter and therefore does not impact the formatting of transport URL. With stream_socket_client() and related functions as with traditional URLs however, the port number is specified as a suffix of the transport URL delimited by a colon.
tcp://127.0.0.1:80
tcp://[fe80::1]:80
tcp://www.example.com:80
IPv6 numeric addresses with port numbers: In the second example above, while the IPv4 and hostname examples are left untouched apart from the addition of their colon and portnumber, the IPv6 address is wrapped in square brackets: [fe80::1]. This is to distinguish between the colons used in an IPv6 address and the colon used to delimit the portnumber.
The ssl:// and tls:// transports (available only when openssl support is compiled into PHP) are extensions of the tcp:// transport which include SSL encryption. Since PHP 4.3.0 OpenSSL support must be statically compiled into PHP, since PHP 5.0.0 it may be compiled as a module or statically.
ssl:// will attempt to negotiate an SSL V2, or SSL V3 connection depending on the capabilities and preferences of the remote host. sslv2:// and sslv3:// will select the SSL V2 or SSL V3 protocol explicitly.
Tabella O-1. Context options for ssl:// and tls:// transports (since PHP 4.3.2)
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 P-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 P-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 P-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 Q-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_CLONE | clone | classes and objects. PHP 5 only. |
T_CLOSE_TAG | ?> or %> | |
T_COMMENT | // or #, and /* */ on PHP 5 | 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_DOC_COMMENT | /** */ | PHPDoc style comments (PHP 5 only) |
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_INSTANCEOF | instanceof | type operators (PHP5 only) |
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_IS_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 (PHP 4 only) |
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 | :: | ::. Also defined as T_DOUBLE_COLON. |
T_PLUS_EQUAL | += | assignment operators |
T_PRINT | print() | print() |
T_PRIVATE | private | classes and objects. PHP 5 only. |
T_PUBLIC | public | classes and objects. PHP 5 only. |
T_PROTECTED | protected | classes and objects. PHP 5 only. |
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 sul sito PHP.net e sui numerosi siti mirror. Per ottenere risultati migliori, dovresti scegliere il mirror a te più vicino. Puoi leggere il manuale sia in un formato HTML adatto alla stampa, sia in un formato HTML che integri le potenzialità "look and feel" del PHP.
Due vantaggio del manuale online sulla maggior parte dei formati offline sono l'integrazione dei contributi degli utenti e le scorciatoie URL che permettono di ottenere rapidamente la pagina del manuale desiderata. Ovviamente, per poter visualizzare il manuale online, dovrai essere collegato ad internet.
Ci sono diversi tipi di manuale scaricabili, e il formato più appropriato alle tue esigenze dipende dal tipo di sistema operativo che usi e dal tuo personale modo di leggere. Per informazioni su come il manuale viene generato in così tanti formati, leggi la sezione 'Come generiamo i formati' di questa appendice.
Il formato più adatto a diversi tipi di sistemi operativi è l'HTML. Il formato HTML è disponibile sia come unica pagina HTML, sia come pacchetto di file univoci per ogni sezione (cioè qualche migliaio di file). Queste versioni sono fornite compresse, pertanto occorre disporre di utility di decompressione per ottenere i file contenuti negli archivi.
Un altro formato adatto a diversi tipi di sistemi operativi e alla stampa è il formato PDF, conosciuto anche come Adobe Acrobat. Ma prima di scaricare questo tipo di formato e iniziare a stampare il manuale, sappi che è contiene oltre 2000 pagine e che viene aggiornato e corretto frequentemente
Nota: Se ancora non hai un programma in grado di leggere il formato PDF, hai bisogno di scaricare Adobe Acrobat Reader.
Per le piattaforme Windows, la versione HTML Help per Windows del manuale fornisce contenuti utilizzabili con le applicazioni HTML Help per Windows. Questo tipo di versione è fornita con un motore di ricerca per tutto il contenuto, con un indice completo e con la possibilità di salvare le ricerche. Molte versioni di manuale PHP per Windows integrano anche questa versione della documentazione, per garantire un accesso più semplice. Sono disponibili diversi visualizzatori CHM per Linux. Alcuni esempi: xCHM oppure GnoCHM.
Inoltre esiste una versione CHM estesa, che viene aggiornata con frequenza minore, ma fornisce maggiori caratteristiche. E' disponibile soltanto su Microsoft Windows a causa della tecnologia utilizzata per realizzare queste pagine.
I contributi degli utenti giocano un ruolo importante nello sviluppo di questo manuale. Possiamo includere questi feedback nel testo principale del manuale permettendo agli utenti di contribuire con esempi, avvertimenti e chiarimenti riguardo a diversi tipi di browser. I contributi inviati dagli utenti sono visibili, così come sono stati inviati, nel formato online del manuale ed in alcuni dei formati scaricabili.
Nota: I contributi degli utenti NON sono controllati prima di essere messi online, quindi la chiarezza del contenuto, gli esempi di codice o l'esattezza stessa dei contributi non puù essere garantita. (E non c'è alcuna garanzia sulla qualità o sull'esattezza del testo dello stesso manuale.)
Nota: Dal punto di vista della licenza i contributi degli utenti sono considerati parte del manuale PHP, e quindi coperti dalla stessa licenza che si applica a questa cocumentazione (Open Publication License al momento). Per maggiori dettagli vedere la pagina Manual's Copyright.
Nel manuale ciascuna funzione è documentata per un rapido riferimento. Conoscendo come leggere e capendo il testo si è in grado di apprendere il PHP molto più facilmente. Piuttosto che appoggiarsi sugli esempi o sul copia e incolla, preferirai sicuramente sapere come leggere la definizione di una funzione. Cominciamo:
Pre-requisito: comprensione di base dei tipi di variabili: Sebbene il PHP sia un linguaggio poco tipizzato (loosely typed), è importante avere una conoscenza di base delle tipologie di variabili per il loro importante significato.
La definizione della funzione ci dice quale tipo di valore viene restituito. Utilizziamo la definizione di strlen() come nostro primo esempio:
strlen (PHP 3, PHP 4, PHP 5) strlen -- Restituisce la lunghezza di una stringa Description int strlen ( string str ) Restituisce la lunghezza di una stringa. |
Tabella R-1. Spiegazione della definizione di una funzione
Parte | Descrizione |
---|---|
strlen | Nome della funzione. |
(PHP 3, PHP 4, PHP 5) | strlen() è disponibile in tutte le versioni di PHP 3, PHP 4 e PHP 5 |
int | Tipo di valore restituito dalla funzione, il quale è un intero (la lunghezza di una stringa si misura in numei). |
( string str ) | Il primo (ed in questo caso unico) parametro/argomento per questa funzione si chiama str, ed è una stringa. |
Si potrebbe riscrivere la funzione precedente in modo generico:
returned type function name ( parameter type parameter name ) |
Diverse funzioni hanno diversi parametri, tipo in_array(). Il loro prototipo è:
bool in_array ( mixed needle, array haystack [, bool strict]) |
Cosa significa? in_array() restituisce un valore boolean value, TRUE se riesce (se il parametro needle viene trovato in haystack) oppure FALSE se fallisce (se il parametro needle non viene trovato in haystack). Il primo parametro si chiama needle e può essere di diversi tipi, pertanto lo chiameremo "mixed". Questo parametro needle di tipo mixed (che indica che il valore che stiamo cercando) può essere sia un valore scalare (stringa, intero, oppure float), sia una matrice. haystack (che indica la variabile in cui cercare) è il secondo parametro. Il terzo parametro opzionale è chiamato strict. Tutti i parametri opzionali sono racchiusi tra parentesi [ quadre ]. Il manuale indica che il valore di defualt per strict è il boolean FALSE. Vedere le pagine del manuale di ciascuna funzione per i dettagli di come funziona.
Esistono anche funzioni con complesse informazioni sulla versione PHP. Ad esempio la funzione html_entity_decode():
(PHP 4 >= 4.3.0, PHP 5) |
Questo significa che questa funzione non era disponibile con il PHP 3, ed è soltanto disponibile a partire dalla release PHP 4.3.0.
Questa documentazione contiene informazioni sulle versioni di PHP 4 e 5, con note sulla migrazione e sulla compatibilità con PHP 3. Il comportamento, i parametri, i valori restituiti ed altre modifiche tra le differenti versioni di PHP sono documentate nelle note e nel testo del manuale.
Si può anche trovare la documentazione sulla versione CVS del PHP, che indica l'ultima verisone in fase di sviluppo, disponibile tramite il sistema di gestione delle versioni CVS. Se non si è sviluppatori del PHP, e non si è ansiosi di utilizzare l'ultimissima versione di PHP, le caratteristiche codificate come "available in CVS" non sono accessibili. Queste caratteristiche, riteniamo, saranno disponibili nella successiva versione stabile del PHP. Se si desidera scaricare la versione CVS vedere la pagina accesso anonimo al CVS.
Si può anche incontrare documentazione di versioni di PHP non ancora rilasciate (tipo PHP 5.0.0 mentre l'ultima versione stabile rilasciata è la 4.3.x). Il più delle volte non si tratta di un errore nella documentazione. Spesso si aggiungono informazioni per caratteristiche non disponibili nella versione corrente di PHP, ma che lo saranno in una versione futura gà nota. In genere il PHP aggiunge nuove caratteristiche nelle release principali, negli altri casi si tratta di correzione di problemi. Nella codifica della versione A.B.C, le release principali aggiornano il numero A o B, mentre le correzioni aggiornano il numero C. Così, ad esempio, è possibile che sia documentata una caratteristica disponibile in PHP x.1.x quando l'ultima versione rilasciata sia PHP x.0.x. Inoltre il manuale è scritto con i verbi al tempo presente, e non futuro
In diverse occasioni il manuale del PHP presenta dei "valori di default" per le configurazioni di PHP. Questi valori sono basati sul php.ini-dist e non sul php.ini-recommended. Inoltre essi si riferiscono all'ultima versione di PHP. Vedere la pagina di appendice parametri di configurazione del PHP per dettagli e modifiche su questi valori.
Lo scopo di questo manuale non è quello di fornire istruzioni sulla pratica in generale della programmazione. Se questa è la tua prima visita, o se sei un programmatore alle prime armi, potresti trovare difficile imparare a programmare usando solo questo manuale. Forse stai cercando un testo più adatto ai principianti: puoi trovare una lista di libri sul PHP su http://www.php.net/books.php.
Ci sono diverse mailing list attive per discutere su tutti gli aspetti del programmare con il PHP. Se sei bloccato con un problema per il quale non riesci a trovare una soluzione con le tue sole conoscenze, potresti trovare l'aiuto di qualcuno più esperto in una di queste mailing list. Puoi trovare un elenco di mailing list con link agli arretrati e altre risorse utili online alle pagine di spupporto di PHP.net. Inoltre, sulla pagina dei link in PHP.net troverai un elenco di siti dedicati al PHP con articoli, forum di discussione e numerosi script.
Ci sono tre modi per aiutarci a migliorare questa documentazione.
Se trovi errori all'interno di questo manuale, in qualsiasi lingua esso sia, comunicacelo usando lo stesso sistema per segnalare bug su http://bugs.php.net/, classificando il bug come "Errore nella documentazione". Allo stesso indirizzo puoi anche segnalare problemi relativi ad uno specifico formato di manuale.
Nota: Sei però pregato di non abusare del sistema per segnalare bug spedendo richieste di aiuto. Se proprio sei in difficoltà, usa le mailing list o le community segnalate prima.
Contribuendo con l'invio di note, puoi fornire ulteriori esempi, avvertimenti e chiarificazioni per altri lettori, ma sei pregato di non segnalare bug usando il sistema di invio delle note. Per saperne di più sul sistema di invio delle note puoi leggere la sezione Sistema di invio delle note di questa appendice.
Se conosci l'inglese ed altre lingue stere, puoi aiutare nella traduzione del manuale. Se desideri iniziare una nuova traduzione, o aiutare un progetto di traduzione, leggi la pagina http://cvs.php.net/co.php/phpdoc/howto/howto.html.tar.gz.
Il progetto di documentazione PHP usa un canale IRC tramite il quale si può discutere con gli autori del manuale, indicare alcuni aspetti del manuale sui quali vuole essere di aiuto. Questo canale è #phpdoc su irc.freenode.net.
Questo manuale è scritto in XML usando il DocBook XML DTD e usando DSSSL (Document Style and Semantic Specification Language) per la formattazione, e sperimentalmente XSLT (Extensible Stylesheet Language Transformations) per il mantenimento e la formattazione.
Usare l'XML come formato originale rende possibile generare diversi tipi di formato partendo da un unico sorgente, mantenendo solo un sorgente per tutti i diversi formati. Gli strumenti utilizzati per formattare le versioni inHTML e TeX sono Jade, scritto da James Clark, e The Modular DocBook Stylesheet, scritto da Norman Walsh. Per generare la versione HTML Help per Windows usiamo Microsoft HTML Help Workshop e, ovviamente, anche PHP stesso per qualche conversione addizionale e per la formattazione.
Puoi scaricare il manuale in diverse lingue e formati, compresi l'HTML, il PDF, il PalmPilot DOC, il PalmPilot iSilo e l'HTML Help per Windows da http://www.php.net/docs.php. Nota, per motivi tecnici, non tutti i formati sono disponibili.
Puoi trovare più informazioni su come scaricare il sorgente XML di questo documento su http://cvs.php.net/. La documentazione e racchiusa in moduli phpdoc.
Il manuale PHP è disponibile non solo in vari formati, am anche in varie lingue. Il testo originale è scritto in inglese, mentre gruppi di persone da tutto il modno si occupano di tradurlo nelle rispettive lingue. Se non esiste la traduzione per un specifico capitolo o funzione la procedura di compila del manuale utilizza la versione inglese del capitolo.
Le persone che si occupano della traduzioni iniziano dal codice XML disponibile da http://cvs.php.net/ e da questo partono per la traduzione nella propria lingua. Non si usa il codice HTML, il testo normale, o la versione PDF. E' il sistema di compila che si occupa della conversione da XML ai vari formati.
Nota: Se si desidera aiutare la traduzione nella propria lingua, occorre entrare in contatto con il gruppo di traduzione/documentazione tramite la mailing list phpdoc: inviare una mail vuota a phpdoc-subscribe@lists.php.net. L'indirizzo della mailing list è phpdoc@lists.php.net. Indicare nel messaggio che si è interessati alla traduzione del manuale in una determinata lingua e si sarà contattati da qualcuno che aiuterà o a cominciare una nuova traduzione o a entrare in contatto con il gruppo di documentazione della propria lingua.
Al momento il manuale è disponibile, anche parzialmente, nelle seguenti lingue: Brasiliano Portoghese, Cinese (semplificato), Cinese (Hong Kong Cantonese), Cinese (Tradizionale), Ceco, Olandese, Finlandese, Francese, Tedesco, Greco, Ebreo, Ungherese, Italiano, Giapponese, Coreano, Polacco, Rumeno, Russo, Slovacco, Sloveno, Spagnolo, Svedese e Turco.
Tutte le versioni possono essere scaricate da: http://www.php.net/docs.php.
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.