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 nascosto| Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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_RETURNTRANSFER| 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_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 indices| Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 indices| Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva 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 avver