Crea sito

Content



Manuale PHP

by:
Mehdi Achour
Friedhelm Betz
Antony Dovgal
Nuno Lopes
Hannes Magnusson
Georg Richter
Damien Seguy
Jakub Vrana
2014-05-09
Edited By: Philip Olson
Edited By: Luca Perugini
Edited By: Simone Cortesi
Edited By: Marco Cucinato
Edited By: Darvin Andrioli
Tradotto con la collaborazione di:
Massimo Colombo
Marco De Nittis
Fabio Gandola
Sergio Marchesini
Alan D'Angelo
Giacomo Tesio
Marco Spisto
Gabriele Scaroni
Mariano Calandra
Rocco Curcio
Luca Costantino
Fernando Fusano
Andrea Paramithiotti

Copyright

Questo manuale è © 1997 - 2014 del Gruppo di Documentazione PHP. Questo manuale può essere redistribuito secondo i termini e le condizioni indicate dalla Creative Commons Attribution 3.0 o successive. Una copia della Creative Commons Attribution 3.0 license è distribuita con questo manuale. La versione più recente è disponibile a » http://creativecommons.org/licenses/by/3.0/.

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 » doc-license@lists.php.net. Nota: questo indirizzo porta ad una mailing list pubblica.



Manuale PHP


Prefazione

PHP, che significa "PHP: Hypertext Preprocessor", è un linguaggio di scripting general-purpose Open Source molto utilizzato, è specialmente indicato per lo sviluppo Web e può essere integrato nell'HTML. La sua sintassi è basata su quella di C, Java e Perl, ed è molto semplice da imparare. L'obiettivo principale del linguaggio è quello di permettere agli sviluppatori web di scrivere velocemente pagine web dinamiche, ma con PHP si possono fare molte altre cose.

Questo manuale consiste principalmente in un elenco commentato di funzioni, ma contiene anche una guida al linguaggio, la spiegazione di alcune delle principali caratteristiche e altre informazioni aggiuntive.

Il manuale è fornito in diversi formati qui: » http://www.php.net/download-docs.php. 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.

Autori e Contributori

Evidenziamo le persone attualmente più attive sulla prima pagina del manuale, ma ci sono molti altri contributori che ci aiutano nel nostro lavoro o che hanno dato un grande aiuto al progetto nel passato. C'è un gran numero di persone non citate che aiutano con le loro annotazioni sulle pagine del manuale, le quali vengono continuamente incluse nei riferimenti; siamo molto grati di questo lavoro. Tutte le liste qui sotto sono in ordine alfabetico.

Autori e Redattori

I seguenti contributori devono essere riconosciuti per l'impatto che hanno avuto o continuano a dare aggiungendo contenuti al manuale: Bill Abt, Jouni Ahto, Alexander Aulbach, Daniel Beckham, Stig Bakken, Nilgün Belma Bugüner, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Peter Cowburn, Daniel Egeberg, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Pierre-Alain Joye, Etienne Kneuss, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Stanislav Malyshev, Justin Martin, Rafael Martinez, Rick McGuire, Moacir de Oliveira Miranda Júnior, Kalle Sommer Nielsen, Yasuo Ohgaki, Richard Quadling, Derick Rethans, Rob Richards, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Masahiro Takagi, Yannick Torres, Michael Wallner, Lars Torben Wilson, Jim Winstead, Jeroen van Wolffelaar e Andrei Zmievski.

I seguenti contributori hanno effettuato un significativo lavoro redigendo il manuale: Stig Bakken, Gabor Hojtsy, Hartmut Holzgraefe e Egon Schmid.

Mantenitori delle note utente

I mantenitori attualmente più attivi sono: Daniel Brown, Nuno Lopes, Felipe Pena, Thiago Pojda e Maciek Sokolewicz.

Anche queste persone si sono impegnate a gestire le note utente: Mehdi Achour, Daniel Beckham, Friedhelm Betz, Victor Boivie, Jesus M. Castagnetto, Nicolas Chaillan, Ron Chmara, Sean Coates, James Cox, Vincent Gevers, Sara Golemon, Zak Greant, Szabolcs Heilig, Oliver Hinckel, Hartmut Holzgraefe, Etienne Kneuss, Rasmus Lerdorf, Matthew Li, Andrew Lindeman, Aidan Lister, Hannes Magnusson, Maxim Maletsky, Bobby Matthis, James Moore, Philip Olson, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Tom Sommer, Jani Taskinen, Yasuo Ohgaki, Jakub Vrana, Lars Torben Wilson, Jim Winstead, Jared Wyles e Jeroen van Wolffelaar.




Guida Rapida


Introduzione

Indice dei contenuti


Che cos'è il PHP?

PHP (acronimo ricorsivo per PHP: Hypertext Preprocessor) è un linguaggio di scripting general-purpose open source molto utilizzato, è specialmente indicato per lo sviluppo web e può essere integrato nell'HTML.

Bello, ma che cosa significa? Un esempio:

Example #1 Un esempio introduttivo

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>Esempio</title>
    </head>
    <body>

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

    </body>
</html>

Invece di un sacco di comandi per produrre HTML (come si è visto in C o Perl), le pagine PHP contengono HTML con codice incorporato che fa "qualcosa" (in questo caso, produce "Ciao, sono uno script PHP!"). Il codice PHP è delimitato da speciali istruzioni di elaborazione di inizio e fine <?php e ?> che permettono di entrare e uscire dalla "modalità PHP".

Ciò che distingue PHP da altri linguaggi di scripting del tipo client-side JavaScript è che il codice viene eseguito nel server, generando HTML che sarà dopo inviato al client. Il client dovrebbe ricevere i risultati dell'esecuzione dello script, ma non potrà conoscere qual'è il codice eseguito. Potete persino configurare il vostro web server per processare tutte i vostri file HTML con PHP ed allora non ci sarebbe realmente alcun modo per gli utenti di sapere cosa avete sul vostro server.

La cosa più interessante nell'uso di PHP è che si tratta di un linguaggio estremamente semplice per il neofita, ma che, tuttavia, offre molte prestazioni avanzate al programmatore di professione. Non lasciatevi impressionare dalla lunga lista delle potenzialità di PHP. In poco tempo potrete iniziare a creare velocemente semplici scripts.

Sebbene lo sviluppo di PHP abbia come obiettivo lo scripting server-side, si può fare molto di più con esso. Leggete, e consultate la sezione Che cosa può fare PHP? oppure andate su tutorial introduttivo se si è interessati solo alla programmazione web.



Che cosa può fare PHP?

Qualsiasi cosa. PHP ha come obiettivo principale lo scripting server-side, per cui può fare tutto ciò che può fare un qualunque programma CGI, come raccogliere dati da un form, generare pagine dai contenuti dinamici, oppure mandare e ricevere cookies. Ma PHP può fare molto di più.

Esistono tre campi principali in cui vengono usati gli scripts PHP.

  • Lo scripting server-side. Questo è il campo più tradizionale ed il maggiore obiettivo del PHP. Per fare questo lavoro occorrono tre cose. Il parser PHP (CGI o server module), un webserver ed un browser web. Occorre avviare il server web con un'installazione di PHP attiva. Si può accedere all'output del programma PHP con un browser web e vedere la pagina PHP tramite il server. Tutto ciò può essere attivato sul pc di casa se si desidera semplicemente 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 processamento 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, IIS, e molti altri. E questo include qualsiasi server web che può utilizzare il binario PHP FastCGI, come lighttpd e nginx. PHP funziona sia come un modulo, o sia 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 (OOP), o una combinazione di entrambe.

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 database. Scrivere una pagina web collegata ad un database è incredibilmente semplice utilizzando una delle specifiche estensioni del database (p.e., per mysql), o utilizzando un abstraction layer come PDO, o connettendosi a qualsiasi database che supporta lo standard Open Database Connection tramite l' estensione ODBC. Altri database possono utilizzare cURL o i socket, come CouchDB.

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'istanziazione dei Java Objects e l'utilizzo di questi come oggetti PHP in modo trasparente.

PHP possiede utili caratteristiche per l'elaborazione testi, che includono la compatibilità alle espressioni regolari di Perl (PCRE), e molte estensioni e strumenti per analizzare e accedere ai documenti XML. PHP standardizza tutte le estensioni XML sulla solida base di libxml2, ed estende le caratteristiche aggiungendo il supporto SimpleXML, XMLReader e XMLWriter.

E molte altre estensioni interessanti esistono, e sono categorizzate sia in ordine alfabetico che per categoria. E ci sono latre estensioni PECL che possono essere o no documentate all'interno del manuale PHP, come » XDebug.

Come si può notare, questa pagina non è sufficiente per elencare tutte le funzioni e i benefici che PHP offre. Continua a leggere, consultando le sezioni Installazione di PHP, e guarda la parte sul riferimento alle funzioni per delle spiegazioni sulle estensioni menzionate qui.




Una semplice introduzione

Indice dei contenuti

Di seguito, in una breve e semplice introduzione, vorremmo mostrare alcuni esempi per l'utilizzo di PHP. Essi sono relativi soltanto alla creazione dinamica di pagine web, anche se PHP non ha funzionalità limitate esclusivamente alla creazione delle sole pagine web. Fare riferimento alla sezione intitolata Cosa può fare PHP per avere ulteriori informazioni.

Le pagine web create con PHP vengono trattate come normali pagine HTML e possono essere create e modificate nello stesso modo in cui si sviluppano normali pagine HTML.


Di cosa ho bisogno?

In questo tutorial assumiamo che il vostro server abbia il suporto PHP attivato e che tutti i file con estensione .php vengano gestiti da questo. Quasi in tutti i server questa è l'estensione di default per i file PHP., ma consultatevi col vostro system administrator per sicurezza. Se il vostro server supporta PHP, allora, non è necessario fare nulla. Semplicemente create i vostri file .php e scaricateli nella vostra directory web, il server le analizzerà e le eseguirà magicamente. Non è necessario compilare nulla nè installare strumenti aggiuntivi. Si pensi ai file PHP come a dei semplici file HTML con una intera famiglia aggiuntiva di magici tags che consentono di fare ogni sorta di cose. Molti web host offrono il supporto PHP, ma se il vostro host non ce l'ha considerate la lettura della sezione »  Link di PHP per delle risorse per trovare web host che supportano PHP.

Diciamo che si vuole risparmiare larghezza di banda preziosa e sviluppare a livello locale. In questo caso, si vorrà installare un web server, come » Apache, e naturalmente » PHP. È molto probabile che si desidera installare anche un database, come » MySQL.

È possibile installare questi applicativi singolarmente o scegliere un modo più semplice. Il nostro manuale ha istruzioni per l'installazione di PHP (ammesso che si abbia già qualche web server funzionante). Se si hanno problemi con l'installazione di PHP, suggeriamo di porre della domande alla nostra » mailing list dell'installazione. Se si sceglie di andare sulla strada più semplice, quindi » individuare un pacchetto pre-configurato per il sistema operativo, che installa automaticamente tutti questi elementi con pochi click. È facile configurare su qualsiasi sistema operativo, incluso MaxOSX, Linux e Windows, un server web con il supporto a PHP. Su Linux, è possibile trovare » rpmfind e » PBone utili per localizzare gli RPM. Potresti voler visitare anche » apt-get per trovare pacchetti per Debian.



La prima pagina PHP

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

Example #1 Il nostro primo script PHP: ciao.php

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

Usa il tuo browser per accedere al file con il tuo URL del web server, finendo con il collegamento al file /ciao.php. Quando si sviluppa localmente questo URL sarà simile a http://localhost/ciao.php o http://127.0.0.1/ciao.php ma questo dipende dalla configurazione del web server. Se tutto è configurato correttamente, questo file verrà analizzato da PHP e il seguente output sarà inviato al vostro browser:

<html>
 <head>
  <title>Test PHP</title>
 </head>
 <body>
 <p>Hello World</p>
 </body>
</html>

Questo programma è molto semplice e sicuramente non era necessario fare ricorso a PHP per creare una pagina come quella. Tutto ciò che essa fa è visualizzare: Hello World! usando l'istruzione echo di PHP. Nota che il file non ha bisogno di essere eseguibile o speciale in alcun modo. Il server viene a sapere che questo file deve essere interpretato da PHP perché si è utilizzata l'estensione ".php", per la quale il server è configurato per passarlo a PHP. 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.

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 o non è configurato opportunamente. Provare a chiedere al proprio amministratore di abilitarlo per voi usando il capitolo del manuale dedicato all'Installazione. Se si vogliono sviluppare in locale script PHP, leggere anche il capitolo sull'installazione per assicurarsi che tutto sia configurato correttamente. Assicurarsi che si accede al file via http con il server che fornisce l'output. Se si richiama il file semplicemente dal proprio file system, allora non sarà analizzato da PHP. Se i problemi persistono comunque, non esitare a utilizzare una delle tante opzioni del» supporto PHP.

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 l'istruzione PHP e abbiamo lasciato la modalità PHP usando il tag di chiusura, ?>. All'interno di un file HTML come questo si può entrare ed uscire dalla modalità PHP quante volte si desidera. Per ulteriori dettagli, leggere la sezione del manuale su sintassi di base di PHP.

Nota: Nota riguardo i Line Feed

I Line feed hanno poco significato in HTML, rimangono comunque una buona idea per rendere l'aspetto dell'HTML bello e pulito inserendo le line feeds al suo interno. Una linefeed che segue immediatamente dopo una chiusura ?> sarà rimossa da PHP. Questo può essere estremamente utile quando si inseriscono molti blocchi PHP o si includono file contenenti PHP che non dovrebbero avere dell'output. Allo stesso tempo può esserci un po' di confusione. È possibile inserire uno spazio dopo la chiusura ?> per forzare uno spazio e un line feed da stampare, o puoi inserire un line feed esplicito nell'ultimo echo/print dall'interno del blocco PHP.

Nota: 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: » Lista degli Editor PHP. Se si desidera suggerire un nuovo programma, visitare la pagina sopra e chiedere al curatore di aggiungerlo alla lista. Avere un editor con evidenziazione della sintassi può essere utile.

Nota: 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 volessero utilizzare comunque per questo script d'esempio, ci si deve assicurare che il file venga salvato come testo o PHP non sarà in grado di leggere ed eseguire lo script.

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

Ora che si è creato con successo uno script funzionante in PHP, è il momento di creare il più famoso script PHP! Effettuare una chiamata alla funzione phpinfo() e si vedranno un sacco di informazioni utili sul proprio sistema e configurazioni come le variabili predefinite disponibili, i moduli PHP caricati, e le impostazioni della configurazione. Prendere un po' di tempo e rivedere queste importanti informazioni.

Example #2 Ricevere informazioni sul sistema da PHP

<?php phpinfo(); ?>



Qualcosa di utile

Andiamo a fare qualcosa di leggermente più utile. Andremo a controllare che tipo di browser sta utilizzando la persona che visita le nostre pagine. Per fare questo si andrà a controllare la stringa dell'user agent che il browser invia come parte della richiesta HTTP. Quest'informazione viene inviata in una variabile. Le Variabili iniziano sempre con il simbolo del dollaro in PHP. La variabile alla quale ci riferiamo adesso è $_SERVER["HTTP_USER_AGENT"].

Nota:

$_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 è stato introdotto nella versione » 4.1.0 di PHP. Nelle versioni precedenti abbiamo utilizzato gli ormai vecchi array $HTTP_*_VARS, come $HTTP_SERVER_VARS. Anche se deprecate, queste variabili continuano ad esistere. (Potete guardare nelle note del vecchio codice.)

Per visualizzare questa variabile, dobbiamo semplicemente:

Example #1 Stampare a video una variable (un elemento d'Array)

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

L'output (risultato) di questo script potrebbe essere:


Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)

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 cercando nell'output della funzione phpinfo() utilizzata nell'esempio della precedente sezione.

Si possono inserire istruzioni PHP multiple all'interno di un tag PHP e creare piccoli blocchi di codice che fanno più di un singolo echo. Per esempio, se si volesse controllare se l'utente usa Internet Explorer si potrebbe fare questo:

Example #2 Esempi usando le strutture di controllo e le funzioni

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
 echo 
'Stai usando Internet Explorer<br />';
}
?>

L'output di esempio di questo script potrebbe essere:

Stai usando Internet Explorer<br />

Qui introduciamo un paio di nuovi concetti. Abbiamo l'istruzione if (se). Se avete una conoscenza con la sintassi di base usata dal linguaggio C, questo dovrebbe sembrare logico per voi. In caso contrario, dovreste probabilmente prendere qualsiasi libro introduttivo di PHP e leggere i primi capitoli, o leggere la parte del manuale relativa ai Riferimenti del Linguaggio.

Il secondo concetto che abbiamo introdotto era la chiamata alla funzione strpos(). Questa è una funzione sviluppata in PHP che cerca una stringa all'interno di un'altra stringa. In questo caso abbiamo cercato 'MSIE' (cosiddetta occorrenza) all'interno della stringa $_SERVER["HTTP_USER_AGENT"] (cosiddetta haystack). Se la stringa viene trovata all'interno dell'haystack, la funzione restituisce la posizione dell'occorrenza relativa all'inizio dell'haystack. Altrimenti, restituisce FALSE. Se non restituisce FALSE, l'espressione if viene valutata come TRUE ed il codice all'interno dei relativi {braces} (sostegni) sarà eseguito. Altrimenti, il codice non sarà eseguito. 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. Se non sei sicuro di come utilizzare queste funzioni, vorrai leggere le pagine del manuale su come leggere una definizione di funzione e la sezione sulle funzioni PHP.

Possiamo fare un passo avanti e mostrarvi come potete entrare ed uscite dal modo PHP anche dall' interno di un blocco PHP:

Example #3 Intercalare i modi PHP e HTML

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
?>
<h3>strpos() dovrebbe ritornare non-false</h3>
<b>Stai usando Internet Explorer</b>
<?php
} else {
?>
<h3>strpos() dovrebbe ritornare false</h3>
<b>Non stai usando Internet Explorer</b>
<?php
}
?>

L'output di esempio di questo script potrebbe essere:

<h3>strpos() dovrebbe ritornare non-false</h3>
<b>Stai usando Internet Explorer</b>

Invece di usare la dichiarazione echo per fare l'output di qualcosa, saltiamo fuori dalla modalità PHP inviando soltanto HTML puro. Il punto importante da notare qui è che il flusso logico dello script rimane intatto. Solo uno dei blocchi di HTML finirà per essere inviato come risposta, dipendendo dal risultato di strpos(). In altre parole, dipende se la stringa MSIE viene trovata o meno.



Trattare con i Form

Una delle caratteritiche più forti di PHP è il modo in cui gestisce i form. Il concetto da comprendere principalmente è che qualsiasi elemento di un form sarà automaticamente disponibile per i vostri script PHP. Per maggiori informazioni ed esempi relativi all'utilizzo dei form consultate la sezione del manuale che si riferisce a le Variabili da sorgenti esterne. A seguire un esempio di un form HTML:

Example #1 Un semplice form HTML

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

Questo form non ha niente di speciale. È un semplice form in HTML che non presenta nessun tipo di tags particolari. Quando l'utente riempie questo form e preme il pulsante submit, viene richiamata la pagina action.php. In questo file il risultato sarà qualcosa di simile:

Example #2 La stampa video di dati dal nostro form

Ciao <?php echo htmlspecialchars($_POST['name']); ?>.
La tua età è di <?php echo (int)$_POST['age']; ?> anni.

Ecco un possibile output di questo script:

Ciao Joe. La tua età è di 22 anni.

A parte le parti relative a htmlspecialchars() e (int), ciò che avviene dovrebbe risultare ovvio. htmlspecialchars() si assicura che qualsiasi carattere speciale in HTML sia propriamente codificato in modo che la gente non possa iniettare tag HTML o Javascript nella vostra pagina. Per il campo age, in quanto sappiamo che è un numero, possiamo semplicemente convertirlo in un integer il quale si sbarazzerà automaticamente di qualsiasi carattere strano. Puoi anche fare questo automaticamente con PHP utilizzando l'estensione filter. 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 autoglobale $_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().

Si può anche trattare con gli input XForms input in PHP, anche se vi troverete a vostro agio con i form HTML ben supportati per parecchio tempo. Nonostante lavorare con XForms non sia per principianti, si potrebbe essere interessati a loro. Abbiamo anche una breve introduzione per gestire i dati ricevuti da XForms nella nostra sezione features.



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

Da quando il PHP è divenuto un linguaggio di scripting popolare, esistono più fonti che producono listati di codice che si possono adoperare nei propri scripts. La maggioranza degli sviluppatori del PHP ha cercato di renderlo compatibile con le versioni precedenti, perciò uno script creato per una vecchia versione del PHP dovrebbe girare senza modifiche (in teoria) in una più recente. 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). In PHP » 4.1.0 furono introdotti i seguenti autoglobal arrays: Essi sono: $_GET, $_POST, $_COOKIE, $_SERVER, $_FILES, $_ENV, $_REQUEST, e $_SESSION. Anche i vecchi arrays $HTTP_*_VARS, quali $HTTP_POST_VARS, esistono. Dal PHP 5.0.0, gli array di variabili predefinite possono essere disabilitati con il parametro register_long_arrays .
  • 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 array autoglobali suddetti. Scripts, libri e tutorials più vecchi possono contare su questa direttiva su on. Se essa è on, per esempio, qualcuno potrebbe usare $id dall'URL http://www.example.com/foo.php?id=42. La variabile, $_GET['id'] sarebbe disponibile indifferentemente del fatto che sia on od off.
Per ulteriori dettagli su queste modifiche, vedere la sezione sulle variabili predefinite ed i links ad essa connessi.



E poi?

Con quello che sapete ora dovreste essere in grado di comprendere la maggior parte del manuale ed anche i vari scripts di esempio reperibili nelle raccolte di esempi. Inoltre potete trovarne altri sui siti web di php.net nella sezione links: » http://www.php.net/links.php.

Per vedere varie slide delle presentazioni che mostrano di più ciò che PHP può fare, consultare il Sito del Materiale della Conferenza di PHP: » http://talks.php.net/





Installazione e configurazione


General Installation Considerations

Before starting the installation, first you need to know what do you want to use PHP for. There are three main fields you can use PHP, as described in the What can PHP do? section:

  • Websites and web applications (server-side scripting)
  • Command line scripting
  • Desktop (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.

In case of 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.



Installation on Unix systems

Indice dei contenuti

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 web server. 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
  • A web server
  • Any module specific components (such as GD, PDF libs, etc.)

When building directly from Git sources or after custom modifications you might also need:

  • autoconf: 2.13+ (for PHP < 5.4.0), 2.59+ (for PHP >= 5.4.0)
  • automake: 1.4+
  • libtool: 1.4.x+ (except 1.4.2)
  • re2c: Version 0.13.4 or newer
  • flex: Version 2.5.4 (for PHP <= 5.2)
  • bison: Version 1.28 (preferred), 1.35, or 1.75

The initial PHP setup and configuration process is controlled by the use of the command line options of the configure script. You could get a list of all available options along with short explanations running ./configure --help. Our manual documents the different options separately. You will find the core options in the appendix, while the different extension specific options are descibed on the reference pages.

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


Apache 1.3.x on Unix systems

This section contains notes and hints specific to Apache installs of PHP on Unix platforms. We also have instructions and notes for Apache 2 on a separate page.

You can select arguments to add to the configure on line 10 below from the list of core configure options and from extension specific options described at the respective places in the manual. The version numbers have been omitted here, to ensure the instructions are not incorrect. You will need to replace the 'xxx' here with the correct values from your files.

Example #1 Installation Instructions (Apache Shared Module Version) for PHP

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

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

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

11. make
12. make install

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

13. Setup your php.ini file:

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

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

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

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

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

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

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

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

Alternatively, to install PHP as a static object:

Example #2 Installation Instructions (Static Module Installation for Apache) for PHP

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

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

10. cd ../apache_1.3.x

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

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

13. cd ../php-5.x.y
14. cp php.ini-development /usr/local/lib/php.ini

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

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.

Example #3 Example commands for restarting Apache

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

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

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

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

The locations of the apachectl and http(s)dctl binaries often vary. If your system has locate or whereis or which commands, these can assist you in finding your server control programs.

Different examples of compiling PHP for apache are as follows:

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

This will create a libphp5.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 library.

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

This will create a libphp5.so shared library for Apache, but it will also create a pgsql.so shared library that is loaded into PHP either by using the extension directive in php.ini file or by loading it explicitly in a script using the dl() function.

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

This will create a libmodphp5.a library, a mod_php5.c and some accompanying files and copy this into the src/modules/php5 directory in the Apache source tree. Then you compile Apache using --activate-module=src/modules/php5/libphp5.a and the Apache build system will create libphp5.a and link it statically into the httpd binary. The PostgreSQL support is included directly into this httpd binary, so the final result here is a single httpd binary that includes all of Apache and all of PHP.

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

Same as before, except instead of including PostgreSQL support directly into the final httpd you will get a pgsql.so shared library that you can load into PHP from either the php.ini file or directly using dl().

When choosing to build PHP in different ways, you should consider the advantages and drawbacks of each method. Building as a shared object will mean that you can compile apache separately, and don't have to recompile everything as you add to, or change, PHP. Building PHP into apache (static method) means that PHP will load and run faster. For more information, see the Apache » web page on DSO support.

Nota:

Apache's default httpd.conf currently ships with a section that looks like this:

User nobody
Group "#-1"
Unless you change that to "Group nogroup" or something like that ("Group daemon" is also very common) PHP will not be able to open files.

Nota:

Make sure you specify the installed version of apxs when using --with-apxs=/path/to/apxs . You must NOT use the apxs version that is in the apache sources but the one that is actually installed on your system.



Apache 2.x on Unix systems

This section contains notes and hints specific to Apache 2.x installs of PHP on Unix systems.

Avviso

L'utilizzo di un threaded MPM non è raccomandato in produzione con Apache 2. Usare il prefork MPM, che è il MPM di default su Apache 2.0 e 2.2. Per informazioni, leggere la voce correlata delle FAQ sull'uso di Apache2 con un threaded MPM

The » Apache Documentation is the most authoritative source of information on the Apache 2.x server. More information about installation options for Apache may be found there.

The most recent version of Apache HTTP Server may be obtained from » Apache download site, and a fitting PHP version from the above mentioned places. This quick guide covers only the basics to get started with Apache 2.x and PHP. For more information read the » Apache Documentation. The version numbers have been omitted here, to ensure the instructions are not incorrect. In the examples below, 'NN' should be replaced with the specific version of Apache being used.

There are currently two versions of Apache 2.x - there's 2.0 and 2.2. While there are various reasons for choosing each, 2.2 is the current latest version, and the one that is recommended, if that option is available to you. However, the instructions here will work for either 2.0 or 2.2.

  1. Obtain the Apache HTTP server from the location listed above, and unpack it:

    gzip -d httpd-2_x_NN.tar.gz
    tar -xf httpd-2_x_NN.tar
    
  2. Likewise, obtain and unpack the PHP source:

    gunzip php-NN.tar.gz
    tar -xf php-NN.tar
    
  3. Build and install Apache. Consult the Apache install documentation for more details on building Apache.

    cd httpd-2_x_NN
    ./configure --enable-so
    make
    make install
    
  4. Now you have Apache 2.x.NN available under /usr/local/apache2, configured with loadable module support and the standard MPM prefork. To test the installation use your normal procedure for starting the Apache server, e.g.:

    /usr/local/apache2/bin/apachectl start
    
    and stop the server to go on with the configuration for PHP:
    /usr/local/apache2/bin/apachectl stop
    

  5. Now, configure and build PHP. This is where you customize PHP with various options, like which extensions will be enabled. Run ./configure --help for a list of available options. In our example we'll do a simple configure with Apache 2 and MySQL support.

    If you built Apache from source, as described above, the below example will match your path for apxs, but if you installed Apache some other way, you'll need to adjust the path to apxs accordingly. Note that some distros may rename apxs to apxs2.

    cd ../php-NN
    ./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql
    make
    make install
    

    If you decide to change your configure options after installation, you'll need to re-run the configure, make, and make install steps. You only need to restart apache for the new module to take effect. A recompile of Apache is not needed.

    Note that unless told otherwise, 'make install' will also install PEAR, various PHP tools such as phpize, install the PHP CLI, and more.

  6. Setup your php.ini

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

    You may edit your .ini file to set PHP options. If you prefer having php.ini in another location, use --with-config-file-path=/some/path in step 5.

    If you instead choose php.ini-production, be certain to read the list of changes within, as they affect how PHP behaves.

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

    LoadModule php5_module modules/libphp5.so
  8. Tell Apache to parse certain extensions as PHP. For example, let's have Apache parse .php files as PHP. Instead of only using the Apache AddType directive, we want to avoid potentially dangerous uploads and created files such as exploit.php.jpg from being executed as PHP. Using this example, you could have any extension(s) parse as PHP by simply adding them. We'll add .php to demonstrate.

    <FilesMatch \.php$>
        SetHandler application/x-httpd-php
    </FilesMatch>

    Or, if we wanted to allow .php, .php2, .php3, .php4, .php5, .php6, and .phtml files to be executed as PHP, but nothing else, we'd use this:

    <FilesMatch "\.ph(p[2-6]?|tml)$">
        SetHandler application/x-httpd-php
    </FilesMatch>

    And to allow .phps files to be handled by the php source filter, and displayed as syntax-highlighted source code, use this:

    <FilesMatch "\.phps$">
        SetHandler application/x-httpd-php-source
    </FilesMatch>

    mod_rewrite may be used To allow any arbitrary .php file to be displayed as syntax-highlighted source code, without having to rename or copy it to a .phps file:

    RewriteEngine On
    RewriteRule (.*\.php)s$ $1 [H=application/x-httpd-php-source]

    The php source filter should not be enabled on production systems, where it may expose confidential or otherwise sensitive information embedded in source code.

  9. Use your normal procedure for starting the Apache server, e.g.:

    /usr/local/apache2/bin/apachectl start
    

    OR

    service httpd restart
    

Following the steps above you will have a running Apache2 web server with support for PHP as a SAPI module. Of course there are many more configuration options available Apache and PHP. For more information type ./configure --help in the corresponding source tree.

Apache may be built multithreaded by selecting the worker MPM, rather than the standard prefork MPM, when Apache is built. This is done by adding the following option to the argument passed to ./configure, in step 3 above:


--with-mpm=worker

This should not be undertaken without being aware of the consequences of this decision, and having at least a fair understanding of the implications. The Apache documentation regarding » MPM-Modules discusses MPMs in a great deal more detail.

Nota:

The Apache MultiViews FAQ discusses using multiviews with PHP.

Nota:

To build a multithreaded version of Apache, the target system must support threads. In this case, PHP should also be built with experimental Zend Thread Safety (ZTS). Under this configuration, not all extensions will be available. The recommended setup is to build Apache with the default prefork MPM-Module.



Nginx 1.4.x on Unix systems

This documentation will cover installing and configuring PHP with PHP-FPM for a Nginx 1.4.x HTTP server.

This guide will assume that you have built Nginx from source and therefore all binaries and configuration files are located at /usr/local/nginx. If this is not the case and you have obtained Nginx through other means then please refer to the » Nginx Wiki in order translate this manual to your setup.

This guide will cover the basics of configuring an Nginx server to process PHP applications and serve them on port 80, it is recommended that you study the Nginx and PHP-FPM documentation if you wish to optimise your setup past the scope of this documentation.

Please note that throughout this documentation version numbers have been replaced with an 'x' to ensure this documentation stays correct in the future, please replace these as necessary with the corresponding version numbers.

  1. It is recomended that you visit the Nginx Wiki » install page in order to obtain and install Nginx on your system.

  2. Obtain and unpack the PHP source:

    tar zxf php-x.x.x
    
  3. Configure and build PHP. This is where you customize PHP with various options, like which extensions will be enabled. Run ./configure --help for a list of available options. In our example we'll do a simple configure with PHP-FPM and MySQL support.

    cd ../php-x.x.x
    ./configure --enable-fpm --with-mysql
    make
    sudo make install
    
  4. Obtain and move configuration files to their correct locations

    cp php.ini-development /usr/local/php/php.ini
    cp /usr/local/etc/php-fpm.conf.default /usr/local/etc/php-fpm.conf
    cp sapi/fpm/php-fpm /usr/local/bin
    
  5. It is important that we prevent Nginx from passing requests to the PHP-FPM backend if the file does not exists, allowing us to prevent arbitrarily script injection.

    We can fix this by setting the cgi.fix_pathinfo directive to 0 within our php.ini file.

    Load up php.ini:

    vim /usr/local/php/php.ini
    

    Locate cgi.fix_pathinfo= and modify it as follows:

    cgi.fix_pathinfo=0
    
  6. php-fpm.conf must be modified to specify that php-fpm must run as the user www-data and the group www-data before we can start the service:

    vim /usr/local/etc/php-fpm.conf
    

    Find and modify the following:

    ; Unix user/group of processes
    ; Note: The user is mandatory. If the group is not set, the default user's group
    ;       will be used.
    user = www-data
    group = www-data
    

    The php-fpm service can now be started:

    /usr/local/bin/php-fpm
    

    This guide will not configure php-fpm any further, if you are interested in further configuring php-fpm then please consult the documentation.

  7. Nginx must now be configured to support the processing of PHP applications:

    vim /usr/local/nginx/conf/nginx.conf
    

    Modify the default location block to be aware it must attempt to serve .php files:

    location / {
        root   html;
        index  index.php index.html index.htm;
    }

    The next step is to ensure that .php files are passed to the PHP-FPM backend, blow the commented default PHP location block, enter the following:

    location ~* \.php$ {
        fastcgi_index   index.php;
        fastcgi_pass    127.0.0.1:9000;
        include         fastcgi_params;
        fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
        fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
    }

    Restart Nginx.

    sudo /usr/local/nginx/sbin/nginx -s stop
    sudo /usr/local/nginx/sbin/nginx
    
  8. Create a test file

    rm /usr/local/nginx/html/index.html
    echo "<?php phpinfo(); ?>" >> /usr/local/nginx/html/index.php
    

    Now navigate to http://localhost. The phpinfo() should now be shown.

Following the steps above you will have a running Nginx web server with support for PHP as a SAPI module. Of course there are many more configuration options available Apache and PHP. For more information type ./configure --help in the corresponding source tree.



Lighttpd 1.4 su sistemi Unix

Questa sezione contiene note e suggerimenti specifici per installazioni di PHP per Lighttpd 1.4 su sistemi Unix.

Si prega di utilizzare » Lighttpd trac per imparare come installare Lighttpd correttamente prima di continuare.

Fastcgi è il SAPI consigliato per connettersi a PHP e Lighttpd. Fastcgi è abilitato automagicamente in php-cgi in PHP 5.3, ma per versioni precedenti è necessario configurare PHP con --enable-fastcgi. Per avere conferma che PHP abbia fastcgi abilitato, php -v dovrebbe contenere PHP 5.2.5 (cgi-fcgi) Prima di PHP 5.2.3, fastcgi era abilitato sulla versione compilata di php (non esisteva alcun php-cgi).

Consentire a Lighttpd di generare processi php

Per configurare Lighttpd per la connessione con php e generare processi fastcgi, editare lighttpd.conf. Si consiglia di eseguire le connessioni ai processi fastcgi sul sistema locale tramite socket.

Example #1 Estratto di lighttpd.conf

server.modules += ( "mod_fastcgi" )

fastcgi.server = ( ".php" =>
  ((
    "socket" => "/tmp/php.socket",
    "bin-path" => "/usr/local/bin/php-cgi",
    "bin-environment" => (
      "PHP_FCGI_CHILDREN" => "16",
      "PHP_FCGI_MAX_REQUESTS" => "10000"
    ),
    "min-procs" => 1,
    "max-procs" => 1,
    "idle-timeout" => 20
  ))
)

La direttiva bin-path consente a lighttpd di generare processi fastcgi dinamicamente. PHP genererà processi figli in accordo con la variabile di ambiente PHP_FCGI_CHILDREN. La direttiva "bin-environment" imposta l'ambiente per i processi generati. PHP terminerà i processi generati dopo che il numero di richieste specificato in PHP_FCGI_MAX_REQUESTS sia stato raggiunto. L'uso delle direttive "min-procs" e "max-procs" è sconsigliato relativamente a PHP. PHP gestisce autonomamente i propri processi figlio e la cache opcode come APC viene condivisa unicamente tra processi gestiti da PHP. Se "min-procs" è impostata ad un numero maggiore di 1, il numero totale di risponditori di php sarà moltiplicato per PHP_FCGI_CHILDREN (2 min-procs * 16 processi dà come risultato 32 risponditori).

Spawning with spawn-fcgi

Lighttpd fornisce un programma chiamato spawn-fcgi per facilitare la generazione di processi fastcgi.

Impiegare php-cgi

E' possibile generare processi senza spawn-fcgi, ma il procedimento è più complicato. L'impostazione della variabile di ambiente PHP_FCGI_CHILDREN controlla quanti processi figlio saranno generati da PHP per gestire le richieste ricevute. L'impostazione di PHP_FCGI_MAX_REQUESTS determinerà quanto a lungo (in termini di richieste) ogni processo figlio dovrà durare. Segue un semplice script bash per generare risponditori php.

Example #2 Generazione di risponditori FastCGI

#!/bin/sh

# Location of the php-cgi binary
PHP=/usr/local/bin/php-cgi

# PID File location
PHP_PID=/tmp/php.pid

# Binding to an address
#FCGI_BIND_ADDRESS=10.0.1.1:10000
# Binding to a domain socket
FCGI_BIND_ADDRESS=/tmp/php.sock

PHP_FCGI_CHILDREN=16
PHP_FCGI_MAX_REQUESTS=10000

env -i PHP_FCGI_CHILDREN=$PHP_FCGI_CHILDREN \
       PHP_FCGI_MAX_REQUESTS=$PHP_FCGI_MAX_REQUESTS \
       $PHP -b $FCGI_BIND_ADDRESS &

echo $! > "$PHP_PID"

Connessione a istanze di FCGI remote

Le istanze di Fastcgi possono essere generate su macchine remote multiple per consentire la scalabilità delle applicazioni.

Example #3 Connessione a istanze di php-fastcgi remote

fastcgi.server = ( ".php" =>
   (( "host" => "10.0.0.2", "port" => 1030 ),
    ( "host" => "10.0.0.3", "port" => 1030 ))
)


Sun, iPlanet and Netscape servers on Sun Solaris

This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Sun Solaris.

From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current web servers 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 web servers, enter the proper install directory for the --with-nsapi=[DIR] option. The default directory is usually /opt/netscape/suitespot/. Please also read /php-xxx-version/sapi/nsapi/nsapi-readme.txt.

  1. Install the following packages from »  http://www.sunfreeware.com/ or another download site:

    • autoconf-2.13
    • automake-1.4
    • bison-1_25-sol26-sparc-local
    • flex-2_5_4a-sol26-sparc-local
    • gcc-2_95_2-sol26-sparc-local
    • gzip-1.2.4-sol26-sparc-local
    • m4-1_4-sol26-sparc-local
    • make-3_76_1-sol26-sparc-local
    • mysql-3.23.24-beta (if you want mysql support)
    • perl-5_005_03-sol26-sparc-local
    • tar-1.13 (GNU tar)

  2. Make sure your path includes the proper directories PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/bin and make it available to your system export PATH.
  3. gunzip php-x.x.x.tar.gz (if you have a .gz dist, otherwise go to 4).
  4. tar xvf php-x.x.x.tar
  5. Change to your extracted PHP directory: cd ../php-x.x.x
  6. For the following step, make sure /opt/netscape/suitespot/ is where your netscape server is installed. Otherwise, change to the correct path and run:

    ./configure --with-mysql=/usr/local/mysql \
    --with-nsapi=/opt/netscape/suitespot/ \
    --enable-libgcc

  7. Run make followed by make install.

After performing the base install and reading the appropriate readme file, you may need to perform some additional configuration steps.

Configuration Instructions for Sun/iPlanet/Netscape

Firstly you may need to add some paths to the LD_LIBRARY_PATH environment for the server to find all the shared libs. This can best done in the start script for your web server. The start script is often located in: /path/to/server/https-servername/start. You may also need to edit the configuration files that are located in: /path/to/server/https-servername/config/.

  1. Add the following line to mime.types (you can do that by the administration server):

    type=magnus-internal/x-httpd-php exts=php
    

  2. Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following, shlib will vary depending on your system, it will be something like /opt/netscape/suitespot/bin/libphp4.so. You should place the following lines after mime types init.

    Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="/opt/netscape/suitespot/bin/libphp4.so"
    Init fn="php4_init" LateInit="yes" errorString="Failed to initialize PHP!" [php_ini="/path/to/php.ini"]
    
    (PHP >= 4.3.3) The php_ini parameter is optional but with it you can place your php.ini in your web server config directory.

  3. Configure the default object in obj.conf (for virtual server classes [version 6.0+] in their vserver.obj.conf):

    <Object name="default">
    .
    .
    .
    .#NOTE this next line should happen after all 'ObjectType' and before all 'AddLog' lines
    Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...]
    .
    .
    </Object>
    
    (PHP >= 4.3.3) As additional parameters you can add some special php.ini-values, for example you can set a docroot="/path/to/docroot" specific to the context php4_execute is called. For boolean ini-keys please use 0/1 as value, not "On","Off",... (this will not work correctly), e.g. zlib.output_compression=1 instead of zlib.output_compression="On"

  4. This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):

    <Object name="x-httpd-php">
    ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
    Service fn=php4_execute [inikey=value inikey=value ...]
    </Object>
    
    After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html.

  5. Setup of authentication: PHP authentication cannot be used with any other authentication. ALL AUTHENTICATION IS PASSED TO YOUR PHP SCRIPT. To configure PHP Authentication for the entire server, add the following line to your default object:

    <Object name="default">
    AuthTrans fn=php4_auth_trans
    .
    .
    .
    </Object>
    

  6. To use PHP Authentication on a single directory, add the following:

    <Object ppath="d:\path\to\authenticated\dir\*">
    AuthTrans fn=php4_auth_trans
    </Object>
    

Nota:

The stacksize that PHP uses depends on the configuration of the web server. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").

CGI environment and recommended modifications in php.ini

Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the web server 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 way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running web server without any valid CGI variables!

Nota:

Why are there (invalid) CGI variables in the environment?

Answer: This is because you started the web server process from the admin server which runs the startup script of the web server, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started web server has some CGI environment variables in it. You can test this by starting the web server not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.

Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):

variables_order = "GPCS"
register_globals = On

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

You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:

Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...]
where XXX is the HTTP error code. Please delete any other Error directives which could interfere with yours. If you want to place a page for all errors that could exist, leave the code parameter out. Your script can get the HTTP status code with $_SERVER['ERROR_TYPE'].

Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:

Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...]
For both error and directory listing pages the original URI and translated URI are in the variables $_SERVER['PATH_INFO'] and $_SERVER['PATH_TRANSLATED'].

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

The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the web server and insert the result in the web page. This function uses some undocumented features from the NSAPI library. On Unix the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.

Nota:

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



CGI and command line setups

By default, PHP is built as both a CLI and CGI program, which can be used for CGI processing. If you are running a web server that 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.

Avviso

Usando il setup del CGI, il server è aperto a parecchi attacchi. Leggere la sezione sulla sicurezza CGI per capire come difendersi da quest attacchi.

Testing

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

Using Variables

Some server supplied environment variables are not defined in the current » CGI/1.1 specification. Only the following variables are defined there: AUTH_TYPE, CONTENT_LENGTH, CONTENT_TYPE, GATEWAY_INTERFACE, PATH_INFO, PATH_TRANSLATED, QUERY_STRING, REMOTE_ADDR, REMOTE_HOST, REMOTE_IDENT, REMOTE_USER, REQUEST_METHOD, SCRIPT_NAME, SERVER_NAME, SERVER_PORT, SERVER_PROTOCOL, and SERVER_SOFTWARE. Everything else should be treated as 'vendor extensions'.



HP-UX specific installation notes

This section contains notes and hints specific to installing PHP on HP-UX systems.

There are two main options for installing PHP on HP-UX systems. Either compile it, or install a pre-compiled binary.

Official pre-compiled packages are located here: » http://software.hp.com/

Until this manual section is rewritten, the documentation about compiling PHP (and related extensions) on HP-UX systems has been removed. For now, consider reading the following external resource: » Building Apache and PHP on HP-UX 11.11



OpenBSD installation notes

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

Using Binary Packages

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

The main package you need to install is php4-core-4.3.8.tgz, which contains the basic engine (plus gettext and iconv). Next, take a look at the module packages, such as php4-mysql-4.3.8.tgz or php4-imap-4.3.8.tgz. You need to use the phpxs command to activate and deactivate these modules in your php.ini.

Example #1 OpenBSD Package Install Example

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

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

Using Ports

You can also compile up PHP from source using the » ports tree. However, this is only recommended for users familiar with OpenBSD. The PHP 4 port is split into two sub-directories: core and extensions. The extensions directory generates sub-packages for all of the supported PHP modules. If you find you do not want to create some of these modules, use the no_* FLAVOR. For example, to skip building the imap module, set the FLAVOR to no_imap.

Common Problems

  • The default install of Apache runs inside a » chroot(2) jail, which will restrict PHP scripts to accessing files under /var/www. You will therefore need to create a /var/www/tmp directory for PHP session files to be stored, or use an alternative session backend. In addition, database sockets need to be placed inside the jail or listen on the localhost interface. If you use network functions, some files from /etc such as /etc/resolv.conf and /etc/services will need to be moved into /var/www/etc. The OpenBSD PEAR package automatically installs into the correct chroot directories, so no special modification is needed there. More information on the OpenBSD Apache is available in the » OpenBSD FAQ.
  • The OpenBSD 3.6 package for the » gd extension requires XFree86 to be installed. If you do not wish to use some of the font features that require X11, install the php4-gd-4.3.8-no_x11.tgz package instead.

Older Releases

Older releases of OpenBSD used the FLAVORS system to compile up a statically linked PHP. Since it is hard to generate binary packages using this method, it is now deprecated. You can still use the old stable ports trees if you wish, but they are unsupported by the OpenBSD team. If you have any comments about this, the current maintainer for the port is Anil Madhavapeddy (avsm at openbsd dot org).



Solaris specific installation tips

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

Required software

Solaris installs often lack C compilers and their related tools. Read this FAQ for information on why using GNU versions for some of these tools is necessary.

For unpacking the PHP distribution you need

  • tar
  • gzip or
  • bzip2

For compiling PHP you need

  • gcc (recommended, other C compilers may work)
  • make
  • GNU sed

For building extra extensions or hacking the code of PHP you might also need

  • flex (up to PHP 5.2)
  • re2c
  • bison
  • m4
  • autoconf
  • automake
In addition, you will need to install (and possibly compile) any additional software specific to your configuration, such as Oracle or MySQL.

Using Packages

You can simplify the Solaris install process by using pkgadd to install most of your needed components. The Image Packaging System (IPS) for Solaris 11 Express also contains most of the required components for installation using the pkg command.



Debian GNU/Linux installation notes

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

Avviso

Unofficial builds from third-parties are not supported here. Any bugs should be reported to the Debian team unless they can be reproduced using the latest builds from our » download area.

While the instructions for building PHP on Unix apply to Debian as well, this manual page contains specific information for other options, such as using either the apt-get or aptitude commands. This manual page uses these two commands interchangeably.

Using APT

First, note that other related packages may be desired like libapache2-mod-php5 to integrate with Apache 2, and php-pear for PEAR.

Second, before installing a package, it's wise to ensure the package list is up to date. Typically, this is done by running the command apt-get update.

Example #1 Debian Install Example with Apache 2

# apt-get install php5-common libapache2-mod-php5 php5-cli

APT will automatically install the PHP 5 module for Apache 2 and all of its dependencies, and then activate it. Apache should be restarted in order for the changes take place. For example:

Example #2 Stopping and starting Apache once PHP is installed

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

Better control of configuration

In the last section, PHP was installed with only core modules. It's very likely that additional modules will be desired, such as MySQL, cURL, GD, etc. These may also be installed via the apt-get command.

Example #3 Methods for listing additional PHP 5 packages

# apt-cache search php5
# aptitude search php5
# aptitude search php5 |grep -i mysql

The examples will show a lot of packages including several PHP specific ones like php5-cgi, php5-cli and php5-dev. Determine which are needed and install them like any other with either apt-get or aptitude. And because Debian performs dependency checks, it'll prompt for those so for example to install MySQL and cURL:

Example #4 Install PHP with MySQL, cURL

# apt-get install php5-mysql php5-curl

APT will automatically add the appropriate lines to the different php.ini related files like /etc/php5/apache2/php.ini, /etc/php5/conf.d/pdo.ini, etc. and depending on the extension will add entries similar to extension=foo.so. However, restarting the web server (like Apache) is required before these changes take affect.

Common Problems

  • If the PHP scripts are not parsing via the web server, then it's likely that PHP was not added to the web server's configuration file, which on Debian may be /etc/apache2/apache2.conf or similar. See the Debian manual for further details.
  • If an extension was seemingly installed yet the functions are undefined, be sure that the appropriate ini file is being loaded and/or the web server was restarted after installation.
  • There are two basic commands for installing packages on Debian (and other linux variants): apt-get and aptitude. However, explaining the subtle differences between these commands goes beyond the scope of this manual.



Installation on Mac OS X

Indice dei contenuti

This section contains notes and hints specific to installing PHP on Mac OS X. PHP is bundled with Macs, and compiling is similar to the Unix installation guide.


Using Packages

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

The following resources offer easy to install packages and precompiled binaries for PHP on Mac OS:



Using the bundled PHP

PHP has come standard with Macs since OS X version 10.0.0. Enabling PHP with the default web server requires uncommenting a few lines in the Apache configuration file httpd.conf whereas the CGI and/or CLI are enabled by default (easily accessible via the Terminal program).

Enabling PHP using the instructions below is meant for quickly setting up a local development environment. It's highly recommended to always upgrade PHP to the newest version. Like most live software, newer versions are created to fix bugs and add features and PHP being is no different. See the appropriate MAC OS X installation documentation for further details. The following instructions are geared towards a beginner with details provided for getting a default setup to work. All users are encouraged to compile, or install a new packaged version.

The standard installation type is using mod_php, and enabling the bundled mod_php on Mac OS X for the Apache web server (the default web server, that is accessible via System Preferences) involves the following steps:

  1. Locate and open the Apache configuration file. By default, the location is as follows: /private/etc/apache2/httpd.conf Using Finder or Spotlight to find this file may prove difficult as by default it's private and owned by the root user.

    Nota: One way to open this is by using a Unix based text editor in the Terminal, for example nano, and because the file is owned by root we'll use the sudo command to open it (as root) so for example type the following into the Terminal Application (after, it will prompt for a password): sudo nano /private/etc/apache2/httpd.conf Noteworthy nano commands: ^w (search), ^o (save), and ^x (exit) where ^ represents the Ctrl key.

    Nota: Versions of Mac OS X prior to 10.5 were bundled with older versions of PHP and Apache. As such, the Apache configuration file on legacy machines may be /etc/httpd/httpd.conf.

  2. With a text editor, uncomment the lines (by removing the #) that look similar to the following (these two lines are often not together, locate them both in the file):

    # LoadModule php5_module libexec/httpd/libphp5.so
    
    # AddModule mod_php5.c
    
    Notice the location/path. When building PHP in the future, the above files should be replaced or commented out.

  3. Be sure the desired extensions will parse as PHP (examples: .php .html and .inc)

    Due to the following statement already existing in httpd.conf (as of Mac Panther), once PHP is enabled the .php files will automatically parse as PHP.

    <IfModule mod_php5.c>
        # If php is turned on, we respect .php and .phps files.
        AddType application/x-httpd-php .php
        AddType application/x-httpd-php-source .phps
    
        # Since most users will want index.php to work we
        # also automatically enable index.php
        <IfModule mod_dir.c>
            DirectoryIndex index.html index.php
        </IfModule>
    </IfModule>
    

    Nota:

    Before OS X 10.5 (Leopard), PHP 4 was bundled instead of PHP 5 in which case the above instructions will differ slightly by changing 5's to 4's.

  4. Be sure the DirectoryIndex loads the desired default index file This is also set in httpd.conf. Typically index.php and index.html are used. By default index.php is enabled because it's also in the PHP check shown above. Adjust accordingly.
  5. Set the php.ini location or use the default A typical default location on Mac OS X is /usr/local/php/php.ini and a call to phpinfo() will reveal this information. If a php.ini is not used, PHP will use all default values. See also the related FAQ on finding php.ini.
  6. Locate or set the DocumentRoot This is the root directory for all the web files. Files in this directory are served from the web server so the PHP files will parse as PHP before outputting them to the browser. A typical default path is /Library/WebServer/Documents but this can be set to anything in httpd.conf. Alternatively, the default DocumentRoot for individual users is /Users/yourusername/Sites
  7. Create a phpinfo() file

    The phpinfo() function will display information about PHP. Consider creating a file in the DocumentRoot with the following PHP code:

    <?php phpinfo(); ?>

  8. Restart Apache, and load the PHP file created above

    To restart, either execute sudo apachectl graceful in the shell or stop/start the "Personal Web Server" option in the OS X System Preferences. By default, loading local files in the browser will have an URL like so: http://localhost/info.php Or using the DocumentRoot in the user directory is another option and would end up looking like: http://localhost/~yourusername/info.php

The CLI (or CGI in older versions) is appropriately named php and likely exists as /usr/bin/php. Open up the terminal, read the command line section of the PHP manual, and execute php -v to check the PHP version of this PHP binary. A call to phpinfo() will also reveal this information.



Compiling PHP on Mac OS X

Use the Unix installation guide to compile PHP on Mac OS X.




Installation on Windows systems

Indice dei contenuti

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.

Nota:

Windows 98/Me/NT4 is no longer supported as of PHP 5.3.0.

Nota:

Windows 95 is no longer supported as of PHP 4.3.0.

If you have a development environment such as 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.


Manual Installation Steps

This section contains instructions for manually installing and configuring PHP on Microsoft Windows.

Selecting and downloading the PHP distribution package

Download the PHP zip binary distribution from » PHP for Windows: Binaries and Sources. There are several different versions of the zip package - choose the version that is suitable for the web server being used:

  • If PHP is used with IIS then choose PHP 5.3 VC9 Non Thread Safe or PHP 5.2 VC6 Non Thread Safe;

  • If PHP is used with IIS7 or greater and PHP 5.3+, then the VC9 binaries of PHP should be used.

  • If PHP is used with Apache 1 or Apache 2 then choose PHP 5.3 VC6 or PHP 5.2 VC6.

Nota:

VC9 Versions are compiled with the Visual Studio 2008 compiler and have improvements in performance and stability. The VC9 versions require you to have the » Microsoft 2008 C++ Runtime (x86) or the » Microsoft 2008 C++ Runtime (x64) installed.

The PHP package structure and content

Unpack the content of the zip archive into a directory of your choice, for example C:\PHP\. The directory and file structure extracted from the zip will look as below:

Example #1 PHP 5 package structure


c:\php
   |
   +--dev
   |  |
   |  |-php5ts.lib                 -- php5.lib in non thread safe version
   |
   +--ext                          -- extension DLLs for PHP
   |  |
   |  |-php_bz2.dll
   |  |
   |  |-php_cpdf.dll
   |  |
   |  |-...
   |
   +--extras                       -- empty 
   |
   +--pear                         -- initial copy of PEAR
   |
   |
   |-go-pear.bat                   -- PEAR setup script
   |
   |-...
   |
   |-php-cgi.exe                   -- CGI executable
   |
   |-php-win.exe                   -- executes scripts without an opened command prompt
   |
   |-php.exe                       -- Command line PHP executable (CLI)
   |
   |-...
   |
   |-php.ini-development           -- default php.ini settings
   |
   |-php.ini-production            -- recommended php.ini settings
   |
   |-php5apache2_2.dll             -- does not exist in non thread safe version
   |
   |-php5apache2_2_filter.dll      -- does not exist in non thread safe version
   |
   |-...
   |
   |-php5ts.dll                    -- core PHP DLL ( php5.dll in non thread safe version)
   | 
   |-...

Below is the list of the modules and executables included in the PHP zip distribution:

  • go-pear.bat - the PEAR setup script. Refer to » Installation (PEAR) for more details.

  • php-cgi.exe - CGI executable that can be used when running PHP on IIS via CGI or FastCGI.

  • php-win.exe - the PHP executable for executing PHP scripts without using a command line window (for example PHP applications that use Windows GUI).

  • php.exe - the PHP executable for executing PHP scripts within a command line interface (CLI).

  • php5apache2_2.dll - Apache 2.2.X module.

  • php5apache2_2_filter.dll - Apache 2.2.X filter.

Changing the php.ini file

After the php package content has been extracted, copy the php.ini-production into php.ini in the same folder. If necessary, it is also possible to place the php.ini into any other location of your choice but that will require additional configuration steps as described in PHP Configuration.

The php.ini file tells PHP how to configure itself, and how to work with the environment that it runs in. Here are a number of settings for the php.ini file that help PHP work better with Windows. Some of these are optional. There are many other directives that may be relevant to your environment - refer to the list of php.ini directives for more information.

Required directives:

  • extension_dir = <path to extension directory> - The extension_dir needs to point to the directory where PHP extensions files are stored. The path can be absolute (i.e. "C:\PHP\ext") or relative (i.e. ".\ext"). Extensions that are listed lower in the php.ini file need to be located in the extension_dir.

  • extension = xxxxx.dll - For each extension you wish to enable, you need a corresponding "extension=" directive that tells PHP which extensions in the extension_dir to load at startup time.

  • log_errors = On - PHP has an error logging facility that can be used to send errors to a file, or to a service (i.e. syslog) and works in conjunction with the error_log directive below. When running under IIS, the log_errors should be enabled, with a valid error_log.

  • error_log = <path to the error log file> - The error_log needs to specify the absolute, or relative path to the file where PHP errors should be logged. This file needs to be writable for the web server. The most common places for this file are in various TEMP directories, for example "C:\inetpub\temp\php-errors.log".

  • cgi.force_redirect = 0 - This directive is required for running under IIS. It is a directory security facility required by many other web servers. However, enabling it under IIS will cause the PHP engine to fail on Windows.

  • cgi.fix_pathinfo = 1 - This lets PHP access real path info following the CGI Spec. The IIS FastCGI implementation needs this set.

  • fastcgi.impersonate = 1 - FastCGI under IIS supports the ability to impersonate security tokens of the calling client. This allows IIS to define the security context that the request runs under.

  • fastcgi.logging = 0 - FastCGI logging should be disabled on IIS. If it is left enabled, then any messages of any class are treated by FastCGI as error conditions which will cause IIS to generate an HTTP 500 exception.

Optional directives

  • max_execution_time = ## - This directive tells PHP the maximum amount of time that it can spend executing any given script. The default for this is 30 seconds. Increase the value of this directive if PHP application take long time to execute.

  • memory_limit = ###M - The amount of memory available for the PHP process, in Megabytes. The default is 128, which is fine for most PHP applications. Some of the more complex ones might need more.

  • display_errors = Off - This directive tells PHP whether to include any error messages in the stream that it returns to the Web server. If this is set to "On", then PHP will send whichever classes of errors that you define with the error_reporting directive back to web server as part of the error stream. For security reasons it is recommended to set it to "Off" on production servers in order not to reveal any security sensitive information that is often included in the error messages.

  • open_basedir = <paths to directories, separated by semicolon>, e.g. openbasedir="C:\inetpub\wwwroot;C:\inetpub\temp". This directive specified the directory paths where PHP is allowed to perform file system operations. Any file operation outside of the specified paths will result in an error. This directive is especially useful for locking down the PHP installation in shared hosting environments to prevent PHP scripts from accessing any files outside of the web site's root directory.

  • upload_max_filesize = ###M and post_max_size = ###M - The maximum allowed size of an uploaded file and post data respectively. The values of these directives should be increased if PHP applications need to perform large uploads, such as for example photos or video files.

PHP is now setup on your system. The next step is to choose a web server, and enable it to run PHP. Choose a web server from the table of contents.

In addition to running PHP via a web server, PHP can run from the command line just like a .BAT script. See Command Line PHP on Microsoft Windows for further details.



Microsoft IIS

This section contains PHP installation instructions specific to Microsoft Internet Information Services (IIS).



Microsoft IIS 5.1 and IIS 6.0

This section contains instructions for manually setting up Internet Information Services (IIS) 5.1 and IIS 6.0 to work with PHP on Microsoft Windows XP and Windows Server 2003. For instructions on setting up IIS 7.0 and later versions on Windows Vista, Windows Server 2008, Windows 7 and Windows Server 2008 R2 refer to Microsoft IIS 7.0 and later.

Configuring IIS to process PHP requests

Download and install PHP in accordance to the instructions described in manual installation steps

Nota:

Non-thread-safe build of PHP is recommended when using IIS. The non-thread-safe builds are available at » PHP for Windows: Binaries and Sources Releases.

Configure the CGI- and FastCGI-specific settings in php.ini file as shown below:

Example #1 CGI and FastCGI settings in php.ini

fastcgi.impersonate = 1
fastcgi.logging = 0
cgi.fix_pathinfo=1
cgi.force_redirect = 0

Download and install the » Microsoft FastCGI Extension for IIS 5.1 and 6.0. The extension is available for 32-bit and 64-bit platforms - select the right download package for your platform.

Configure the FastCGI extension to handle PHP-specific requests by running the command shown below. Replace the value of the "-path" parameter with the absolute file path to the php-cgi.exe file.

Example #2 Configuring FastCGI extension to handle PHP requests

cscript %windir%\system32\inetsrv\fcgiconfig.js -add -section:"PHP" ^
-extension:php -path:"C:\PHP\php-cgi.exe"

This command will create an IIS script mapping for *.php file extension, which will result in all URLs that end with .php being handled by FastCGI extension. Also, it will configure FastCGI extension to use the executable php-cgi.exe to process the PHP requests.

Nota:

At this point the required installation and configuration steps are completed. The remaining instructions below are optional but highly recommended for achieving optimal functionality and performance of PHP on IIS.

Impersonation and file system access

It is recommended to enable FastCGI impersonation in PHP when using IIS. This is controlled by the fastcgi.impersonate directive in php.ini file. When impersonation is enabled, PHP will perform all the file system operations on behalf of the user account that has been determined by IIS authentication. This ensures that even if the same PHP process is shared across different IIS web sites, the PHP scripts in those web sites will not be able to access each others' files as long as different user accounts are used for IIS authentication on each web site.

For example IIS 5.1 and IIS 6.0, in its default configuration, has anonymous authentication enabled with built-in user account IUSR_<MACHINE_NAME> used as a default identity. This means that in order for IIS to execute PHP scripts, it is necessary to grant IUSR_<MACHINE_NAME> account read permission on those scripts. If PHP applications need to perform write operations on certain files or write files into some folders then IUSR_<MACHINE_NAME> account should have write permission to those.

To determine which user account is used by IIS anonymous authentication, follow these steps:

  1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";

  2. Expand the list of web sites under the "Web Sites" node in the tree view, right-click on a web site that is being used and select "Properties";

  3. Click the "Directory Security" tab;

  4. Take note of a "User name:" field in the "Authentication Methods" dialog

Anonymous authenication for IIS 5.1 and IIS 6.0

To modify the permissions settings on files and folders, use the Windows Explorer user interface or icacls command.

Example #3 Configuring file access permissions

icacls C:\inetpub\wwwroot\upload /grant IUSR:(OI)(CI)(M)

Set index.php as a default document in IIS

The IIS default documents are used for HTTP requests that do not specify a document name. With PHP applications, index.php usually acts as a default document. To add index.php to the list of IIS default documents, follow these steps:

  1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";

  2. Right-click on the "Web Sites" node in the tree view and select "Properties";

  3. Click the "Documents" tab;

  4. Click the "Add..." button and enter "index.php" for the "Default content page:".

Setting index.php as default document for IIS

FastCGI and PHP Recycling configuration

Configure IIS FastCGI extension settings for recycling of PHP processes by using the commands shown below. The FastCGI setting instanceMaxRequests controls how many requests will be processed by a single php-cgi.exe process before FastCGI extension shuts it down. The PHP environment variable PHP_FCGI_MAX_REQUESTS controls how many requests a single php-cgi.exe process will handle before it recycles itself. Make sure that the value specified for FastCGI InstanceMaxRequests setting is less than or equal to the value specified for PHP_FCGI_MAX_REQUESTS.

Example #4 Configuring FastCGI and PHP recycling

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-InstanceMaxRequests:10000

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-EnvironmentVars:PHP_FCGI_MAX_REQUESTS:10000

Configuring FastCGI timeout settings

Increase the timeout settings for FastCGI extension if there are applications that have long running PHP scripts. The two settings that control timeouts are ActivityTimeout and RequestTimeout. Refer to » Configuring FastCGI Extension for IIS 6.0 for more information about those settings.

Example #5 Configuring FastCGI timeout settings

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-ActivityTimeout:90

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-RequestTimeout:90

Changing the Location of php.ini file

PHP searches for php.ini file in several locations and it is possible to change the default locations of php.ini file by using PHPRC environment variable. To instruct PHP to load the configuration file from a custom location run the command shown below. The absolute path to the directory with php.ini file should be specified as a value of PHPRC environment variable.

Example #6 Changing the location of php.ini file

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-EnvironmentVars:PHPRC:"C:\Some\Directory\"



Microsoft IIS 7.0 and later

This section contains instructions for manually setting up Internet Information Services (IIS) 7.0 and later to work with PHP on Microsoft Windows Vista SP1, Windows 7, Windows Server 2008 and Windows Server 2008 R2. For instructions on setting up IIS 5.1 and IIS 6.0 on Windows XP and Windows Server 2003 refer to Microsoft IIS 5.1 and IIS 6.0.

Enabling FastCGI support in IIS

FastCGI module is disabled in default installation of IIS. The steps to enable it differ based on the version of Windows being used.

To enable FastCGI support on Windows Vista SP1 and Windows 7:

  1. In the Windows Start Menu choose "Run:", type "optionalfeatures.exe" and click "Ok";

  2. In the "Windows Features" dialog expand "Internet Information Services", "World Wide Web Services", "Application Development Features" and then enable the "CGI" checkbox;

  3. Click OK and wait until the installation is complete.

Enabling FastCGI support for IIS7 on Windows Vista SP1 and Windows 7

To enable FastCGI support on Windows Server 2008 and Windows Server 2008 R2:

  1. In the Windows Start Menu choose "Run:", type "CompMgmtLauncher" and click "Ok";

  2. If the "Web Server (IIS)" role is not present under the "Roles" node, then add it by clicking "Add Roles";

  3. If the "Web Server (IIS)" role is present, then click "Add Role Services" and then enable the "CGI" checkbox under "Application Development" group;

  4. Click "Next" and then "Install" and wait for the installation to complete.

Enabling FastCGI support on Windows Server 2008 and Windows Server 2008 R2

Configuring IIS to process PHP requests

Download and install PHP in accordance to the instructions described in manual installation steps

Nota:

Non-thread-safe build of PHP is recommended when using IIS. The non-thread-safe builds are available at » PHP for Windows: Binaries and Sources Releases.

Configure the CGI- and FastCGI-specific settings in php.ini file as shown below:

Example #1 CGI and FastCGI settings in php.ini

fastcgi.impersonate = 1
fastcgi.logging = 0
cgi.fix_pathinfo=1
cgi.force_redirect = 0

Configure IIS handler mapping for PHP by using either IIS Manager user interface or a command line tool.

Using IIS Manager user interface to create a handler mapping for PHP

Follow these steps to create an IIS handler mapping for PHP in IIS Manager user interface:

  1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";

  2. In the IIS Manager user interface select the server node in the "Connections" tree view;

  3. In the "Features View" page open the "Handler Mappings" feature;

    Create IIS handler mapping for PHP : Locate Handler Mappings

  4. In the "Actions" pane click "Add Module Mapping...";

  5. In the "Add Module Mapping" dialog enter the following:

    • Request path: *.php
    • Module: FastCgiModule
    • Executable: C:\[Path to PHP installation]\php-cgi.exe
    • Name: PHP_via_FastCGI

  6. Click "Request Restrictions" button and then configure the mapping to invoke handler only if request is mapped to a file or a folder;

  7. Click OK on all the dialogs to save the configuration.

Create IIS handler mapping for PHP : Add Handler Mapping

Using command line tool to create a handler mapping for PHP

Use the command shown below to create an IIS FastCGI process pool which will use php-cgi.exe executable for processing PHP requests. Replace the value of the fullPath parameter with the absolute file path to the php-cgi.exe file.

Example #2 Creating IIS FastCGI process pool

%windir%\system32\inetsrv\appcmd set config /section:system.webServer/fastCGI ^
/+[fullPath='c:\PHP\php-cgi.exe']

Configure IIS to handle PHP specific requests by running the command shown below. Replace the value of the scriptProcessor parameter with the absolute file path to the php-cgi.exe file.

Example #3 Creating handler mapping for PHP requests

%windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers ^
/+[name='PHP_via_FastCGI', path='*.php',verb='*',modules='FastCgiModule',^
scriptProcessor='c:\PHP\php-cgi.exe',resourceType='Either']

This command creates an IIS handler mapping for *.php file extension, which will result in all URLs that end with .php being handled by FastCGI module.

Nota:

At this point the required installation and configuration steps are completed. The remaining instructions below are optional but highly recommended for achieving optimal functionality and performance of PHP on IIS.

Impersonation and file system access

It is recommended to enable FastCGI impersonation in PHP when using IIS. This is controlled by the fastcgi.impersonate directive in php.ini file. When impersonation is enabled, PHP will perform all the file system operations on behalf of the user account that has been determined by IIS authentication. This ensures that even if the same PHP process is shared across different IIS web sites, the PHP scripts in those web sites will not be able to access each other's files as long as different user accounts are used for IIS authentication on each web site.

For example IIS 7, in its default configuration, has anonymous authentication enabled with built-in user account IUSR used as a default identity. This means that in order for IIS to execute PHP scripts, it is necessary to grant IUSR account read permission on those scripts. If PHP applications need to perform write operations on certain files or write files into some folders then IUSR account should have write permission to those.

To determine what user account is used as an anonymous identity in IIS 7 use the following command. Replace the "Default Web Site" with the name of IIS web site that you use. In the output XML configuration element look for the userName attribute.

Example #4 Determining the account used as IIS anonymous identity

%windir%\system32\inetsrv\appcmd.exe list config "Default Web Site" ^
/section:anonymousAuthentication

<system.webServer>
  <security>
    <authentication>
      <anonymousAuthentication enabled="true" userName="IUSR" />
    </authentication>
   </security>
</system.webServer>

Nota:

If userName attribute is not present in the anonymousAuthentication element, or is set to an empty string, then it means that the application pool identity is used as an anonymous identity for that web site.

To modify the permissions settings on files and folders, use the Windows Explorer user interface or icacls command.

Example #5 Configuring file access permissions

icacls C:\inetpub\wwwroot\upload /grant IUSR:(OI)(CI)(M)

Set index.php as a default document in IIS

The IIS default documents are used for HTTP requests that do not specify a document name. With PHP applications, index.php usually acts as a default document. To add index.php to the list of IIS default documents, use this command:

Example #6 Set index.php as a default document in IIS

%windir%\system32\inetsrv\appcmd.exe set config ^
-section:system.webServer/defaultDocument /+"files.[value='index.php']" ^
/commit:apphost

FastCGI and PHP Recycling configuration

Configure IIS FastCGI settings for recycling of PHP processes by using the commands shown below. The FastCGI setting instanceMaxRequests controls how many requests will be processed by a single php-cgi.exe process before IIS shuts it down. The PHP environment variable PHP_FCGI_MAX_REQUESTS controls how many requests a single php-cgi.exe process will handle before it recycles itself. Make sure that the value specified for FastCGI InstanceMaxRequests setting is less than or equal to the value specified for PHP_FCGI_MAX_REQUESTS.

Example #7 Configuring FastCGI and PHP recycling

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath='c:\php\php-cgi.exe'].instanceMaxRequests:10000

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/+"[fullPath='C:\{php_folder}\php-cgi.exe'].environmentVariables.^
[name='PHP_FCGI_MAX_REQUESTS',value='10000']"

FastCGI timeout settings

Increase the timeout settings for FastCGI if it is expected to have long running PHP scripts. The two settings that control timeouts are activityTimeout and requestTimeout. Use the commands below to change the timeout settings. Make sure to replace the value in the fullPath parameter to contain the absolute path to the php-cgi.exe file.

Example #8 Configuring FastCGI timeout settings

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath='C:\php\php-cgi.exe',arguments=''].activityTimeout:"90"  /commit:apphost

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath='C:\php\php-cgi.exe',arguments=''].requestTimeout:"90"  /commit:apphost

Changing the Location of php.ini file

PHP searches for php.ini file in several locations and it is possible to change the default locations of php.ini file by using PHPRC environment variable. To instruct PHP to load the configuration file from a custom location run the command shown below. The absolute path to the directory with php.ini file should be specified as a value of PHPRC environment variable.

Example #9 Changing the location of php.ini file

appcmd.exe set config  -section:system.webServer/fastCgi ^
/+"[fullPath='C:\php\php.exe',arguments=''].environmentVariables.^
[name='PHPRC',value='C:\Some\Directory\']" /commit:apphost



Apache 1.3.x on Microsoft Windows

This section contains notes and hints specific to Apache 1.3.x installs of PHP on Microsoft Windows systems. There are also instructions and notes for Apache 2 on a separate page.

Nota:

Please read the manual installation steps first!

There are two ways to set up PHP to work with Apache 1.3.x on Windows. One is to use the CGI binary (php.exe for PHP 4 and php-cgi.exe for PHP 5), the other is to use the Apache Module DLL. In either case you need to edit your httpd.conf to configure Apache to work with PHP, and then restart the server.

It is worth noting here that now the SAPI module has been made more stable under Windows, we recommend it's use above the CGI binary, since it is more transparent and secure.

Although there can be a few variations of configuring PHP under Apache, these are simple enough to be used by the newcomer. Please consult the Apache Documentation for further configuration directives.

After changing the configuration file, remember to restart the server, for example, NET STOP APACHE followed by NET START APACHE, if you run Apache as a Windows Service, or use your regular shortcuts.

Nota: Ricordare che quando si aggiungono valori di path nei file di configurazione Apache su Windows, tutti i backslash some c:\directory\file.ext devono essere convertiti in slash, come c:/directory/file.ext. Uno slash finale può essere necessario per le cartelle.

Installing as an Apache module

You should add the following lines to your Apache httpd.conf file:

Example #1 PHP as an Apache 1.3.x module

This assumes PHP is installed to c:\php. Adjust the path if this is not the case.

For PHP 4:

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

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

For PHP 5:

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

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

For both:

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

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

Installing as a CGI binary

If you unzipped the PHP package to C:\php\ as described in the Manual Installation Steps section, you need to insert these lines to your Apache configuration file to set up the CGI binary:

Example #2 PHP and Apache 1.3.x as CGI

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

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

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

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

Avviso

Usando il setup del CGI, il server è aperto a parecchi attacchi. Leggere la sezione sulla sicurezza CGI per capire come difendersi da quest attacchi.

If you would like to present PHP source files syntax highlighted, there is no such convenient option as with the module version of PHP. If you chose to configure Apache to use PHP as a CGI binary, you will need to use the highlight_file() function. To do this simply create a PHP script file and add this code: <?php highlight_file('some_php_script.php'); ?>.



Apache 2.x on Microsoft Windows

This section contains notes and hints specific to Apache 2.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!

Nota: Apache 2.2 Support

Users of Apache 2.2 should note that the DLL file for Apache 2.2 is named php5apache2_2.dll rather than php5apache2.dll and is available only for PHP 5.2.0 and later. See also » http://snaps.php.net/

You are strongly encouraged to consult the » Apache Documentation to get a basic understanding of the Apache 2.x Server. Also consider reading the » Windows specific notes for Apache 2.x before reading on here.

Apache 2.x is designed to run on the Windows version designated as server platforms, such as Windows NT 4.0, Windows 2000, Windows XP, or Windows 7. While Apache 2.x works tolerably well on Windows 9x, support on these platforms is incomplete, and some things will not work correctly. There is no plan to remedy this situation.

Download the most recent version of »  Apache 2.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 three ways to set up PHP to work with Apache 2.x on Windows. You can run PHP as a handler, as a CGI, or under FastCGI.

Nota: Ricordare che quando si aggiungono valori di path nei file di configurazione Apache su Windows, tutti i backslash some c:\directory\file.ext devono essere convertiti in slash, come c:/directory/file.ext. Uno slash finale può essere necessario per le cartelle.

Installing as an Apache handler

You need to insert the following lines into your Apache httpd.conf configuration file to load the PHP module for Apache 2.x:

Example #1 PHP and Apache 2.x as handler

# 
LoadModule php5_module "c:/php/php5apache2.dll"
AddHandler application/x-httpd-php .php

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

Nota: Remember to substitute your actual path to PHP for the C:/php/ in the above examples. Take care to use either php5apache2.dll or php5apache2_2.dll in your LoadModule directive and verify that the referenced file is in fact located at the file path that you point to in this directive.

The above configuration will enable PHP handling of any file that has a .php extension, even if there are other file extensions. For example, a file named example.php.txt will be executed by the PHP handler. To ensure that only files that end in .php are executed, use the following configuration instead:

<FilesMatch \.php$>
      SetHandler application/x-httpd-php
 </FilesMatch>

Running PHP as CGI

You should consult the » Apache CGI documentation for a more complete understanding of running CGI on Apache.

To run PHP as CGI, you'll need to place your php-cgi files in a directory designated as a CGI directory using the ScriptAlias directive.

You will then need to insert a #! line in the PHP files, pointing to the location of your PHP binary:

Example #2 PHP and Apache 2.x as CGI

#!C:/php/php.exe
<?php
  phpinfo();
?>

Avviso

Usando il setup del CGI, il server è aperto a parecchi attacchi. Leggere la sezione sulla sicurezza CGI per capire come difendersi da quest attacchi.

Running PHP under FastCGI

Running PHP under FastCGI has a number of advantages over running it as a CGI. Setting it up this way is fairly straightforward:

Obtain mod_fcgid from » http://httpd.apache.org/mod_fcgid/. Win32 binaries are available for download from that site. Install the module according to the instructions that will come with it.

Configure your web server as shown below, taking care to adjust any paths to reflect your how you have installed things on your particular system:

Example #3 Configure Apache to run PHP as FastCGI

LoadModule fcgid_module modules/mod_fcgid.so  

# Where is your php.ini file?
FcgidInitialEnv PHPRC        "c:/php" 

AddHandler fcgid-script .php  
FcgidWrapper "c:/php/php-cgi.exe" .php  
Files with a .php extension will now be executed by the PHP FastCGI wrapper.



Sun, iPlanet and Netscape servers on Microsoft Windows

This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Windows.

From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current web servers read the note about subrequests.

CGI setup on Sun, iPlanet and Netscape servers

To install PHP as a CGI handler, do the following:

  • Copy php4ts.dll to your systemroot (the directory where you installed Windows)
  • Make a file association from the command line. Type the following two lines:

    assoc .php=PHPScript
    ftype PHPScript=c:\php\php.exe %1 %*

  • In the Netscape Enterprise Administration Server create a dummy shellcgi directory and remove it just after (this step creates 5 important lines in obj.conf and allow the web server to handle shellcgi scripts).
  • In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/shellcgi, File Suffix:php).
  • Do it for each web server instance you want PHP to run

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

NSAPI setup on Sun, iPlanet and Netscape servers

To install PHP with NSAPI, do the following:

  • Copy php4ts.dll to your systemroot (the directory where you installed Windows)
  • Make a file association from the command line. Type the following two lines:

    assoc .php=PHPScript
    ftype PHPScript=c:\php\php.exe %1 %*

  • In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/x-httpd-php, File Suffix: php).
  • Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following: You should place the lines after mime types init.

    Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="c:/php/sapi/php4nsapi.dll"
    Init fn="php4_init" LateInit="yes" errorString="Failed to initialise PHP!" [php_ini="c:/path/to/php.ini"]
    
    (PHP >= 4.3.3) The php_ini parameter is optional but with it you can place your php.ini in your web server configuration directory.

  • Configure the default object in obj.conf (for virtual server classes [Sun Web Server 6.0+] in their vserver.obj.conf): In the <Object name="default"> section, place this line necessarily after all 'ObjectType' and before all 'AddLog' lines:

    Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...]
    
    (PHP >= 4.3.3) As additional parameters you can add some special php.ini-values, for example you can set a docroot="/path/to/docroot" specific to the context php4_execute is called. For boolean ini-keys please use 0/1 as value, not "On","Off",... (this will not work correctly), e.g. zlib.output_compression=1 instead of zlib.output_compression="On"

  • This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):

    <Object name="x-httpd-php">
    ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
    Service fn=php4_execute [inikey=value inikey=value ...]
    </Object>
    
    After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html.

  • Restart your web service and apply changes
  • Do it for each web server instance you want PHP to run

Nota:

More details about setting up PHP as an NSAPI filter can be found here: » http://benoit.noss.free.fr/php/install-php4.html

Nota:

The stacksize that PHP uses depends on the configuration of the web server. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").

CGI environment and recommended modifications in php.ini

Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the web server 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 way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running web server without any valid CGI variables!

Nota:

Why are there (invalid) CGI variables in the environment?

Answer: This is because you started the web server process from the admin server which runs the startup script of the web server, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started web server has some CGI environment variables in it. You can test this by starting the web server not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.

Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):

variables_order = "GPCS"
register_globals = On

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

You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:

Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...]
where XXX is the HTTP error code. Please delete any other Error directives which could interfere with yours. If you want to place a page for all errors that could exist, leave the code parameter out. Your script can get the HTTP status code with $_SERVER['ERROR_TYPE'].

Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:

Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...]
For both error and directory listing pages the original URI and translated URI are in the variables $_SERVER['PATH_INFO'] and $_SERVER['PATH_TRANSLATED'].

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

The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the web server and insert the result in the web page. The problem is, that this function uses some undocumented features from the NSAPI library.

Under Unix this is not a problem, because the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.

Under Windows limitations in the DLL handling need the use of a automatic detection of the most recent ns-httpdXX.dll file. This is tested for servers till version 6.1. If a newer version of the Sun server is used, the detection fails and nsapi_virtual() is disabled.

If this is the case, try the following: Add the following parameter to php4_init in magnus.conf/obj.conf:

Init fn=php4_init ... server_lib="ns-httpdXX.dll"
where XX is the correct DLL version number. To get it, look in the server-root for the correct DLL name. The DLL with the biggest filesize is the right one.

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

Nota:

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



Sambar Server on Microsoft Windows

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

Nota:

You should read the manual installation steps first!

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

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

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

    Example #1 ISAPI configuration of Sambar

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

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

Nota:

If you intend to use PHP to communicate with resources which are held on a different computer on your network, then you will need to alter the account used by the Sambar Server Service. The default account used for the Sambar Server Service is LocalSystem which will not have access to remote resources. The account can be amended by using the Services option from within the Windows Control Panel Administation Tools.



Xitami on Microsoft Windows

This section contains notes and hints specific to » Xitami on Windows.

Nota:

You should read the manual installation steps first!

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

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

Avviso

Usando il setup del CGI, il server è aperto a parecchi attacchi. Leggere la sezione sulla sicurezza CGI per capire come difendersi da quest attacchi.

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

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

  • In Filter command or script put the path and name of your PHP CGI executable i.e. C:\php\php.exe for PHP 4, or C:\php\php-cgi.exe for PHP 5.

  • Press the 'Save' icon.

  • Restart the server to reflect changes.



Building from source

This chapter teaches how to compile PHP from sources on windows, using Microsoft's tools. To compile PHP with cygwin, please refer to Installation on Unix systems.

See the Wiki documentation at: » http://wiki.php.net/internals/windows/stepbystepbuild



Installation of extensions on Windows

After installing PHP and a web server on Windows, you will probably want to install some extensions for added functionality. You can choose which extensions you would like to load when PHP starts by modifying your php.ini. You can also load a module dynamically in your script using dl().

The DLLs for PHP extensions are prefixed with php_.

Many extensions are built into the Windows version of PHP. This means additional DLL files, and the extension directive, are not used to load these extensions. The Windows PHP Extensions table lists extensions that require, or used to require, additional PHP DLL files. Here's a list of built in extensions:

In PHP 4 (updated PHP 4.3.11): BCMath, Caledar, COM, Ctype, FTP, MySQL, ODBC, Overload, PCRE, Session, Tokenizer, WDDX, XML e Zlib

In PHP 5 (updated PHP 5.0.4), the following changes exist. Built in: DOM, LibXML, Iconv, SimpleXML, SPL e SQLite. And the following are no longer built in: MySQL and Overload.

The default location PHP searches for extensions is C:\php4\extensions in PHP 4 and C:\php5 in PHP 5. To change this setting to reflect your setup of PHP edit your php.ini file:

  • You will need to change the extension_dir setting to point to the directory where your extensions lives, or where you have placed your php_*.dll files. For example:

    extension_dir = C:\php\extensions

  • Enable the extension(s) in php.ini you want to use by uncommenting the extension=php_*.dll lines in php.ini. This is done by deleting the leading ; from the extension you want to load.

    Example #1 Enable Bzip2 extension for PHP-Windows

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

  • Some of the extensions need extra DLLs to work. Couple of them can be found in the distribution package, in the C:\php\dlls\ folder in PHP 4 or in the main folder in PHP 5, but some, for example Oracle (php_oci8.dll) require DLLs which are not bundled with the distribution package. If you are installing PHP 4, copy the bundled DLLs from C:\php\dlls folder to the main C:\php folder. Don't forget to include C:\php in the system PATH (this process is explained in a separate FAQ entry).

  • Some of these DLLs are not bundled with the PHP distribution. See each extensions documentation page for details. Also, read the manual section titled Installation of PECL extensions for details on PECL. An increasingly large number of PHP extensions are found in PECL, and these extensions require a separate download.

Nota: If you are running a server module version of PHP remember to restart your web server to reflect your changes to php.ini.

The following table describes some of the extensions available and required additional dlls.

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_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_dba.dll DBA: DataBase (dbm-style) Abstraction layer functions None
php_dbase.dll dBase functions None
php_dbx.dll dbx functions  
php_domxml.dll PHP 4 domxml 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 functions Requires: Ingres 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_overload.dll PHP 4 Object overloading functions Built in since PHP 4.3.0, removed as of PHP 5.0.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



Command Line PHP on Microsoft Windows

This section contains notes and hints specific to getting PHP running from the command line for Windows.

Nota:

You should read the manual installation steps first!

Getting PHP to run from the command line can be performed without making any changes to Windows.

C:\PHP5\php.exe -f "C:\PHP Scripts\script.php" -- -arg1 -arg2 -arg3

But there are some easy steps that can be followed to make this simpler. Some of these steps should already have been taken, but are repeated here to be able to provide a complete step-by-step sequence.

    Nota:

    Both PATH and PATHEXT are important pre-existing system variables in Windows, and care should be taken to not overwrite either variable, only to add to them.

  • Append the location of the PHP executable (php.exe, php-win.exe or php-cli.exe depending upon your PHP version and display preferences) to the PATH environment variable. Read more about how to add your PHP directory to PATH in the corresponding FAQ entry.

  • Append the .PHP extension to the PATHEXT environment variable. This can be done at the same time as amending the PATH environment variable. Follow the same steps as described in the FAQ but amend the PATHEXT environment variable rather than the PATH environment variable.

    Nota:

    The position in which you place the .PHP will determine which script or program is executed when there are matching filenames. For example, placing .PHP before .BAT will cause your script to run, rather than the batch file, if there is a batch file with the same name.

  • Associate the .PHP extension with a file type. This is done by running the following command:

    assoc .php=phpfile
    

  • Associate the phpfile file type with the appropriate PHP executable. This is done by running the following command:

    ftype phpfile="C:\PHP5\php.exe" -f "%1" -- %~2
    

Following these steps will allow PHP scripts to be run from any directory without the need to type the PHP executable or the .PHP extension and all parameters will be supplied to the script for processing.

The example below details some of the registry changes that can be made manually.

Example #1 Registry changes

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.php]
@="phpfile"
"Content Type"="application/php"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile]
@="PHP Script"
"EditFlags"=dword:00000000
"BrowserFlags"=dword:00000008
"AlwaysShowExt"=""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\DefaultIcon]
@="C:\\PHP5\\php-win.exe,0"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell]
@="Open"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open]
@="&Open"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open\command]
@="\"C:\\PHP5\\php.exe\" -f \"%1\" -- %~2"

With these changes the same command can be written as:

"C:\PHP Scripts\script" -arg1 -arg2 -arg3
or, if your "C:\PHP Scripts" path is in the PATH environment variable:
script -arg1 -arg2 -arg3

Nota:

There is a small problem if you intend to use this technique and use your PHP scripts as a command line filter, like the example below:

dir | "C:\PHP Scripts\script" -arg1 -arg2 -arg3
or
dir | script -arg1 -arg2 -arg3
You may find that the script simply hangs and nothing is output. To get this operational, you need to make another registry change.
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer]
"InheritConsoleHandles"=dword:00000001
Further information regarding this issue can be found in this » Microsoft Knowledgebase Article : 321788.




L'installazione su Piattaforme di Cloud Computing

Indice dei contenuti

PHP viene installato sul cloud. Verso il cloud di PHP!


Microsoft Azure

PHP viene installato sulla » piattaforma cloud di Azure.

Leggere anche l'» SDK di Azure per PHP.



Amazon EC2

PHP viene installato sulla » piattaforma cloud EC2.

Leggere anche l'» SDK di AWS per PHP.




FastCGI Process Manager (FPM)

Indice dei contenuti

FPM (FastCGI Process Manager) is an alternative PHP FastCGI implementation with some additional features (mostly) useful for heavy-loaded sites.

These features include:

  • advanced process management with graceful stop/start;

  • ability to start workers with different uid/gid/chroot/environment, listening on different ports and using different php.ini (replaces safe_mode);

  • stdout and stderr logging;

  • emergency restart in case of accidental opcode cache destruction;

  • accelerated upload support;

  • "slowlog" - logging scripts (not just their names, but their PHP backtraces too, using ptrace and similar things to read remote process' execute_data) that are executed unusually slow;

  • fastcgi_finish_request() - special function to finish request and flush all data while continuing to do something time-consuming (video converting, stats processing etc.);

  • dynamic/static child spawning;

  • basic SAPI status info (similar to Apache mod_status);

  • php.ini-based config file.


Installation

Compiling from sources

In order to enable FPM in your PHP build you need to add --enable-fpm to your configure line.

There are several other FPM-specific configure options (all of them optional):

  • --with-fpm-user - set FPM user (default - nobody).

  • --with-fpm-group - set FPM group (default - nobody).



Configuration

FPM uses php.ini syntax for its configuration file - php-fpm.conf, and pool configuration files.

List of global php-fpm.conf directives

pid string

Path to PID file. Default value: none.

error_log string

Path to error log file. Default value: #INSTALL_PREFIX#/log/php-fpm.log.

log_level string

Error log level. Possible values: alert, error, warning, notice, debug. Default value: notice.

emergency_restart_threshold int

If this number of child processes exit with SIGSEGV or SIGBUS within the time interval set by emergency_restart_interval then FPM will restart. A value of 0 means 'Off'. Default value: 0 (Off).

emergency_restart_interval mixed

Interval of time used by emergency_restart_interval to determine when a graceful restart will be initiated. This can be useful to work around accidental corruptions in an accelerator's shared memory. Available Units: s(econds), m(inutes), h(ours), or d(ays). Default Unit: seconds. Default value: 0 (Off).

process_control_timeout mixed

Time limit for child processes to wait for a reaction on signals from master. Available units: s(econds), m(inutes), h(ours), or d(ays) Default Unit: seconds. Default value: 0.

daemonize boolean

Send FPM to background. Set to 'no' to keep FPM in foreground for debugging. Default value: yes.

List of pool directives

With FPM you can run several pools of processes with different setting. These are settings that can be tweaked per pool.

listen string

The address on which to accept FastCGI requests. Valid syntaxes are: 'ip.add.re.ss:port', 'port', '/path/to/unix/socket'. This option is mandatory for each pool.

listen.backlog int

Set listen(2) backlog. A value of '-1' means unlimited. Default value: -1.

listen.allowed_clients string

List of ipv4 addresses of FastCGI clients which are allowed to connect. Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original PHP FastCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address must be separated by a comma. If this value is left blank, connections will be accepted from any ip address. Default value: any.

listen.owner string

Set permissions for unix socket, if one is used. In Linux, read/write permissions must be set in order to allow connections from a web server. Many BSD-derived systems allow connections regardless of permissions. Default values: user and group are set as the running user, mode is set to 0666.

listen.group string

See listen.owner.

listen.mode string

See listen.owner.

user string

Unix user of FPM processes. This option is mandatory.

group string

Unix group of FPM processes. If not set, the default user's group is used.

pm string

Choose how the process manager will control the number of child processes. Possible values: static, ondemand, dynamic. This option is mandatory.

static - the number of child processes is fixed (pm.max_children).

ondemand - the processes spawn on demand (when requested, as opposed to dynamic, where pm.start_servers are started when the service is started.

dynamic - the number of child processes is set dynamically based on the following directives: pm.max_children, pm.start_servers, pm.min_spare_servers, pm.max_spare_servers.

pm.max_children int

The number of child processes to be created when pm is set to static and the maximum number of child processes to be created when pm is set to dynamic. This option is mandatory.

This option sets the limit on the number of simultaneous requests that will be served. Equivalent to the ApacheMaxClients directive with mpm_prefork and to the PHP_FCGI_CHILDREN environment variable in the original PHP FastCGI.

pm.start_servers int

The number of child processes created on startup. Used only when pm is set to dynamic. Default Value: min_spare_servers + (max_spare_servers - min_spare_servers) / 2.

pm.min_spare_servers int

The desired minimum number of idle server processes. Used only when pm is set to dynamic. Also mandatory in this case.

pm.max_spare_servers int

The desired maximum number of idle server processes. Used only when pm is set to dynamic. Also mandatory in this case.

pm.max_requests int

The number of requests each child process should execute before respawning. This can be useful to work around memory leaks in 3rd party libraries. For endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS. Default value: 0.

pm.status_path string

The URI to view the FPM status page. If this value is not set, no URI will be recognized as a status page. Default value: none.

ping.path string

The ping URI to call the monitoring page of FPM. If this value is not set, no URI will be recognized as a ping page. This could be used to test from outside that FPM is alive and responding. Please note that the value must start with a leading slash (/).

ping.response string

This directive may be used to customize the response to a ping request. The response is formatted as text/plain with a 200 response code. Default value: pong.

request_terminate_timeout mixed

The timeout for serving a single request after which the worker process will be killed. This option should be used when the 'max_execution_time' ini option does not stop script execution for some reason. A value of '0' means 'Off'. Available units: s(econds)(default), m(inutes), h(ours), or d(ays). Default value: 0.

request_slowlog_timeout mixed

The timeout for serving a single request after which a PHP backtrace will be dumped to the 'slowlog' file. A value of '0' means 'Off'. Available units: s(econds)(default), m(inutes), h(ours), or d(ays). Default value: 0.

slowlog string

The log file for slow requests. Default value: #INSTALL_PREFIX#/log/php-fpm.log.slow.

rlimit_files int

Set open file descriptor rlimit. Default value: system defined value.

rlimit_core int

Set max core size rlimit. Possible Values: 'unlimited' or an integer greater or equal to 0. Default value: system defined value.

chroot string

Chroot to this directory at the start. This value must be defined as an absolute path. When this value is not set, chroot is not used.

chdir string

Chdir to this directory at the start. This value must be an absolute path. Default value: current directory or / when chroot.

catch_workers_output boolean

Redirect worker stdout and stderr into main error log. If not set, stdout and stderr will be redirected to /dev/null according to FastCGI specs. Default value: no.

It's possible to pass additional environment variables and update PHP settings of a certain pool. To do this, you need to add the following options to the pool configuration file.

Example #1 Passing environment variables and PHP settings to a pool

env[HOSTNAME] = $HOSTNAME
env[PATH] = /usr/local/bin:/usr/bin:/bin
env[TMP] = /tmp
env[TMPDIR] = /tmp
env[TEMP] = /tmp

php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
php_flag[display_errors] = off
php_admin_value[error_log] = /var/log/fpm-php.www.log
php_admin_flag[log_errors] = on
php_admin_value[memory_limit] = 32M
PHP settings passed with php_value or php_flag will overwrite their previous value. Please note that defining disable_functions or disable_classes will not overwrite previously defined php.ini values, but will append the new value instead.

Settings defined with php_admin_value and php_admin_flag cannot be overriden with ini_set().

As of 5.3.3, PHP settings are also possible to be set in webserver.

Example #2 set PHP settings in nginx.conf

set $php_value "pcre.backtrack_limit=424242";
set $php_value "$php_value \n pcre.recursion_limit=99999";
fastcgi_param  PHP_VALUE $php_value;

fastcgi_param  PHP_ADMIN_VALUE "open_basedir=/var/www/htdocs";
Attenzione

Because these settings are passed to php-fpm as fastcgi headers, php-fpm should not be bound to a worldwide accessible address. Otherwise, anyone could alter the PHP configuration options. See also listen.allowed_clients.




Installation of PECL extensions

Indice dei contenuti


Introduction to PECL Installations

» PECL is a repository of PHP extensions that are made available to you via the » PEAR packaging system. This section of the manual is intended to demonstrate how to obtain and install PECL extensions.

These instructions assume /your/phpsrcdir/ is the path to the PHP source distribution, and that extname is the name of the PECL extension. Adjust accordingly. These instructions also assume a familiarity with the » pear command. The information in the PEAR manual for the pear command also applies to the pecl 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 the 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 Git Instructions for details on the required tools, and required versions.



Downloading PECL extensions

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

  • The pecl install extname command downloads the extensions code automatically, so in this case there is no need for a separate download.
  • » http://pecl.php.net/ The PECL web site contains information about the different extensions that are offered by the PHP Development Team. The information available here includes: ChangeLog, release notes, requirements and other similar details.
  • pecl download extname PECL extensions that have releases listed on the PECL web site are available for download and installation using the » pecl command. Specific revisions may also be specified.
  • SVN Most PECL extensions also reside in SVN. A web-based view may be seen at » http://svn.php.net/viewvc/pecl/. To download straight from SVN, the following sequence of commands may be used:


    $ svn checkout http://svn.php.net/repository/pecl/extname/trunk extname

  • Windows downloads At this time the PHP project does not compile Windows binaries for PECL extensions. However, to compile PHP under Windows see the chapter titled building PHP for Windows.


Installing a PHP extension on Windows

On Windows, you have two ways to load a PHP extension: either compile it into PHP, or load the DLL. Loading a pre-compiled extension is the easiest and preferred way.

To load an extension, you need to have it available as a ".dll" file on your system. All the extensions are automatically and periodically compiled by the PHP Group (see next section for the download).

To compile an extension into PHP, please refer to building from source documentation.

To compile a standalone extension (aka a DLL file), please refer to building from source documentation. If the DLL file is available neither with your PHP distribution nor in PECL, you may have to compile it before you can start using the extension.

Where to find an extension?

PHP extensions are usually called "php_*.dll" (where the star represents the name of the extension) and they are located under the "PHP\ext" ("PHP\extensions" in PHP 4) folder.

PHP ships with the extensions most useful to the majority of developers. They are called "core" extensions.

However, if you need functionality not provided by any core extension, you may still be able to find one in PECL. The PHP Extension Community Library (PECL) is a repository for PHP Extensions, providing a directory of all known extensions and hosting facilities for downloading and development of PHP extensions.

If you have developed an extension for your own uses, you might want to think about hosting it on PECL so that others with the same needs can benefit from your time. A nice side effect is that you give them a good chance to give you feedback, (hopefully) thanks, bug reports and even fixes/patches. Before you submit your extension for hosting on PECL, please read http://pecl.php.net/package-new.php.

Which extension to download?

Many times, you will find several versions of each DLL:

  • Different version numbers (at least the first two numbers should match)
  • Different thread safety settings
  • Different processor architecture (x86, x64, ...)
  • Different debugging settings
  • etc.

You should keep in mind that your extension settings should match all the settings of the PHP executable you are using. The following PHP script will tell you all about your PHP settings:

Example #1 phpinfo() call

<?php
phpinfo
();
?>

Or from the command line, run:

drive:\\path\to\php\executable\php.exe -i

Loading an extension

The most common way to load a PHP extension is to include it in your php.ini configuration file. Please note that many extensions are already present in your php.ini and that you only need to remove the semicolon to activate them.

;extension=php_extname.dll
extension=php_extname.dll

However, some web servers are confusing because they do not use the php.ini located alongside your PHP executable. To find out where your actual php.ini resides, look for its path in phpinfo():

Configuration File (php.ini) Path  C:\WINDOWS
Loaded Configuration File   C:\Program Files\PHP\5.2\php.ini

After activating an extension, save php.ini, restart the web server and check phpinfo() again. The new extension should now have its own section.

Resolving problems

If the extension does not appear in phpinfo(), you should check your logs to learn where the problem comes from.

If you are using PHP from the command line (CLI), the extension loading error can be read directly on screen.

If you are using PHP with a web server, the location and format of the logs vary depending on your software. Please read your web server documentation to locate the logs, as it does not have anything to do with PHP itself.

Common problems are the location of the DLL, the value of the " extension_dir" setting inside php.ini and compile-time setting mismatches.

If the problem lies in a compile-time setting mismatch, you probably didn't download the right DLL. Try downloading again the extension with the right settings. Again, phpinfo() can be of great help.



Compiling shared PECL extensions with the pecl command

PECL makes it easy to create shared PHP extensions. Using the » pecl command, do the following:


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


$ pecl install extname-beta

You may also install a specific version using this variant:


$ pecl install extname-0.1

Nota:

After enabling the extension in php.ini, restarting the web service is required for the changes to be picked up.



Compiling shared PECL extensions with phpize

Sometimes, using the pecl 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 PECL compatible package, such as unreleased extensions from SVN. 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.

If the system is missing the phpize command, and precompiled packages (like RPM's) are used, be sure to also install the appropriate devel version of the PHP package as they often include the phpize command along with the appropriate header files to build PHP and its extensions.

Execute phpize --help to display additional usage information.



php-config

php-config is a simple shell script for obtaining information about the installed PHP configuration.

When compiling extensions, if you have multiple PHP versions installed, you may specify for which installation you'd like to build by using the --with-php-config option during configuration, specifying the path of the respective php-config script.

The list of command line options provided by the php-config script can be queried anytime by running php-config with the -h switch:

Usage: /usr/local/bin/php-config [OPTION]
Options:
  --prefix            [...]
  --includes          [...]
  --ldflags           [...]
  --libs              [...]
  --extension-dir     [...]
  --include-dir       [...]
  --php-binary        [...]
  --php-sapis         [...]
  --configure-options [...]
  --version           [...]
  --vernum            [...]

Command line options
Option Description
--prefix Directory prefix where PHP is installed, e.g. /usr/local
--includes List of -I options with all include files
--ldflags LD Flags which PHP was compiled with
--libs Extra libraries which PHP was compiled with
--extension-dir Directory where extensions are searched by default
--include-dir Directory prefix where header files are installed by default
--php-binary Full path to php CLI or CGI binary
--php-sapis Show all SAPI modules available
--configure-options Configure options to recreate configuration of current PHP installation
--version PHP version
--vernum PHP version as integer



Compiling PECL extensions statically into PHP

You might find that you need to build a PECL extension statically into your PHP binary. To do this, you'll need to place the extension source under the php-src/ext/ directory and tell the PHP build system to regenerate its configure script.

$ cd /your/phpsrcdir/ext
$ pecl 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




Problemi?

Indice dei contenuti


Leggi le FAQ

Alcuni problemi sono più comuni di altri. I più comuni nella sezione PHP FAQ, di questo manuale.



Altri problemi

Se sei ancora bloccato, qualcuno nella mailing list per l'installazione di PHP potrebbe aiutarti. Dovresti controllare prima l'archivio in caso qualcun'altro avesse già dato una risposta ad un problema simile al tuo. Gli archivi sono accessibili dalla pagina di supporto a » http://www.php.net/support.php. Per iscriverti alla mailing list per l'istallazione di PHP invia una mail a » php-install-subscribe@lists.php.net. L'indirizzo per la mailing list è » php-install@lists.php.net.

Se vuoi ricevere aiuto dalla mailing list, cerca di essere preciso e fornisci tutti i dettagli necessari riguardo al tuo ambiente (sistema operativo, versione PHP, tipo di web server, se stai eseguendo PHP da CGI o come un modulo server, modalità sicura, ecc.), e possibilmente il codice per permettere ad altri di riprodurre e testare il tuo problema.



Segnalazione bug

Se pensi di aver trovato un bug in PHP, per favore segnalalo. Gli sviluppatori PHP probabilmente non ne sono a conoscenza e finchè non lo segnali non potrà essere risolto. Puoi segnalare i bug usando il sistema di bug-tracking alla pagina » http://bugs.php.net/. Ti preghiamo di non inviare segnalazioni di bug in mailing list o lettere personali. Il sistema di bug-tracking può essere utilizzato anche per richiedere miglioramenti.

Leggi il documento » Come segnalare un bug prima di inviare qualunque segnalazione.




Runtime Configuration

Indice dei contenuti


The configuration file

The configuration file (php.ini) 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 versions, it happens on every invocation.

php.ini is searched for 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)
  • The PHPRC environment variable. Before PHP 5.2.0, this was checked after the registry key mentioned below.
  • As of PHP 5.2.0, the location of the php.ini file can be set for different versions of PHP. The following registry keys are examined in order: [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y.z], [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y] and [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x], where x, y and z mean the PHP major, minor and release versions. If there is a value for IniFilePath in any of these keys, the first one found will be used as the location of the php.ini (Windows only).
  • [HKEY_LOCAL_MACHINE\SOFTWARE\PHP], value of IniFilePath (Windows only).
  • Current working directory (except 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 the SAPI in use, so, for example, php-cli.ini or php-apache.ini), it is used instead of php.ini. The SAPI name can be determined with 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.

Using environment variables can be used in php.ini as shown below.

Example #1 php.ini Environment Variables

; PHP_MEMORY_LIMIT is taken from environment
memory_limit = ${PHP_MEMORY_LIMIT}

The php.ini directives handled by extensions are documented on the respective pages of the extensions themselves. A list of the core directives is available in the appendix. Not all PHP directives are necessarily documented in this manual: for a complete list of directives available in your PHP version, please read your well commented php.ini file. Alternatively, you may find » the latest php.ini from Git helpful too.

Example #2 php.ini example

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

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

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

Since PHP 5.1.0, it is possible to refer to existing .ini variables from within .ini files. Example: open_basedir = ${open_basedir} ":/new/dir".



.user.ini files

Since PHP 5.3.0, PHP includes support for configuration INI files on a per-directory basis. These files are processed only by the CGI/FastCGI SAPI. This functionality obsoletes the PECL htscanner extension. If you are using Apache, use .htaccess files for the same effect.

In addition to the main php.ini file, PHP scans for INI files in each directory, starting with the directory of the requested PHP file, and working its way up to the current document root (as set in $_SERVER['DOCUMENT_ROOT']). In case the PHP file is outside the document root, only its directory is scanned.

Only INI settings with the modes PHP_INI_PERDIR and PHP_INI_USER will be recognized in .user.ini-style INI files.

Two new INI directives, user_ini.filename and user_ini.cache_ttl control the use of user INI files.

user_ini.filename sets the name of the file PHP looks for in each directory; if set to an empty string, PHP doesn't scan at all. The default is .user.ini.

user_ini.cache_ttl controls how often user INI files are re-read. The default is 300 seconds (5 minutes).



Where a configuration setting may be set

These modes determine when and where a PHP directive may or may not be set, and each directive within the manual refers to one of these modes. For example, some settings may be set within a PHP script using ini_set(), whereas others may require php.ini or httpd.conf.

For example, the output_buffering setting is PHP_INI_PERDIR therefore it may not be set using ini_set(). However, the display_errors directive is PHP_INI_ALL therefore it may be set anywhere, including with ini_set().

Definition of PHP_INI_* modes
Mode Meaning
PHP_INI_USER Entry can be set in user scripts (like with ini_set()) or in the Windows registry. Since PHP 5.3, entry can be set in .user.ini
PHP_INI_PERDIR Entry can be set in php.ini, .htaccess, httpd.conf or .user.ini (since PHP 5.3)
PHP_INI_SYSTEM Entry can be set in php.ini or httpd.conf
PHP_INI_ALL Entry can be set anywhere



How to change configuration settings

Running PHP as an Apache module

When using PHP as an Apache module, you can also change the configuration settings using directives in Apache configuration files (e.g. httpd.conf) and .htaccess files. You will need "AllowOverride Options" or "AllowOverride All" privileges to do so.

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.

php_value name value

Sets the value of the specified directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives. To clear a previously set value use none as the value.

Nota: Don't use php_value to set boolean values. php_flag (see below) should be used instead.

php_flag name on|off

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

php_admin_value name value

Sets the value of the specified directive. This can not be used in .htaccess files. Any directive type set with php_admin_value can not be overridden by .htaccess or ini_set(). To clear a previously set value use none as the value.

php_admin_flag name on|off

Used to set a boolean configuration directive. This can not be used in .htaccess files. Any directive type set with php_admin_flag can not be overridden by .htaccess or ini_set().

Example #1 Apache configuration example

<IfModule mod_php5.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag engine on
</IfModule>
<IfModule mod_php4.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag engine on
</IfModule>

Attenzione

PHP constants do not exist outside of PHP. For example, in httpd.conf you can not use PHP constants such as E_ALL or E_NOTICE to set the error_reporting directive as they will have no meaning and will evaluate to 0. Use the associated bitmask values instead. These constants can be used in php.ini

Changing PHP configuration via the Windows registry

When running PHP on Windows, the configuration values can be modified on a per-directory basis using the Windows registry. The configuration values are stored in the registry key HKLM\SOFTWARE\PHP\Per Directory Values, in the sub-keys corresponding to the path names. For example, configuration values for the directory c:\inetpub\wwwroot would be stored in the key HKLM\SOFTWARE\PHP\Per Directory Values\c\inetpub\wwwroot. The settings for the directory would be active for any script running from this directory or any subdirectory of it. The values under the key should have the name of the PHP configuration directive and the string value. PHP constants in the values are not parsed. However, only configuration values changeable in PHP_INI_USER can be set this way, PHP_INI_PERDIR values can not.

Other interfaces to PHP

Regardless of how you run PHP, you can change certain values at runtime of your scripts through ini_set(). See the documentation on the ini_set() page for more information.

If you are interested in a complete list of configuration settings on your system with their current values, you can execute the phpinfo() function, and review the resulting page. You can also access the values of individual configuration directives at runtime using ini_get() or get_cfg_var().





Struttura del Linguaggio


Sintassi Fondamentale

Indice dei contenuti


Tag PHP

Quando il PHP inizia a esaminare un file, cerca i tag di apertura e di chiusura, che sono <?php e ?>, i quali 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 ignorata dal parser PHP.

PHP permette anche dei tag abbreviati <? e ?> (che sono sconsigliati in quanto sono disponibili solo se abilitati con la direttiva short_open_tag nel file di configurazione php.ini, oppure se PHP è stato configuration con l'opzione --enable-short-tags .

Se un file contiene solo codice PHP, è cosniglato di omettere il tag di chiusura PHP alla fine del file. Questo evita che vengano aggiunti spazi o ritorni a capo dopo il tag di chiusura, che può creare effetti indesiderati poiché PHP comincerà a processare l'output quando in realtà non c'è intenzione da parte dello sviluppatore di inviare dell'output in quella parte dello script.

<?php
echo "Hello world";

// ... altro codice

echo "Last statement";

// lo script finisce qui senza tag di chiusura



Uscita dal modo HTML

Tutto ciò che esiste fuori dai tag di apertura e chiusura è ignorato dall'analizzatore PHP, il che permette di avere contenuto misto nei file PHP. Questo permette a PHP di essere incluso nei documenti HTML, per esempio per creare modelli.

<p>Questo sarà ignorato dea PHP e verrà visualizzato nel browser.</p>
<?php echo 'Questo invece sarà interpretato.'?>
<p>Pure questo sarà ignorato dea PHP e verrà visualizzato nel browser.</p>
Questo codice si comporta come desiderato, perché quando l'interprete PHP incontra il tag di chiusura ?>, comincia semplicemente a visualizzare tutto ciò che trova (a parte se è immediatamente seguito da una nuova linea - vedere l'istruzione di separazione) finché non incontra un altro tag di apertura, a meno che non si trovi in una istruzione condizionale, nel qual caso l'interprete determinerà il risultato della condizione prima di prendere una decisione su cosa ignorare. Vedere l'esempio seguente.

Utilizzo di strutture con condizioni

Example #1 Escape avanzato con le condizioni

<?php if ($expression == true): ?>
  Questo sarà viualizzato se l'espressione $expression è vera.
<?php else: ?>
  Altrimenti verrà visualizzata questa linea.
<?php endif; ?>
In questo esempio PHP ignorerà i blichi di codice in cui la condizione non è verificata, anche se sono fuori dai tag di apertura/chiusura, PHP li ignora a seconda della condizione dal momento che l'interprete PHP scavalca i blocchi contenuti in una condizione non verificata.

Nella visualizzazzione di grossi blocchi di testo uscire dalla modalità di parsing del codice PHP è generalmente più efficiente che inviare il tutto tramite echo o print.

Esistono 4 set di tag che possono essere utilizzati per delimitare blocchi di codice PHP. Soltanto due di questi, <?php ?> e <script language="php"> </script>, sono sempre disponibili. Gli altri due sono i tag brevi e i tag stile ASP e possono essere attivati o disattivati tramite il file di configurazione php.ini. Sebbene i tag brevi o quelli in stile ASP possano essere pratici, questi sono meno portabili e, in generale, sconsigliati.

Nota:

Occorre notare che se si intende inserire codice PHP all'interno di testi XMl o XHTML, occorre utilizzare <?php ?> per essere conformi allo standard XML.

Example #2 Tag di apertura e di chiusura

1.  <?php echo 'se si vogliono produrre documenti XHTML o XML, si utilizzi questo modo'?>

2.  <script language="php">
        
echo 'alcuni editor (tipo FrontPage) non 
               amano le istruzioni di elaborazione'
;
    
</script>

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

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

Sebbene i tag utilizzati negli esempi 1 e 2 siano sempre disponibili, l'esempio uno rappresenta la situazione più comunemente utilizzata, e la più raccomandata dei due.

I tag brevi (esempio tre) sono disponibili soltanto se sono stati abilitati tramite il parametro short_open_tag del php.ini, oppure se il PHP è stato configurato con --enable-short-tags .

I tag in stile ASP (esempio quattro) sono disponibili soltanto quando sono abilitati tramite il parametro asp_tags del php.ini

Nota:

L'utilizzo di tag brevi dovrebbe essere evitato quando si sviluppano applicazioni o librerie che sono destinate alla distribuzione, o all'installazione su server PHP che non sono sotto controllo diretto, poiché i tag brevi potrebbero non essere supportati dal server di destinazione. Per ottenere un codice portabile e redistribuibile, assicurarsi di non utilizzare tag brevi.

Nota:

In PHP 5.2 e precedenti, l'interprete non accetta che il tag di apertura <?php sia l'unica sequenza contenuta in un file. Questo è ammesso a partire da PHP 5.3, purché ci sia almeno un carattere spazio dopo il tag di apertura.

Nota:

A partire da PHP 5.4, il tag breve di echo <?= è sempre riconosciuto e valido, indipendentemente dall'impostazione short_open_tag.



Separazione delle istruzioni

Come in C od in Perl, il PHP richiede che le istruzioni siano chiuse dal punto e virgola al termine di ogni istruzione. I tag di chiusura di un blocco di codice PHP implicano in automatico il punto e virgola; non occorre, pertanto, inserire il punto e virgola per chiudere l'ultima riga di un blocco PHP. Il tag di chiusura del blocco include il newline immediatamente seguente, se presente.

<?php
    
echo 'Questo è un test';
?>

<?php echo 'Questo è un test' ?>

<?php echo 'Qui è stato omesso il tag di chiusura';

Nota:

Il tag di chiusura di un blocco PHP alla fine di un file è opzionale, ed in alcuni casi è utile ometterlo quando si utilizzano le funzioni include o require, in modo che spazi indesiderati non vengano generati alla fine dei file, e quindi sia ancora possibile aggiungere intestazioni alla risposta HTTP. È utile anche quando si usa l'output buffering, e non si vogliono avere spazi indesiderati alla fine delle parti generate dai file inclusi.



Commenti

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 // ... ?> o # ... ?> 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 // %> e # %>. 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
 
/*
    echo 'Questo è un test'; /* Questo commento causerà dei problemi */
 
*/
?>




Tipi di dati

Indice dei contenuti


Introduzione

PHP supporta otto tipi di dati primitivi.

Quattro tipi scalari:

Due tipi composti:

Ed infine tre tipi speciali di dati:

Questo manuale introduce anche alcuni pseudo-tipi per ragioni di leggibilità:

E la pseudo-variabile $....

Alcuni riferimenti al tipo "double" possono essere rimasti nel manuale. Si consideri che double equivale a float; i due nomi esistono solo per ragioni storiche.

Generalmente, il tipo di una variabile non viene assegnata dal programmatore; anzi, viene assegnata in fase di esecuzione da PHP a seconda del contesto nel quale tale variabile viene utilizzata.

Nota: Per verificare il tipo e il valore di una espressione, usare la funzione var_dump().

Per ottenere una rappresentazione leggibile di un tipo in fase di debugging usare la funzione gettype(). Per verificare che una variabile sia di un certo tipo non usare la funzione gettype(), piuttosto sua la funzione is_tipo. Alcuni esempi:

<?php
$a_bool 
TRUE;   // un booleano
$a_str  "foo";  // una stringa
$a_str2 'foo';  // una stringa
$an_int 12;     // un integer

echo gettype($a_bool); // stampa:  boolean
echo gettype($a_str);  // stampa:  string

// Se è un intero, incrementalo di quattro
if (is_int($an_int)) {
    
$an_int += 4;
}

// Se $a_bool è una stringa, stampala a video
// (non stampa niente)
if (is_string($a_bool)) {
    echo 
"Stringa: $a_bool";
}
?>

Per forzare la conversione di una variabile in un certo tipo, puoi usare sia il cast sulla variabile oppure la funzione settype().

Si noti che una variabile può essere riempita con valori differenti in determinate situazioni, dipendentemente dal suo tipo nel dato momento. Per ulteriori informazioni vedere la sezione sulla Manipolazione dei Tipi. Le tabelle di comparazione dei tipi possono essere utili, in quanto mostrano esempi di comparazioni correlate ai tipi.



Booleans

This is the simplest type. A boolean expresses a truth value. It can be either TRUE or FALSE.

Syntax

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

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

Typically, the result of an operator which returns a boolean value is passed on to a control structure.

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

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

// ...because this can be used with exactly the same meaning:
if ($show_separators) {
    echo 
"<hr>\n";
}
?>

Converting to boolean

To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, 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)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

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

Avviso

-1 is considered TRUE, like any other non-zero (whether negative or positive) number!

<?php
var_dump
((bool) "");        // bool(false)
var_dump((bool) 1);         // bool(true)
var_dump((bool) -2);        // bool(true)
var_dump((bool) "foo");     // bool(true)
var_dump((bool) 2.3e5);     // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array());   // bool(false)
var_dump((bool) "false");   // bool(true)
?>


Integers

An integer is a number of the set ℤ = {..., -2, -1, 0, 1, 2, ...}.

See also:

Syntax

Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a sign (- or +).

Binary integer literals are available since PHP 5.4.0.

To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x. To use binary notation precede the number with 0b.

Example #1 Integer literals

<?php
$a 
1234// decimal number
$a = -123// a negative number
$a 0123// octal number (equivalent to 83 decimal)
$a 0x1A// hexadecimal number (equivalent to 26 decimal)
$a 0b11111111// binary number (equivalent to 255 decimal)
?>

Formally, the structure for integer literals is:

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

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

octal       : 0[0-7]+

binary      : 0b[01]+

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

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

Avviso

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

Example #2 Octal weirdness

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

Integer overflow

If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.

Example #3 Integer overflow on a 32-bit system

<?php
$large_number 
2147483647;
var_dump($large_number);                     // int(2147483647)

$large_number 2147483648;
var_dump($large_number);                     // float(2147483648)

$million 1000000;
$large_number =  50000 $million;
var_dump($large_number);                     // float(50000000000)
?>

Example #4 Integer overflow on a 64-bit system

<?php
$large_number 
9223372036854775807;
var_dump($large_number);                     // int(9223372036854775807)

$large_number 9223372036854775808;
var_dump($large_number);                     // float(9.2233720368548E+18)

$million 1000000;
$large_number =  50000000000000 $million;
var_dump($large_number);                     // float(5.0E+19)
?>

There is no integer division operator in PHP. 1/2 yields the float 0.5. The value can be casted to an integer to round it downwards, or the round() function provides finer control over rounding.

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

Converting to integer

To explicitly convert a value to integer, use either the (int) or (integer) casts. However, in most cases the cast is not needed, since a value will be automatically converted if an operator, function or control structure requires an integer argument. A value can also be converted to integer with the intval() function.

If a resource is converted to an integer, then the result will be the unique resource number assigned to the resource by PHP at runtime.

See also Type Juggling.

From booleans

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

From floating point numbers

When converting from float to integer, the number will be rounded towards zero.

If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31 on 32-bit platforms and +/- 9.22e+18 = 2^63 on 64-bit platforms), the result is undefined, since the float doesn't have enough precision to give an exact integer result. No warning, not even a notice will be issued when this happens!

Avviso

Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results.

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

See also the warning about float precision.

From strings

See String conversion to numbers

From other types

Attenzione

The behaviour of converting to integer is undefined for other types. Do not rely on any observed behaviour, as it can change without notice.



Floating point numbers

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

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

Formally:

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

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

Avviso

Floating point precision

Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small 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, since the internal representation will be something like 7.9999999999999991118....

So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

For a "simple" explanation, see the » floating point guide that's also titled "Why don’t my numbers add up?"

Converting to float

For information on converting strings to float, see String conversion to numbers. For values of other types, the conversion is performed by converting the value to integer first and then to float. See Converting to integer for more information. As of PHP 5, a notice is thrown if an object is converted to float.

Comparing floats

As noted in the warning above, testing floating point values for equality is problematic, due to the way that they are represented internally. However, there are ways to make comparisons of floating point values that work around these limitations.

To test floating point values for equality, an upper bound on the relative error due to rounding is used. This value is known as the machine epsilon, or unit roundoff, and is the smallest acceptable difference in calculations.

$a and $b are equal to 5 digits of precision.

<?php
$a 
1.23456789;
$b 1.23456780;
$epsilon 0.00001;

if(
abs($a-$b) < $epsilon) {
    echo 
"true";
}
?>

NaN

Some numeric operations can result in a value represented by the constant NAN. This result represents an undefined or unrepresentable value in floating-point calculations. Any loose or strict comparisons of this value against any other value, including itself, will have a result of FALSE.

Because NAN represents any number of different values, NAN should not be compared to other values, including itself, and instead should be checked for using is_nan().



Strings

A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. See details of the string type.

Nota: string can be as large as up to 2GB (2147483647 bytes maximum)

Syntax

A string literal can be specified in four different ways:

Single quoted

The simplest way to specify a string is to enclose it in single quotes (the character ').

To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash, double it (\\). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \r or \n, will be output literally as specified rather than having any special meaning.

Nota: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

<?php
echo 'this is a simple string';

echo 
'You can also have embedded newlines in 
strings this way as it is
okay to do'
;

// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';

// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';

// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>

Double quoted

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

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)
\v vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)
\e escape (ESC or 0x1B (27) in ASCII) (since PHP 5.4.0)
\f form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\\ 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

As in single quoted strings, escaping any other character will result in the backslash being printed too. Before PHP 5.1.1, the backslash in \{$var} had not been printed.

The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.

Heredoc

A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.

The closing identifier must begin in the first column of the line. Also, the identifier 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.

Avviso

It is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter must also be followed by a newline.

If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line.

Heredocs can not be used for initializing class properties. Since PHP 5.3, this limitation is valid only for heredocs containing variables.

Example #1 Invalid example

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

Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.

Example #2 Heredoc string quoting example

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

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

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

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

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

Il precedente esempio visualizzerà:

My name is "MyName". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A

It is also possible to use the Heredoc syntax to pass data to function arguments:

Example #3 Heredoc in arguments example

<?php
var_dump
(array(<<<EOD
foobar!
EOD
));
?>

As of PHP 5.3.0, it's possible to initialize static variables and class properties/constants using the Heredoc syntax:

Example #4 Using Heredoc to initialize static values

<?php
// Static variables
function foo()
{
    static 
$bar = <<<LABEL
Nothing in here...
LABEL;
}

// Class properties/constants
class foo
{
    const 
BAR = <<<FOOBAR
Constant example
FOOBAR;

    public 
$baz = <<<FOOBAR
Property example
FOOBAR;
}
?>

Starting with PHP 5.3.0, the opening Heredoc identifier may optionally be enclosed in double quotes:

Example #5 Using double quotes in Heredoc

<?php
echo <<<"FOOBAR"
Hello World!
FOOBAR;
?>

Nowdoc

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML <![CDATA[ ]]> construct, in that it declares a block of text which is not for parsing.

A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.

Example #6 Nowdoc string quoting example

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

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

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

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

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

Il precedente esempio visualizzerà:

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

Nota:

Unlike heredocs, nowdocs can be used in any static data context. The typical example is initializing class properties or constants:

Example #7 Static data example

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

Nota:

Nowdoc support was added in PHP 5.3.0.

Variable parsing

When a string is specified in double quotes or with heredoc, variables are parsed within it.

There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort.

The complex syntax can be recognised by the curly braces surrounding the expression.

Simple syntax

If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.

<?php
$juice 
"apple";

echo 
"He drank some $juice juice.".PHP_EOL;
// Invalid. "s" is a valid character for a variable name, but the variable is $juice.
echo "He drank some juice made of $juices.";
?>

Il precedente esempio visualizzerà:

He drank some apple juice.
He drank some juice made of .

Similarly, an array index or an object property can be parsed. With array indices, the closing square bracket (]) marks the end of the index. The same rules apply to object properties as to simple variables.

Example #8 Simple syntax example

<?php
$juices 
= array("apple""orange""koolaid1" => "purple");

echo 
"He drank some $juices[0] juice.".PHP_EOL;
echo 
"He drank some $juices[1] juice.".PHP_EOL;
echo 
"He drank some $juices[koolaid1] juice.".PHP_EOL;

class 
people {
    public 
$john "John Smith";
    public 
$jane "Jane Smith";
    public 
$robert "Robert Paulsen";
    
    public 
$smith "Smith";
}

$people = new people();

echo 
"$people->john drank some $juices[0] juice.".PHP_EOL;
echo 
"$people->john then said hello to $people->jane.".PHP_EOL;
echo 
"$people->john's wife greeted $people->robert.".PHP_EOL;
echo 
"$people->robert greeted the two $people->smiths."// Won't work
?>

Il precedente esempio visualizzerà:

He drank some apple juice.
He drank some orange juice.
He drank some purple juice.
John Smith drank some apple juice.
John Smith then said hello to Jane Smith.
John Smith's wife greeted Robert Paulsen.
Robert Paulsen greeted the two .

For anything more complex, you should use the complex syntax.

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

<?php
// 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, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";


// 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 only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
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 
"This works too: {$obj->values[3]->name}";

echo 
"This is the value of the var named $name{${$name}}";

echo 
"This is the value of the var named by the return value of getName(): {${getName()}}";

echo 
"This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";

// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>

It is also possible to access class properties using variables within strings using this syntax.

<?php
class foo {
    var 
$bar 'I am bar.';
}

$foo = new foo();
$bar 'bar';
$baz = array('foo''bar''baz''quux');
echo 
"{$foo->$bar}\n";
echo 
"{$foo->$baz[1]}\n";
?>

Il precedente esempio visualizzerà:

I am bar.
I am bar.

Nota:

Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.

<?php
// Show all errors.
error_reporting(E_ALL);

class 
beers {
    const 
softdrink 'rootbeer';
    public static 
$ale 'ipa';
}

$rootbeer 'A & W';
$ipa 'Alexander Keith\'s';

// This works; outputs: I'd like an A & W
echo "I'd like an {${beers::softdrink}}\n";

// This works too; outputs: I'd like an Alexander Keith's
echo "I'd like an {${beers::$ale}}\n";
?>

String access and modification by character

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose. The functions substr() and substr_replace() can be used when you want to extract or replace more than 1 character.

Nota: Strings may also be accessed using braces, as in $str{42}, for the same purpose.

Avviso

Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits E_NOTICE. Negative offset emits E_NOTICE in write but reads empty string. Only the first character of an assigned string is used. Assigning empty string assigns NULL byte.

Avviso

Internally, PHP strings are byte arrays. As a result, accessing or modifying a string using array brackets is not multi-byte safe, and should only be done with strings that are in a single-byte encoding such as ISO-8859-1.

Example #9 Some string examples

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

// Get the third character of a string
$third $str[2];

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

// Modify the last character of a string
$str 'Look at the sea';
$str[strlen($str)-1] = 'e';

?>

As of PHP 5.4 string offsets have to either be integers or integer-like strings, otherwise a warning will be thrown. Previously an offset like "foo" was silently cast to 0.

Example #10 Differences between PHP 5.3 and PHP 5.4

<?php
$str 
'abc';

var_dump($str['1']);
var_dump(isset($str['1']));

var_dump($str['1.0']);
var_dump(isset($str['1.0']));

var_dump($str['x']);
var_dump(isset($str['x']));

var_dump($str['1x']);
var_dump(isset($str['1x']));
?>

Risultato del precedente esempio in PHP 5.3:

string(1) "b"
bool(true)
string(1) "b"
bool(true)
string(1) "a"
bool(true)
string(1) "b"
bool(true)

Risultato del precedente esempio in PHP 5.4:

string(1) "b"
bool(true)

Warning: Illegal string offset '1.0' in /tmp/t.php on line 7
string(1) "b"
bool(false)

Warning: Illegal string offset 'x' in /tmp/t.php on line 9
string(1) "a"
bool(false)
string(1) "b"
bool(false)

Nota:

Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL.

Nota:

PHP 5.5 added support for accessing characters within string literals using [] or {}.

Useful functions and operators

Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. See String operators for more information.

There are a number of useful functions for string manipulation.

See the string functions section for general functions, and the regular expression functions or the Perl-compatible regular expression functions for advanced find & replace functionality.

There are also functions for URL strings, and functions to encrypt/decrypt strings (mcrypt and mhash).

Finally, see also the character type functions.

Converting to string

A value can be converted to a string using the (string) cast or the strval() function. String conversion is automatically done in the scope of an expression where a string is needed. This happens when using the echo or print functions, or when a variable is compared to a string. The sections on Types and Type Juggling will make the following clearer. See also the settype() function.

A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

An integer or float is converted to a string representing the number textually (including the exponent part for floats). Floating point numbers can be converted using exponential notation (4.1E+6).

Nota:

The decimal point character is defined in the script's locale (category LC_NUMERIC). See the setlocale() function.

Arrays are always converted to the string "Array"; because of this, echo and print can not by themselves show the contents of an array. To view a single element, use a construction such as echo $arr['foo']. See below for tips on viewing the entire contents.

Objects in PHP 4 are always converted to the string "Object". To print the values of object properties for debugging reasons, read the paragraphs below. To get an object's class name, use the get_class() function. As of PHP 5, the __toString method is used when applicable.

Resources are always converted to strings with the structure "Resource id #1", where 1 is the resource number assigned to the resource by PHP at runtime. While the exact structure of this string should not be relied on and is subject to change, it will always be unique for a given resource within the lifetime of a script being executed (ie a Web request or CLI process) and won't be reused. To get a resource's type, use the get_resource_type() function.

NULL is always converted to an empty string.

As stated above, directly converting an array, object, or resource to a string does not provide any useful information about the value beyond its type. See the functions print_r() and var_dump() for more effective means of inspecting the contents of these types.

Most PHP values can also be converted to strings for permanent storage. This method is called serialization, and is performed by the serialize() function. If the PHP engine was built with WDDX support, PHP values can also be serialized as well-formed XML text.

String conversion to numbers

When a string is evaluated in a numeric context, the resulting value and type are determined as follows.

If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.

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 
"10.5";                // $foo is float (11.5)
$foo "-1.3e3";              // $foo is float (-1299)
$foo "bob-1.3e3";           // $foo is integer (1)
$foo "bob3";                // $foo is integer (1)
$foo "10 Small Pigs";       // $foo is integer (11)
$foo "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).

To test any of the examples in this section, cut and paste the examples and insert the following line to see what's going on:

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

Do not expect to get the code of one character by converting it to integer, as is done in C. Use the ord() and chr() functions to convert between ASCII codes and characters.

Details of the String Type

The string in PHP is implemented as an array of bytes and an integer indicating the length of the buffer. It has no information about how those bytes translate to characters, leaving that task to the programmer. There are no limitations on the values the string can be composed of; in particular, bytes with value 0 (“NUL bytes”) are allowed anywhere in the string (however, a few functions, said in this manual not to be “binary safe”, may hand off the strings to libraries that ignore data after a NUL byte.)

This nature of the string type explains why there is no separate “byte” type in PHP – strings take this role. Functions that return no textual data – for instance, arbitrary data read from a network socket – will still return strings.

Given that PHP does not dictate a specific encoding for strings, one might wonder how string literals are encoded. For instance, is the string "á" equivalent to "\xE1" (ISO-8859-1), "\xC3\xA1" (UTF-8, C form), "\x61\xCC\x81" (UTF-8, D form) or any other possible representation? The answer is that string will be encoded in whatever fashion it is encoded in the script file. Thus, if the script is written in ISO-8859-1, the string will be encoded in ISO-8859-1 and so on. However, this does not apply if Zend Multibyte is enabled; in that case, the script may be written in an arbitrary encoding (which is explicity declared or is detected) and then converted to a certain internal encoding, which is then the encoding that will be used for the string literals. Note that there are some constraints on the encoding of the script (or on the internal encoding, should Zend Multibyte be enabled) – this almost always means that this encoding should be a compatible superset of ASCII, such as UTF-8 or ISO-8859-1. Note, however, that state-dependent encodings where the same byte values can be used in initial and non-initial shift states may be problematic.

Of course, in order to be useful, functions that operate on text may have to make some assumptions about how the string is encoded. Unfortunately, there is much variation on this matter throughout PHP’s functions:

  • Some functions assume that the string is encoded in some (any) single-byte encoding, but they do not need to interpret those bytes as specific characters. This is case of, for instance, substr(), strpos(), strlen() or strcmp(). Another way to think of these functions is that operate on memory buffers, i.e., they work with bytes and byte offsets.
  • Other functions are passed the encoding of the string, possibly they also assume a default if no such information is given. This is the case of htmlentities() and the majority of the functions in the mbstring extension.
  • Others use the current locale (see setlocale()), but operate byte-by-byte. This is the case of strcasecmp(), strtoupper() and ucfirst(). This means they can be used only with single-byte encodings, as long as the encoding is matched by the locale. For instance strtoupper("á") may return "Á" if the locale is correctly set and á is encoded with a single byte. If it is encoded in UTF-8, the correct result will not be returned and the resulting string may or may not be returned corrupted, depending on the current locale.
  • Finally, they may just assume the string is using a specific encoding, usually UTF-8. This is the case of most functions in the intl extension and in the PCRE extension (in the last case, only when the u modifier is used). Although this is due to their special purpose, the function utf8_decode() assumes a UTF-8 encoding and the function utf8_encode() assumes an ISO-8859-1 encoding.

Ultimately, this means writing correct programs using Unicode depends on carefully avoiding functions that will not work and that most likely will corrupt the data and using instead the functions that do behave correctly, generally from the intl and mbstring extensions. However, using functions that can handle Unicode encodings is just the beginning. No matter the functions the language provides, it is essential to know the Unicode specification. For instance, a program that assumes there is only uppercase and lowercase is making a wrong assumption.



Arrays

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

Explanation of those data structures is beyond the scope of this manual, but at least one example is provided for each of them. For more information, look towards the considerable literature that exists about this broad topic.

Syntax

Specifying with array()

An array can be created using the array() language construct. It takes any number of comma-separated key => value pairs as arguments.

array(
    key  => value,
    key2 => value2,
    key3 => value3,
    ...
)

The comma after the last array element is optional and can be omitted. This is usually done for single-line arrays, i.e. array(1, 2) is preferred over array(1, 2, ). For multi-line arrays on the other hand the trailing comma is commonly used, as it allows easier addition of new elements at the end.

As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].

Example #1 A simple array

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

// as of PHP 5.4
$array = [
    
"foo" => "bar",
    
"bar" => "foo",
];
?>

The key can either be an integer or a string. The value can be of any type.

Additionally the following key casts will occur:

  • Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.
  • Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under 8.
  • Bools are cast to integers, too, i.e. the key true will actually be stored under 1 and the key false under 0.
  • Null will be cast to the empty string, i.e. the key null will actually be stored under "".
  • Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.

Example #2 Type Casting and Overwriting example

<?php
$array 
= array(
    
1    => "a",
    
"1"  => "b",
    
1.5  => "c",
    
true => "d",
);
var_dump($array);
?>

Il precedente esempio visualizzerà:

array(1) {
  [1]=>
  string(1) "d"
}

As all the keys in the above example are cast to 1, the value will be overwritten on every new element and the last assigned value "d" is the only one left over.

PHP arrays can contain integer and string keys at the same time as PHP does not distinguish between indexed and associative arrays.

Example #3 Mixed integer and string keys

<?php
$array 
= array(
    
"foo" => "bar",
    
"bar" => "foo",
    
100   => -100,
    -
100  => 100,
);
var_dump($array);
?>

Il precedente esempio visualizzerà:

array(4) {
  ["foo"]=>
  string(3) "bar"
  ["bar"]=>
  string(3) "foo"
  [100]=>
  int(-100)
  [-100]=>
  int(100)
}

The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key.

Example #4 Indexed arrays without key

<?php
$array 
= array("foo""bar""hello""world");
var_dump($array);
?>

Il precedente esempio visualizzerà:

array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(5) "hello"
  [3]=>
  string(5) "world"
}

It is possible to specify the key only for some elements and leave it out for others:

Example #5 Keys not on all elements

<?php
$array 
= array(
         
"a",
         
"b",
    
=> "c",
         
"d",
);
var_dump($array);
?>

Il precedente esempio visualizzerà:

array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [6]=>
  string(1) "c"
  [7]=>
  string(1) "d"
}

As you can see the last value "d" was assigned the key 7. This is because the largest integer key before that was 6.

Accessing array elements with square bracket syntax

Array elements can be accessed using the array[key] syntax.

Example #6 Accessing array elements

<?php
$array 
= array(
    
"foo" => "bar",
    
42    => 24,
    
"multi" => array(
         
"dimensional" => array(
             
"array" => "foo"
         
)
    )
);

var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
?>

Il precedente esempio visualizzerà:

string(3) "bar"
int(24)
string(3) "foo"

Nota:

Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} will both do the same thing in the example above).

As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.

As of PHP 5.5 it is possible to array dereference an array literal.

Example #7 Array dereferencing

<?php
function getArray() {
    return array(
123);
}

// on PHP 5.4
$secondElement getArray()[1];

// previously
$tmp getArray();
$secondElement $tmp[1];

// or
list(, $secondElement) = getArray();
?>

Nota:

Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_NOTICE-level error message will be issued, and the result will be NULL.

Creating/modifying with square bracket syntax

An existing array can be modified by explicitly setting values in it.

This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]).

$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type

If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize variable by a direct assignment.

To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset() function on it.

<?php
$arr 
= array(=> 112 => 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 no key is specified, the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1 (but at least 0). If no integer indices exist yet, the key will be 0 (zero).

Note that the maximum integer key used for this need not currently exist in the array. It need only 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(12345);
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).
$array[] = 6;
print_r($array);

// Re-index:
$array array_values($array);
$array[] = 7;
print_r($array);
?>

Il precedente esempio visualizzerà:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array
(
)
Array
(
    [5] => 6
)
Array
(
    [0] => 6
    [1] => 7
)

Useful functions

There are quite a few useful functions for working with arrays. See the array functions section.

Nota:

The unset() function allows removing keys from an array. Be aware that the array will not be reindexed. If a true "remove and shift" behavior is desired, the array can be reindexed using the array_values() function.

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

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

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

Array do's and don'ts

Why is $foo[bar] wrong?

Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not. But why? It is common to encounter this kind of syntax in old scripts:

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

This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in the future define constants which, unfortunately for such 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. Do not 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(12);
$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";
}
?>

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

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

// This defines a constant to demonstrate what's going on.  The value 'veggie'
// is assigned 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 occurs here
print "Hello $arr[fruit]";      // Hello apple

// With one exception: braces surrounding arrays within strings allows constants
// to be interpreted
print "Hello {$arr[fruit]}";    // Hello carrot
print "Hello {$arr['fruit']}";  // Hello apple

// This will not work, and will result 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 superglobals in strings as well
print "Hello $arr['fruit']";
print 
"Hello $_GET['foo']";

// Concatenation is another option
print "Hello " $arr['fruit']; // Hello apple
?>

When error_reporting is set to show E_NOTICE level errors (by setting it to E_ALL, for example), such uses will become immediately visible. By default, error_reporting is set not to show notices.

As stated in the syntax section, what's inside the square brackets ('[' and ']') must be an expression. This means that code like this works:

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

This is an example of using a function return value as the array index. PHP also knows about constants:

<?php
$error_descriptions
[E_ERROR]   = "A fatal error has occurred";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE]  = "This is just an informal notice";
?>

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

<?php
$error_descriptions
[1] = "A fatal error has occurred";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
?>

because E_ERROR equals 1, etc.

So why is it bad then?

At some point in the future, the PHP team might want to add another constant or keyword, or a constant in other code may interfere. For example, it is already wrong to use the words empty and default this way, since they are reserved keywords.

Nota: To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings.

Converting to array

For any of the types: integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue).

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour:

<?php

class {
    private 
$A// This will become '\0A\0A'
}

class 
extends {
    private 
$A// This will become '\0B\0A'
    
public $AA// This will become 'AA'
}

var_dump((array) new B());
?>

The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'.

Converting NULL to an array results in an empty array.

Comparing

It is possible to compare arrays with the array_diff() function and with array operators.

Examples

The array type in PHP is very versatile. Here are some examples:

<?php
// This:
$a = array( 'color' => 'red',
            
'taste' => 'sweet',
            
'shape' => 'round',
            
'name'  => 'apple',
            
4        // key will be 0
          
);

$b = array('a''b''c');

// . . .is completely equivalent with this:
$a = array();
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name']  = 'apple';
$a[]        = 4;        // key will be 0

$b = array();
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';

// After the above code is executed, $a will be the array
// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round', 
// 'name' => 'apple', 0 => 4), and $b will be the array 
// array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c').
?>

Example #8 Using array()

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

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

Example #9 Collection

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

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

?>

Il precedente esempio visualizzerà:

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

Changing the values of the array directly is possible since PHP 5 by passing them by reference. Before that, a workaround is necessary:

Example #10 Changing element in the loop

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

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

print_r($colors);
?>

Il precedente esempio visualizzerà:

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

This example creates a one-based array.

Example #11 One-based index

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

Il precedente esempio visualizzerà:

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

Example #12 Filling an array

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

Arrays are ordered. The order can be changed using various sorting functions. See the array functions section for more information. The count() function can be used to count the number of items in an array.

Example #13 Sorting an array

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

Because the value of an array can be anything, it can also be another array. This enables the creation of recursive and multi-dimensional arrays.

Example #14 Recursive and multi-dimensional arrays

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

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

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

Array assignment always involves value copying. Use the reference operator to copy an array by reference.

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


Objects

Object Initialization

To create a new object, use the new statement to instantiate a class:

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

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

For a full discussion, see the Classes and Objects chapter.

Converting to object

If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty. Arrays convert to an object with properties named by keys, and corresponding values. For any other value, a member variable named scalar will contain the value.

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


Resources

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.

See also the get_resource_type() function.

Converting to resource

As resource variables hold special handlers to opened files, database connections, image canvas areas and the like, converting to a resource makes no sense.

Freeing resources

Thanks to the reference-counting system introduced with PHP 4's Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.

Nota: Persistent database links are an exception to this rule. They are not destroyed by the garbage collector. See the persistent connections section for more information.



NULL

Il valore speciale NULL rappresenta una variable senza valore. NULL è il solo valore possibile del tipo null.

Una variabile è null se:

  • le è stato assegnata la costante NULL.

  • non le è stato ancora assegnato un valore.

  • è stata cancellata con la funzione unset().

Syntax

Esiste solo un valore di tipo null, la costante NULL, che è invariante, sia essa in maiuscolo o in minuscolo.

<?php
$var 
NULL;       
?>

Vedere anche le funzioni is_null() e unset().

Casting a NULL

Effettuare il casting di una variabile a null usando (unset) $var non rimuove la variabile, né cancella il valore. Non fa altro che restituire un valore NULL.



Callbacks

Callbacks can be denoted by callable type hint as of PHP 5.4. This documentation used callback type information for the same purpose.

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.

Passing

A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: array(), echo, empty(), eval(), exit(), isset(), list(), print or unset().

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at 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 at index 0. As of PHP 5.2.3, it is also possible to pass 'ClassName::methodName'.

Apart from common user-defined function, anonymous functions can also be passed to a callback parameter.

Example #1 Callback function examples

<?php 

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

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

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

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

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

// Type 4: Static class method call (As of PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');

// Type 5: Relative static class method call (As of PHP 5.3.0)
class {
    public static function 
who() {
        echo 
"A\n";
    }
}

class 
extends {
    public static function 
who() {
        echo 
"B\n";
    }
}

call_user_func(array('B''parent::who')); // A
?>

Example #2 Callback example using a Closure

<?php
// Our closure
$double = function($a) {
    return 
$a 2;
};

// This is our range of numbers
$numbers range(15);

// Use the closure as a callback here to 
// double the size of each element in our 
// range
$new_numbers array_map($double$numbers);

print 
implode(' '$new_numbers);
?>

Il precedente esempio visualizzerà:

2 4 6 8 10

Nota: In PHP 4, it was necessary to use a reference to create a callback that points to the actual object, and not a copy of it. For more details, see References Explained.

Nota:

I callback registrati alle funzioni come call_user_func() e call_user_func_array() non saranno invocati se un'eccezione non gestita è trasmessa da un callback precedente.



Pseudo-types and variables used in this documentation

mixed

mixed indicates that a parameter may accept multiple (but not necessarily all) types.

gettype() for example will accept all PHP types, while str_replace() will accept strings and arrays.

number

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

callback

callback pseudo-types was used in this documentation before callable type hint was introduced by PHP 5.4. It means exactly the same.

void

void as a return type means that the return value is useless. void in a parameter list means that the function doesn't accept any parameters.

...

$... in function prototypes means and so on. This variable name is used when a function can take an endless number of arguments.



Type Juggling

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.

An example of PHP's automatic type conversion is the addition operator '+'. If either operand is a float, then both 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 and what the type of the expression itself is.

<?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 "10 Little Piggies"// $foo is integer (15)
$foo "10 Small Pigs";     // $foo is integer (15)
?>

If the last two examples above seem odd, see String conversion to numbers.

To force a variable to be evaluated as a certain type, see the section on Type casting. To change the type of a variable, see the settype() function.

To test any of the examples in this section, use the var_dump() function.

Nota:

The behaviour of an automatic conversion to array is currently undefined.

Also, because PHP supports indexing into strings via offsets using the same syntax as array indexing, the following example holds true for all PHP versions:

<?php
$a    
'car'// $a is a string
$a[0] = 'b';   // $a is still a string
echo $a;       // bar
?>

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

Type Casting

Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.

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

The casts allowed are:

  • (int), (integer) - cast to integer
  • (bool), (boolean) - cast to boolean
  • (float), (double), (real) - cast to float
  • (string) - cast to string
  • (array) - cast to array
  • (object) - cast to object
  • (unset) - cast to NULL (PHP 5)

(binary) casting and b prefix forward support was added in PHP 5.2.1

Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:

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

Casting literal strings and variables to binary strings:

<?php
$binary 
= (binary) $string;
$binary b"binary string";
?>

Nota:

Instead of casting a variable to a string, it is also possible to enclose the variable in double quotes.

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

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

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




Variables

Indice dei contenuti


Basics

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

Nota: For our purposes here, a letter is a-z, A-Z, and the bytes from 127 through 255 (0x7f-0xff).

Nota: $this is a special variable that can't be assigned.

Suggerimento

Si può anche consultare Userland Naming Guide.

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

By default, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see the chapter on Expressions.

PHP also 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.

To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice:

<?php
$foo 
'Bob';              // Assign the value 'Bob' to $foo
$bar = &$foo;              // Reference $foo via $bar.
$bar "My name is $bar";  // Alter $bar...
echo $bar;
echo 
$foo;                 // $foo is altered too.
?>

One important thing to note is that only named variables may be assigned by reference.

<?php
$foo 
25;
$bar = &$foo;      // This is a valid assignment.
$bar = &(24 7);  // Invalid; references an unnamed expression.

function test()
{
   return 
25;
}

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

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.

Example #1 Default values of uninitialized variables

<?php
// Unset AND unreferenced (no use context) variable; outputs NULL
var_dump($unset_var);

// Boolean usage; outputs 'false' (See ternary operators for more on this syntax)
echo($unset_bool "true\n" "false\n");

// String usage; outputs 'string(3) "abc"'
$unset_str .= 'abc';
var_dump($unset_str);

// Integer usage; outputs 'int(25)'
$unset_int += 25// 0 + 25 => 25
var_dump($unset_int);

// Float/double usage; outputs 'float(1.25)'
$unset_float += 1.25;
var_dump($unset_float);

// Array usage; outputs array(1) {  [3]=>  string(3) "def" }
$unset_arr[3] = "def"// array() + array(3 => "def") => array(3 => "def")
var_dump($unset_arr);

// Object usage; creates new stdClass object (see http://www.php.net/manual/en/reserved.classes.php)
// Outputs: object(stdClass)#1 (1) {  ["foo"]=>  string(3) "bar" }
$unset_obj->foo 'bar';
var_dump($unset_obj);
?>

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.



Predefined Variables

PHP provides a large number of predefined variables to any script which it runs. Many of these variables, however, cannot be fully documented as they are dependent upon which server is running, the version and setup of the server, and other factors. Some of these variables will not be available when PHP is run on the command line. For a listing of these variables, please see the section on Reserved Predefined Variables.

Avviso

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 "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. Dal PHP 5.0.0, gli array di variabili predefinite possono essere disabilitati con il parametro register_long_arrays .

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



Variable scope

The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:

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

Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:

<?php
$a 
1/* global scope */ 

function test()

    echo 
$a/* reference to local scope variable */ 


test();
?>

This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.

The global keyword

First, an example use of global:

Example #1 Using global

<?php
$a 
1;
$b 2;

function 
Sum()
{
    global 
$a$b;

    
$b $a $b;


Sum();
echo 
$b;
?>

The above script will output 3. By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.

A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:

Example #2 Using $GLOBALS instead of global

<?php
$a 
1;
$b 2;

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


Sum();
echo 
$b;
?>

The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal. Here's an example demonstrating the power of superglobals:

Example #3 Example demonstrating superglobals and scope

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

Nota:

Using global keyword outside a function is not an error. It can be used if the file is included from inside a function.

Using static variables

Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example:

Example #4 Example demonstrating need for static variables

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

This function is quite useless since every time it is called it sets $a to 0 and prints 0. The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:

Example #5 Example use of static variables

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

Now, $a is initialized only in first call of function and 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:

Example #6 Static variables with recursive functions

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

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

Nota:

Static variables may be declared as seen in the examples above. Trying to assign values to these variables which are the result of expressions will cause a parse error.

Example #7 Declaring static variables

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

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

Nota:

Static declarations are resolved in compile-time.

References with global and static variables

The Zend Engine 1, driving PHP 4, implements the static and global modifier for variables in terms of references. For example, a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. This can lead to unexpected behaviour which the following example addresses:

<?php
function test_global_ref() {
    global 
$obj;
    
$obj = &new stdclass;
}

function 
test_global_noref() {
    global 
$obj;
    
$obj = new stdclass;
}

test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>

Il precedente esempio visualizzerà:


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

Il precedente esempio visualizzerà:


Static object: NULL
Static object: NULL

Static object: NULL
Static object: object(stdClass)(1) {
["property"]=>
int(1)
}

This example demonstrates that when assigning a reference to a static variable, it's not remembered when you call the &get_instance_ref() function a second time.



Variable variables

Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:

<?php
$a 
'hello';
?>

A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.

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

At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement:

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

produces the exact same output as:

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

i.e. they both produce: hello world.

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as $foo->$bar, then the local scope will be examined for $bar and its value will be used as the name of the property of $foo. This is also true if $bar is an array access.

Curly braces may also be used, to clearly delimit the property name. They are most useful when accessing values within a property that contains an array, when the property name is made of mulitple parts, or when the property name contains characters that are not otherwise valid (e.g. from json_decode() or SimpleXML).

Example #1 Variable property example

<?php
class foo {
    var 
$bar 'I am bar.';
    var 
$arr = array('I am A.''I am B.''I am C.');
    var 
$r   'I am r.';
}

$foo = new foo();
$bar 'bar';
$baz = array('foo''bar''baz''quux');
echo 
$foo->$bar "\n";
echo 
$foo->$baz[1] . "\n";

$start 'b';
$end   'ar';
echo 
$foo->{$start $end} . "\n";

$arr 'arr';
echo 
$foo->$arr[1] . "\n";
echo 
$foo->{$arr}[1] . "\n";

?>

Il precedente esempio visualizzerà:


I am bar.
I am bar.
I am bar.
I am r.
I am B.

Avviso

Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.



Variables From External Sources

HTML Forms (GET and POST)

When a form is submitted to a PHP script, the information from that form is automatically made available to the script. There are many ways to access this information, for example:

Example #1 A simple HTML form

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

Depending on your particular setup and personal preferences, there are many ways to access data from your HTML forms. Some examples are:

Example #2 Accessing data from a simple POST HTML form

<?php 
// Available since PHP 4.1.0

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

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

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

   
echo $HTTP_POST_VARS['username'];

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

   
echo $username;
?>

Using a GET form is similar except you'll use the appropriate GET predefined variable instead. GET also applies to the QUERY_STRING (the information after the '?' in a URL). So, for example, http://www.example.com/test.php?id=3 contains GET data which is accessible with $_GET['id']. See also $_REQUEST and import_request_variables().

Nota:

Superglobal arrays, like $_POST and $_GET, became available in PHP 4.1.0

Nota:

Dots and spaces in variable names are converted to underscores. For example <input name="a.b" /> becomes $_REQUEST["a_b"].

As shown, before PHP 4.2.0 the default value for register_globals was 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!\"). It was deemed that this was needed for escaping for DB insertion circa a decade ago and is a legacy feature now that should be disabled. 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:

Example #3 More complex form variables

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

IMAGE SUBMIT variable names

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

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

When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image. The experienced may note that the actual variable names sent by the browser contains a period rather than an underscore, but PHP converts the period to an underscore automatically.

HTTP Cookies

PHP transparently supports HTTP cookies as defined by » RFC 6265. 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.

Example #4 A setcookie() example

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

Dots in incoming variable names

Typically, PHP does not alter the names of variables when they are passed into a script. However, it should be noted that the dot (period, full stop) is not a valid character in a PHP variable name. For the reason, look at it:

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

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

Determining variable types

Because PHP determines the types of variables and converts them (generally) as needed, it is not always obvious what type a given variable is at any one time. PHP includes several functions which find out what type a variable is, such as: gettype(), is_array(), is_float(), is_int(), is_object(), and is_string(). See also the chapter on Types.




Costanti

Indice dei contenuti

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

Suggerimento

Si può anche consultare Userland Naming Guide.

Example #1 Nomi di costanti validi ed errati

<?php

// Nomi validi
define("FOO",     "something");
define("FOO2",    "something else");
define("FOO_BAR""something more")

// Nomi di costante errati
define("2FOO",    "something");

// Nomi validi, ma da evitare:
// un domani potrebbero essere utilizzati dal PHP per fornire costanti magiche
// e quindi si avrebbero problemi nello script
define("__FOO__""something");

?>

Nota: In questo contesto una lettera è a-z, A-Z e i caratteri ASCII dal 127 al 255 (0x7f-0xff).

Come le superglobals, costante è sempre globale. Si può accedere alle costanti da qualsiasi punto dello script senza tenere conto della visibilità. Per maggiori dettagli sulla visibilità, leggere la sezione variable scope.


Sintassi

È possibile definire una variabile utilizzando la funzione define() o utilizzando la parola chiave const all'esterno di una definizione di una classe in PHP 5.3.0. Una volta definita una costante, non è possibile cambiare il valore o renderlo indefinito.

Le costanti possono contenere solo dati di tipo scalare (boolean, integer, float e string). È possibile definire costanti come resource, ma questo dovrebbe essere evitato, perchè può causare risultati inaspettati.

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 volesse ottenere il nome dinamicamente. 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 una costante indefinita, PHP assume che si intendesse il nome della costante stessa, come se si fosse chiamata come una string (COSTANTE vs "COSTANTE"). Un errore di livello E_NOTICE verrà rilasciato quando questo accade. Leggere anche la voce del manuale sul perchè $foo[bar] è errato (a meno che prima non si 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 né annullate;
  • Le costanti possono essere solo valori scalari;

Example #1 Definizione di costanti

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

Example #2 Definizione di Costanti utilizzando la parola chiave const

<?php
// Funzion in PHP 5.3.0
const CONSTANT 'Hello World';

echo 
CONSTANT;
?>

Nota:

Al contrario di definire costanti utilizzando define(), le costanti definite utilizzando la parola chiave const devono essere dichiarate nella scope del livello superiore perchè sono definite in fase di compilazione. Questo significa che non possono essere dichiarate all'interno di funzioni, cicli oppure istruzioni if.

Leggere anche Le Costanti delle Classi.



Costanti magiche

PHP fornisce un grande numero di costanti predefinite per qualsiasi script che viene eseguito. Molte di queste costanti, comunque, sono create da varie estensioni, e saranno presenti solo quando queste estensioni sono disponibili, sia perchè vengono caricate dinamicamente e sia perchè sono state compilati in PHP.

Ci sono otto costanti magiche che cambiano in base a dove vengono utilizzate. Per esempio, il valore di __LINE__ dipende dalla linea che sta utilizzando nel tuo script. Queste costanti speciali sono case-insensitive e sono le seguenti:

Alcune costanti "magiche" di PHP
Nome Descrizione
__LINE__ Il numero della riga corrente del file.
__FILE__ Il percorso completo e il nome del file. Se utilizzato all'interno di un'inclusione, viene restituito il nome del file incluso. Da PHP 4.0.2, __FILE__ contiene sempre un percorso assoluto con link simbolici risolti, mentre nelle versioni esso conteneva un percorso relativo in alcune circostanze.
__DIR__ La cartella del file. Se utilizzato all'interno di un'inclusione, viene restituita la cartella del file incluso. Questo è equivalente a dirname(__FILE__). Il nome della cartella non ha slash a meno che non sia la directory root. (Aggiunta in PHP 5.3.0.)
__FUNCTION__ Il nome della funzione. (Aggiunta in PHP 4.3.0) Dal PHP 5 questa costante restituisce il nome della funzione come è stato dichiarato (case-sensitive). In PHP 4 il suo valore è sempre in minuscolo.
__CLASS__ Il nome della classe. (Aggiunta in PHP 4.3.0) Da PHP 5 questa costante restituisce il nome della classe come è stato dichiarato (case-sensitive). In PHP 4 il suo valore è sempre in minuscolo. Il nome della classe include il namespace in cui è stata dichiarata (es. Foo\Bar). Notare che da PHP 5.4 __CLASS__ funziona anche nei traits. Quando usata in un metodo trait, __CLASS__ è il nome della classe in cui il trait è usato.
__TRAIT__ Il nome del trait. (Aggiunta in PHP 5.4.0) Da PHP 5.4 questa costante restituisce il trait come è stato dichiarato (case-sensitive). Il nome del trait include il namespace in cui è stato dichiarato (es. Foo\Bar).
__METHOD__ Il nome del metodo della classe. (Aggiunta in PHP 5.0.0) Il nome del metodo è restituito come è stato dichiarato (case-sensitive).
__NAMESPACE__ Il nome del namespace corrente (case-sensitive). Questa costante è definita in fase di compilazione (Aggiunta in PHP 5.3.0).

Vedere anche get_class(), get_object_vars(), file_exists() e function_exists().




Expressions

Expressions are the most important building stones of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value".

The most basic forms of expressions are constants and variables. When you type "$a = 5", you're assigning '5' into $a. '5', obviously, has the value 5, or in other words '5' is an expression with the value of 5 (in this case, '5' is an integer constant).

After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value of 5 as well. If everything works right, this is exactly what will happen.

Slightly more complex examples for expressions are functions. For instance, consider the following function:

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

Assuming you're familiar with the concept of functions (if you're not, take a look at the chapter about functions), you'd assume that typing $c = foo() is essentially just like writing $c = 5, and you're right. Functions are expressions with the value of their return value. Since foo() returns 5, the value of the expression 'foo()' is 5. Usually functions don't just return a static value but compute something.

Of course, values in PHP don't have to be integers, and very often they aren't. PHP supports four scalar value types: integer values, floating point values (float), string values and boolean values (scalar values are values that you can't 'break' into smaller pieces, unlike arrays, for instance). PHP also supports two composite (non-scalar) types: arrays and objects. Each of these value types can be assigned into variables or returned from functions.

PHP takes expressions much further, in the same way many other languages do. PHP is an expression-oriented language, in the sense that almost everything is an expression. Consider the example we've already dealt with, '$a = 5'. It's easy to see that there are two values involved here, the value of the integer constant '5', and the value of $a which is being updated to 5 as well. But the truth is that there's one additional value involved here, and that's the value of the assignment itself. The assignment itself evaluates to the assigned value, in this case 5. In practice, it means that '$a = 5', regardless of what it does, is an expression with the value 5. Thus, writing something like '$b = ($a = 5)' is like writing '$a = 5; $b = 5;' (a semicolon marks the end of a statement). Since assignments are parsed in a right to left order, you can also write '$b = $a = 5'.

Another good example of expression orientation is pre- and post-increment and decrement. Users of PHP and many other languages may be familiar with the notation of variable++ and variable--. These are increment and decrement operators. In PHP, like in C, there are two types of increment - pre-increment and post-increment. Both pre-increment and post-increment essentially increment the variable, and the effect on the variable is identical. The difference is with the value of the increment expression. Pre-increment, which is written '++$variable', evaluates to the incremented value (PHP increments the variable before reading its value, thus the name 'pre-increment'). Post-increment, which is written '$variable++' evaluates to the original value of $variable, before it was incremented (PHP increments the variable after reading its value, thus the name 'post-increment').

A very common type of expressions are comparison expressions. These expressions evaluate to either FALSE or TRUE. PHP supports > (bigger than), >= (bigger than or equal to), == (equal), != (not equal), < (smaller than) and <= (smaller than or equal to). The language also supports a set of strict equivalence operators: === (equal to and same type) and !== (not equal to or not same type). These expressions are most commonly used inside conditional execution, such as if statements.

The last example of expressions we'll deal with here is combined operator-assignment expressions. You already know that if you want to increment $a by 1, you can simply write '$a++' or '++$a'. But what if you want to add more than one to it, for instance 3? You could write '$a++' multiple times, but this is obviously not a very efficient or comfortable way. A much more common practice is to write '$a = $a + 3'. '$a + 3' evaluates to the value of $a plus 3, and is assigned back into $a, which results in incrementing $a by 3. In PHP, as in several other languages like C, you can write this in a shorter way, which with time would become clearer and quicker to understand as well. Adding 3 to the current value of $a can be written '$a += 3'. This means exactly "take the value of $a, add 3 to it, and assign it back into $a". In addition to being shorter and clearer, this also results in faster execution. The value of '$a += 3', like the value of a regular assignment, is the assigned value. Notice that it is NOT 3, but the combined value of $a plus 3 (this is the value that's assigned into $a). Any two-place operator can be used in this operator-assignment mode, for example '$a -= 5' (subtract 5 from the value of $a), '$b *= 7' (multiply the value of $b by 7), etc.

There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:

<?php
$first 
$second $third
?>

If the value of the first subexpression is TRUE (non-zero), then the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.

The following example should help you understand pre- and post-increment and expressions in general a bit better:

<?php
function double($i)
{
    return 
$i*2;
}
$b $a 5;        /* assign the value five into the variable $a and $b */
$c $a++;          /* post-increment, assign original value of $a 
                       (5) to $c */
$e $d = ++$b;     /* pre-increment, assign the incremented value of 
                       $b (6) to $d and $e */

/* at this point, both $d and $e are equal to 6 */

$f double($d++);  /* assign twice the value of $d before
                       the increment, 2*6 = 12 to $f */
$g double(++$e);  /* assign twice the value of $e after
                       the increment, 2*7 = 14 to $g */
$h $g += 10;      /* first, $g is incremented by 10 and ends with the 
                       value of 24. the value of the assignment (24) is 
                       then assigned into $h, and $h ends with the value 
                       of 24 as well. */
?>

Some expressions can be considered as statements. In this case, a statement has the form of 'expr ;' that is, an expression followed by a semicolon. In '$b = $a = 5;', '$a = 5' is a valid expression, but it's not a statement by itself. '$b = $a = 5;' however is a valid statement.

One last thing worth mentioning is the truth value of expressions. In many events, mainly in conditional execution and loops, you're not interested in the specific value of the expression, but only care about whether it means TRUE or FALSE. The constants TRUE and FALSE (case-insensitive) are the two possible boolean values. When necessary, an expression is automatically converted to boolean. See the section about type-casting for details about how.

PHP provides a full and powerful implementation of expressions, and documenting it entirely goes beyond the scope of this manual. The above examples should give you a good idea about what expressions are and how you can construct useful expressions. Throughout the rest of this manual we'll write expr to indicate any valid PHP expression.



Operatori

Indice dei contenuti

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

Gli operatori possono essere raggruppati a seconda del numero di valori che trattano. Gli operatori unari quali richiedono un solo valore, ad esempio !i (l'operatore logico noti) oppure ++ (l'operatore di autoincremento). Gli operatori binari accettano due valor, come i familiari operatori aritmetici + (più) e - (meno), e la maggior parte degli operatori disponibili in PHP ricadono in questa categoria. Infine, esiste un solo operatore ternario, ? :, che accetta tre valori; viene normalmente chiamato "l'operatore ternario" (anche se potrebbe forse essere chiamato più precisamente operatore condizionale).

Una lista completa degli operatore è fornita nella sezione Precedenza degli operatori. Questa sezione spiega anche la precedenza degli operatori e l'associatività, che stabiliscono esattamente come le espressioni contenenti differenti operatori sono valutate ed eseguite.


Precedenza degli operatori

La precedenza di un operatore specifica come esso tenga legate assieme "strettamente" due espressioni. Per esempio, nell'espressione 1 + 5 * 3, la risposta è 16 e non 18 perché l'operatore di moltiplicazione ("*") ha una precedenza più alta rispetto all'operatore di addizione ("+"). Le parentesi possono essere usate per forzare la precedenza, se necessario. Per esempio: (1 + 5) * 3 viene valutata 18.

Quando gli operatori hanno precedenza identica, la loro associatività decide se sono valutati partendo da destra o da sinistra - vedere gli esempi qui sotto.

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.

Precedenza degli operatori
Associatività Operatori Informazioni aggiuntive
non associativi clone new clone e new
sinistra [ array()
destra ++ -- ~ (int) (float) (string) (array) (object) (bool) @ types and increment/decrement
non associativi instanceof tipi
destra ! operatori logici
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

Per operatori con uguale precedenza, l'associazione a sinistra indica che l'espressione viene valutata da sinistra verso destra, e l'associazione destra indica il contrario.

Example #1 Associatività

<?php
$a 
5// (3 * 3) % 5 = 4
$a true true 2// (true ? 0 : true) ? 1 : 2 = 2

$a 1;
$b 2;
$a $b += 3// $a = ($b += 3) -> $a = 5, $b = 5

// mescolare  ++ e + produce un comportamento indefinito
$a 1;
echo ++
$a $a++; // può stampare 4 o 5
?>
Utilizzare le parentesi, anche quando non è strettamente necessarion, pùò spesso aumentare la leggibilità del codice.

Nota:

Sebbene = abbia una precedenza minore rispetto alla maggior parte degli altri operatori, PHP permette comunque espressioni simili alla seguente: if (!$a = foo()), in questo caso l'output di foo() viene inserito in $a.



Operatori aritmetici

Ricordate l'aritmetica di base dalla scuola? Questi operatori funzionano esattamente nello stesso modo.

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 a meno che i due operandi siano interi (oppure stringhe che vengono convertite in interi) e i numeri siano divisibili, nel qual caso viene restituito un valore intero.

Gli operandi del modulo sono convertiti a interi (rimuovendo la parte decimale) prima dell'operazione.

Il risultato dell'operatore modulo % ha lo stesso segno del dividendo - ovvero, il risultato di $a % $b avrà lo stesso segno di $a. Per esempio:

<?php

echo (3)."\n";           // prints 2
echo (% -3)."\n";          // prints 2
echo (-3)."\n";          // prints -2
echo (-% -3)."\n";         // prints -2

?>

Vedere anche le pagine del manuale sulle funzioni matematiche.



Operatori di assegnazione

L'operatore di base dell'assegnazione è "=". Il primo impulso può essere quello di pensare che corrisponda a "uguale a". Invece questo operatore significa che l'operando a sinistra assume il valore dell'espressione a destra (cioè, "assegna il valore a").

Il valore di un'espressione di assegnazione è il valore assegnato. Ovvero il valore di "$a = 3" è 3. Questo permette di fare qualche trucchetto:

<?php

$a 
= ($b 4) + 5// $a è uguale a 9 ora, e $b è stato impostato a 4.

?>

Per gli array, l'assegnazione di un valore a una chiave è ottenuto usando l'operatore "=>". La precedenza di questo operatore è la stessa degli altri operatori d'assegnazione.

In aggiunta all'operatore di base dell'assegnazione, ci sono gli "operatori combinati" per tutta l'aritmetica binaria e gli operatori di stringa che 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, corrispondente a: $a = $a + 5;
$b "Ciao ";
$b .= "come va?"// imposta $b a "Ciao come va?", proprio come $b = $b . "come va?";

?>

Si noti che l'assegnazione copia la variabile originale nella nuova (assegnazione per valore), così i cambiamenti della prima non si verificheranno nell' altra. Ciò può anche avere rilevanza se si ha bisogno di copiare un grande array in un ciclo molto stretto.

Un'eccezione al comportamento standard dell'assegnazione per valore avviene con gliobject, che sono assegnati per riferimento in PHP 5. Gli oggetti possono essere copiati esplicitamente attraverso la keyword clone.

Assegnazione per referimento

L'assegnazione per riferimento è pure supportato, usando la sintassi "$var = &$othervar;. 'Assegnazione per riferimento' significa che entrambe le variabili finiscono con il puntare agli stessi dati, e nulla è copiato.

Example #1 Assegnare per riferimento

<?php
$a 
3;
$b = &$a// $b è un riferimento ad $a

print "$a\n"// stampa 3
print "$b\n"// stampa 3

$a 4// modifica $a

print "$a\n"// stampa 4
print "$b\n"// stampa ugualmente 4, dal momento che $b è un riferimento ad $a, che è
              // stata modificata
?>

Da PHP 5, l'operatore new restituisce automaticamente un riferimento, quindi assegnare il risultato di new per riferimento risulta in un messaggio E6DEPRECATED in PHP 5.3 e successivi, e un messaggio E_STRICT nelle version precedenti.

Per esempio, quesco codice provocherà un avvertimento:

<?php
class {}

/* la prossima linea genera il seguente messaggio di errore:
 * Deprecated: Assigning the return value of new by reference is deprecated in...
 */
$o = &new C;
?>

Ulteriori informazioni sui riferimenti e sul loro uso possono essere trovati nella sezione del manuale Spiegazioni sui riferimenti .



Operatori sui bit

Gli operatori sui bit permettono la valutazione e manipolazione di specifici bit in un valore intero.

Operatori sui bit
Esempio Nome Risultato
$a & $b And Vengono accesi i bit che sono accesi sia in $a che in $b.
$a | $b Or (inclusive or) Vengono accesi i bit che sono accesi o in $a oppure in $b.
$a ^ $b Xor (exclusive or) Vengono accesi i bit che sono accesi in $a o in $b, ma non quelli accesi in entrambe le variabili.
~ $a Not Vengono accesi i bit che sono spenti in $a, e viceversa
$a << $b Shift left Sposta verso sinistra i bit di $a per $b volte (ogni passo significa "moltiplica per due")
$a >> $b Shift right Sposta verso destra i bit di $a per $b volte (ogni passo significa "dividi per due")

Lo spostamento di bit in PHP è aritmetico. I bit spostati al di fuori delle estremità sono scartati. Gli spostamenti a sinistra inseriscono zeri a destra mentre il bit di segno è scartato sulla sinistra, quindi il segno di un operando non è conservato. Gli spostamenti a destra copiano il bit di segno sulla sinistra, quindi il segno di un operando è conservato.

Utilizzare le parentesi per assicurare la precedenza desiderata. Per esempio, $a & $b == true valuta l'equivalenza e poi l'operatore and; mentre ($a & $b) == true valuta l'operatore and e poi l'equivalenza.

Prestare attenzione alle conversioni tra tipi di dato. Se entrambi gli operandi sono stringhe, l'operatore bit lavorarà sui valori ASCII dei caratter.

L'opzione ini error_reporting di PHP usa valori imappati sui bit,
fornendo quindi una dimostrazione reale dello spegnimento 
dei bit. Per mostrare tutti gli errori, eccettuati gli avvisi,
le istruzioni del file php.ini dicono di usare:
E_ALL & ~E_NOTICE
      

Si prende il valore di E_ALL:
00000000000000000111011111111111
Quindi quello di E_NOTICE...
00000000000000000000000000001000
... e lo si inverte con ~:
11111111111111111111111111110111
infine, si usa AND (&) pre trovare i bit che sono accesi
in entrambi i valori:
00000000000000000111011111110111
      

Un altro metodo per ottenere questo risultato è usare XOR (^)
per trovare i bit che sono accesi solo in uno dei due operandi:
E_ALL ^ E_NOTICE
      

error_reporting può essere usata anche per dimostrare come accendere i bit.
Il modo per mostrare solo gli errori e gli errori recuperabili è:
E_ERROR | E_RECOVERABLE_ERROR
      

Questo processo combina E_ERROR
00000000000000000000000000000001
e
00000000000000000001000000000000
usando l'operatore OR (|)
per recuperare i bit accesi in entrambi i valori:
00000000000000000001000000000001
      

Example #1 Operazioni AND, OR e XOR su interi

<?php
/*
 * Ignorare la sezione iniziale,
 * server solo a formattare per rendere più leggibile il risultato.
 */

$format '(%1$2d = %1$04b) = (%2$2d = %2$04b)'
        
' %3$s (%4$2d = %4$04b)' "\n";

echo <<<EOH
 ---------     ---------  -- ---------
 risultato     valore     op test
 ---------     ---------  -- ---------
EOH;


/*
 * Ecco gli esempi.
 */

$values = array(01248);
$test 4;

echo 
"\n Bitwise AND \n";
foreach (
$values as $value) {
    
$result $value $test;
    
printf($format$result$value'&'$test);
}

echo 
"\n Bitwise Inclusive OR \n";
foreach (
$values as $value) {
    
$result $value $test;
    
printf($format$result$value'|'$test);
}

echo 
"\n Bitwise Exclusive OR (XOR) \n";
foreach (
$values as $value) {
    
$result $value $test;
    
printf($format$result$value'^'$test);
}
?>

Il precedente esempio visualizzerà:

 ---------     ---------  -- ---------
 risultato     valore     op test
 ---------     ---------  -- ---------
 Bitwise AND
( 0 = 0000) = ( 0 = 0000) & ( 5 = 0101)
( 1 = 0001) = ( 1 = 0001) & ( 5 = 0101)
( 0 = 0000) = ( 2 = 0010) & ( 5 = 0101)
( 4 = 0100) = ( 4 = 0100) & ( 5 = 0101)
( 0 = 0000) = ( 8 = 1000) & ( 5 = 0101)

 Bitwise Inclusive OR
( 5 = 0101) = ( 0 = 0000) | ( 5 = 0101)
( 5 = 0101) = ( 1 = 0001) | ( 5 = 0101)
( 7 = 0111) = ( 2 = 0010) | ( 5 = 0101)
( 5 = 0101) = ( 4 = 0100) | ( 5 = 0101)
(13 = 1101) = ( 8 = 1000) | ( 5 = 0101)

 Bitwise Exclusive OR (XOR)
( 5 = 0101) = ( 0 = 0000) ^ ( 5 = 0101)
( 4 = 0100) = ( 1 = 0001) ^ ( 5 = 0101)
( 7 = 0111) = ( 2 = 0010) ^ ( 5 = 0101)
( 1 = 0001) = ( 4 = 0100) ^ ( 5 = 0101)
(13 = 1101) = ( 8 = 1000) ^ ( 5 = 0101)

Example #2 Operazioni XOR su stringhe

<?php
echo 12 9// Ritorna '5'

echo "12" "9"// Ritorna il carattere Backspace (ascii 8)
                 // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8

echo "hallo" "hello"// Ritorna i valori ascii #0 #4 #0 #0 #0
                        // 'a' ^ 'e' = #4

echo "3"// Ritorna 1
              // 2 ^ ((int)"3") == 1

echo "2" 3// Ritorna 1
              // ((int)"2") ^ 3 == 1
?>

Example #3 Spostamento di bit su interi

<?php
/*
 * Ecco gli esempi.
 */

echo "\n--- SPOSTAMENTO A DESTRA SU INTERI POSITIVI ---\n";

$val 4;
$places 1;
$res $val >> $places;
p($res$val'>>'$places'copia del bit di segno inserito a sinistra');

$val 4;
$places 2;
$res $val >> $places;
p($res$val'>>'$places);

$val 4;
$places 3;
$res $val >> $places;
p($res$val'>>'$places'i bit escono dal lato destro');

$val 4;
$places 4;
$res $val >> $places;
p($res$val'>>'$places'come sopra; non c'è spostamento oltre lo 0');


echo "\n--- SPOSTAMENTO A SINISTRA SU INTERI NEGATIVI ---\n";

$val = -4;
$places = 1;
$res = $val >> $places;
p($res, $val, '
>>', $places, 'copia del bit di segno inserito a sinistra');

$val = -4;
$places = 2;
$res = $val >> $places;
p($res, $val, '
>>', $places, 'i bit escono dal lato destro');

$val = -4;
$places = 3;
$res = $val >> $places;
p($res, $val, '
>>', $places, 'come sopranon c'è spostamento oltre il -1');


echo 
"\n--- SPOSTAMENTO A SINISTRA SU INTERI POSITIVI ---\n";

$val 4;
$places 1;
$res $val << $places;
p($res$val'<<'$places'zeri inseriti a destra');

$val 4;
$places = (PHP_INT_SIZE 8) - 4;
$res $val << $places;
p($res$val'<<'$places);

$val 4;
$places = (PHP_INT_SIZE 8) - 3;
$res $val << $places;
p($res$val'<<'$places'i bit di segno sono spostati');

$val 4;
$places = (PHP_INT_SIZE 8) - 2;
$res $val << $places;
p($res$val'<<'$places'i bit escono dal lato sinistro');


echo 
"\n--- SPOSTAMENTO A SINISTRA SU INTERI NEGATIVI ---\n";

$val = -4;
$places 1;
$res $val << $places;
p($res$val'<<'$places'zeri inseriti a destra');

$val = -4;
$places = (PHP_INT_SIZE 8) - 3;
$res $val << $places;
p($res$val'<<'$places);

$val = -4;
$places = (PHP_INT_SIZE 8) - 2;
$res $val << $places;
p($res$val'<<'$places'i bit escono dal lato sinistro, incluso il bit di segno');


/*
 * Ignorare questa sezione finale,
 * server solo a formattare per rendere più leggibile il risultato.
 */

function p($res$val$op$places$note '') {
    
$format '%0' . (PHP_INT_SIZE 8) . "b\n";

    
printf("Espressione: %d = %d %s %d\n"$res$val$op$places);

    echo 
" Decimale:\n";
    
printf("  val=%d\n"$val);
    
printf("  res=%d\n"$res);

    echo 
" Binario:\n";
    
printf('  val=' $format$val);
    
printf('  res=' $format$res);

    if (
$note) {
        echo 
" NOTA: $note\n";
    }

    echo 
"\n";
}
?>

Risultato del precedente esempio su macchine a 32 bit:


--- SPOSTAMENTO A DESTRA SU INTERI POSITIVI ---
Espressione: 2 = 4 >> 1
 Decimale:
  val=4
  res=2
 Binario:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000010
 NOTA: copia del bit di segno inserito a sinistra

Espressione: 1 = 4 >> 2
 Decimale:
  val=4
  res=1
 Binario:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000001

Espressione: 0 = 4 >> 3
 Decimale:
  val=4
  res=0
 Binario:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000000
 NOTA: i bit escono dal lato destro

Espressione: 0 = 4 >> 4
 Decimale:
  val=4
  res=0
 Binario:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000000
 NOTA: come sopra; non c'è spostamento oltre lo 0


--- SPOSTAMENTO A DESTRA SU INTERI NEGATIVI ---
Espressione: -2 = -4 >> 1
 Decimale:
  val=-4
  res=-2
 Binario:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111110
 NOTA: copia del bit di segno inserito a sinistra

Espressione: -1 = -4 >> 2
 Decimale:
  val=-4
  res=-1
 Binario:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111111
 NOTA: i bit escono dal lato destro

Espressione: -1 = -4 >> 3
 Decimale:
  val=-4
  res=-1
 Binario:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111111
 NOTA: come sopra; non c'è spostamento oltre il -1


--- SPOSTAMENTO A SINISTRA SU INTERI POSITIVI ---
Espressione: 8 = 4 << 1
 Decimale:
  val=4
  res=8
 Binario:
  val=00000000000000000000000000000100
  res=00000000000000000000000000001000
 NOTA: zeri inseriti a destra

Espressione: 1073741824 = 4 << 28
 Decimale:
  val=4
  res=1073741824
 Binario:
  val=00000000000000000000000000000100
  res=01000000000000000000000000000000

Espressione: -2147483648 = 4 << 29
 Decimale:
  val=4
  res=-2147483648
 Binario:
  val=00000000000000000000000000000100
  res=10000000000000000000000000000000
 NOTA:i bit di segno sono spostati

Espressione: 0 = 4 << 30
 Decimale:
  val=4
  res=0
 Binario:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000000
 NOTA: i bit escono dal lato sinistro


--- SPOSTAMENTO A SINISTRA SU INTERI NEGATIVI ---
Espressione: -8 = -4 << 1
 Decimale:
  val=-4
  res=-8
 Binario:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111000
 NOTA: zeri inseriti a destra

Espressione: -2147483648 = -4 << 29
 Decimale:
  val=-4
  res=-2147483648
 Binario:
  val=11111111111111111111111111111100
  res=10000000000000000000000000000000

Espressione: 0 = -4 << 30
 Decimale:
  val=-4
  res=0
 Binario:
  val=11111111111111111111111111111100
  res=00000000000000000000000000000000
 NOTA: i bit escono dal lato sinistro, incluso il bit di segno

Risultato del precedente esempio su macchine a 64 bit:


--- SPOSTAMENTO A DESTRA SU INTERI POSITIVI ---
Espressione: 2 = 4 >> 1
 Decimale:
  val=4
  res=2
 Binario:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000010
 NOTA: copia del bit di segno inserito a sinistra

Espressione: 1 = 4 >> 2
 Decimale:
  val=4
  res=1
 Binario:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000001

Espressione: 0 = 4 >> 3
 Decimale:
  val=4
  res=0
 Binario:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTA: i bit escono dal lato destro

Espressione: 0 = 4 >> 4
 Decimale:
  val=4
  res=0
 Binario:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTA: come sopra; non c'è spostamento oltre lo 0


--- SPOSTAMENTO A DESTRA SU INTERI NEGATIVI ---
Espressione: -2 = -4 >> 1
 Decimale:
  val=-4
  res=-2
 Binario:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111110
 NOTA: copia del bit di segno inserito a sinistra

Espressione: -1 = -4 >> 2
 Decimale:
  val=-4
  res=-1
 Binario:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111111
 NOTA: i bit escono dal lato destro

Espressione: -1 = -4 >> 3
 Decimale:
  val=-4
  res=-1
 Binario:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111111
 NOTA: come sopra; non c'è spostamento oltre il -1


--- SPOSTAMENTO A SINISTRA SU INTERI POSITIVI ---
Espressione: 8 = 4 << 1
 Decimale:
  val=4
  res=8
 Binario:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000001000
 NOTA: zeri inseriti a destra

Espressione: 4611686018427387904 = 4 << 60
 Decimale:
  val=4
  res=4611686018427387904
 Binario:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0100000000000000000000000000000000000000000000000000000000000000

Espressione: -9223372036854775808 = 4 << 61
 Decimale:
  val=4
  res=-9223372036854775808
 Binario:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=1000000000000000000000000000000000000000000000000000000000000000
 NOTA: i bit di segno sono spostati

Espressione: 0 = 4 << 62
 Decimale:
  val=4
  res=0
 Binario:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTA: i bit escono dal lato sinistro


--- SPOSTAMENTO A SINISTRA SU INTERI NEGATIVI ---
Espressione: -8 = -4 << 1
 Decimale:
  val=-4
  res=-8
 Binario:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111000
 NOTA: zeri inseriti a destra

Espressione: -9223372036854775808 = -4 << 61
 Decimale:
  val=-4
  res=-9223372036854775808
 Binario:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1000000000000000000000000000000000000000000000000000000000000000

Espressione: 0 = -4 << 62
 Decimale:
  val=-4
  res=0
 Binario:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTA: i bit escono dal lato sinistro, incluso il bit di segno

Avviso

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. Utilizzare le funzioni dell'estensione gmp per manipolazioni di bit su numeri più grandi di PHP_INT_MAX.

vedere anche pack(), unpack(), gmp_and(), gmp_or(), gmp_xor(), gmp_testbit(), gmp_clrbit()



Operatori di confronto

Gli operatori di confronto, come suggerisce il loro nome, permettono di confrontare due valori. Può essere interessante vedere la tabella di raffronto dei tipi, dato che mostra esempi di vari confronti tra i tipi di variabili.

Operatori di confronto
Esempio Nome Risultato
$a == $b Uguale TRUE se $a è uguale a $b dopo la manipolazione dei tipi.
$a === $b Identico TRUE se $a è uguale a $b, ed sono dello stesso tipo.
$a != $b Diversi TRUE se $a è diverso da $b dopo la manipolazione dei tipi.
$a <> $b Diversi TRUE se $a è diverso da $b dopo la manipolazione dei tipi.
$a !== $b Non identici TRUE se $a è diverso da $b, o se non sono dello stesso tipo.
$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 confrontano interi con stringhe o il confronto coinvolge stringhe numeriche, ogni stringa viene convertita in numero e il confronto è effettuato sui numeri. Queste regole valgono anche per l'istruzione switch. La conversione di tipo non avviene quando il confronto è === o !== dal momento che ciò include anche il confronto del tipo.

<?php
var_dump
(== "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> 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 operandi utilizzati differiscono, il confronto viene svolto nell'ordine indicato della seguente tabella.

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, classi differenti non sono confrontabili, classi uguali confrontano le proprietà nello stesso modo delle matrici (PHP 4), PHP 5 ha il suo metodo di confronto.
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

Example #1 Trascrizione del confronto standard tra matrici

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

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

Avviso

Confronto di numeri in virgola mobile

A causa del modo in cui i float sono rappresentati internamente al PHP, non si dovrebbe esaminare l'eguaglianza di due float.

Per maggior informazioni, fare riferimento alla documentazione del tipo float.

Operatore ternario

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

Example #2 Assegnazione di un valore di default

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

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

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

Dal PHP 5.3, è possibile tralasciare l'elemento centrale dell'operatore ternario. L'espressione espressione1 ?: espressione3 restituisce espressione1 se espressione1 è TRUE, e espressione3 in caso contrario.

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

Nota:

si raccomanda di non sovrapporre le espressioni ternarie. Il comportamento di PHP quando si usa più di un operatore ternario nella stessa istruzione non è ovvio:

Example #3 Comportamento ternario non ovvio

<?php
// a prima vista, questa istruzione dovrebbe restituire 'true'
echo (true?'true':false?'t':'f');

// invece, il risultato è 't'
// perché le espressioni ternarie sono valutate da sinistra a destra

// quanti segue è una versione più chiara dello stesso codice
echo ((true 'true' false) ? 't' 'f');

// si può notare che la prima espressione è 'true', che
// a sua volta diventa (bool)true, e quindi restituisce il ramo true della
// seconda espressione ternaria.
?>



Operatori di controllo errori

PHP supporta un operatore di controllo dell'errore: il carattere at (@). Quando prefisso ad una espressione in PHP, qualunque messaggio di errore che possa essere generato da quella espressione sarà ignorato.

Se è stata assegnata una funzione personalizzata di gestione degli errori con set_error_handler() questa verrà comunque chiamata, ma questa funzione può (e dovrebbe) chiamare error_reporting() che restituirà 0 quando la chiamata che ha attivato l'errore era preceduta da un @.

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, quindi va controllata spesso per poterla utilizzare.

<?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 si può ottenere il valore di qualcosa, allora si può anteporre ad esso l'operatore @. Per esempio, si può anteporre a variabili, funzioni e chiamate ad include, costanti, e così via. non si può anteporre 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.

Avviso

In effetti, il prefisso operatore di controllo dell'errore "@" disabiliterà la restituzione di errori per errori critici che interrompono l'esecuzione dello script. Tra le altre cose, questo significa che se si usa "@" per sopprimere errori da una certa funzione ed essa non è disponibile oppure è stata scritta male, lo script terminerà senza dare indicazioni sul motivo.



Operatori di esecuzione

PHP supporta un operatore di esecuzione: backticks (``). Si noti che non sono apostrofi o apici! PHP cercherà di eseguire il contenuto dei backticks come comando di shell; sarà restituito l'output (ovvero, non sarà semplicemente inviato all'output, ma potrà essere assegnato ad una variabile). L'uso dell'operatore backtick è identico alla funzione shell_exec().

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

Nota:

L'operatore backtick è disabilitato quando è abilitata modalità sicura oppure quando è disabilitata shell_exec().

Nota:

Diversamente da altri linguaggi, i backtick non posso essere usati all'interno di stringhe delimitate da doppi apici.

Vedere anche la sezione del manuale Funzioni per l'esecuzione di programmi, popen(), proc_open() e Utilizzo del PHP da linea di comando.



Operatori di incremento/decremento

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

Nota: Gli operatori di incremento e decremento non agiscono sui valori boolean. Anche decrementare il valore NULL non ha effetti, ma incrementarlo darà come risultato 1.

Operatori di incremento/decremento
Esempio Nome Effetto
++$a Pre-incremento Incrementa $a di una unità, quindi restituisce $a.
$a++ Post-incremento Restituisce $a, quindi incrementa $a di una unità.
--$a Pre-decremento Decrementa $a di una unità, quindi restituisce $a.
$a-- Post-decremento Restituisce $a, quindi decrementa $a di una unità.

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 PHP e Perl $a = 'Z'; $a++; modifica $a in 'AA', mentre in C a = 'Z'; a++; modifica a in '[' (il valore ASCII di 'Z' è 90, quello di '[' è 91). Si noti che le variabili carattere possono essere incrementate ma non decrementate e anche in questo caso solo i caratteri ASCII (a-z e A-Z) sono supportati. Incrementare/decrementare altre variabili di carattere non ha effetto, la stringa originale non viene modificata.

Example #1 Operazioni aritmetiche su variabili carattere

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

Il precedente esempio visualizzerà:

X
Y
Z
AA
AB
AC

Incrementare o decrementare valori booleani non ha effetto.



Operatori logici

Operatori logici
Esempio Nome Risultato
$a and $b And TRUE se $a e $b sono entrambe TRUE.
$a or $b Or TRUE se $a o $b è TRUE.
$a xor $b Xor TRUE se $a o $b è TRUE, ma non entrambe.
! $a Not TRUE se $a non è TRUE.
$a && $b And TRUE se $a e $b sono entrambe TRUE.
$a || $b Or TRUE se $a o $b è TRUE.

La ragione per le due differenti variazioni degli operatori "and" e "or" è che operano con differenti precedenze. (Vedere Precedenza degli operatori.)

Example #1 Dimostrazione degli operatori logici

<?php

// --------------------
// foo() non viene mai chiamata in quanto gli operatori sono in corto-circuito

$a = (false && foo());
$b = (true  || foo());
$c = (false and foo());
$d = (true  or  foo());

// --------------------
// "||" ha una precedenza maggiore rispetto a "or"

// Il risultato dell'espressione (false || true) è assegnato a $e
// Funziona come: ($e = (false || true))
$e false || true;

// La costante false è assegnata a $f e quindi true è ignorato
// Funziona come: (($f = false) or true)
$f false or true;

var_dump($e$f);

// --------------------
// "&&" ha una precesenza maggiore rispetto a "and"

// Il risultato dell'espressione (true && false) è assegnato a $g
// Funziona come: ($g = (true && false))
$g true && false;

// La costante true è assegnata a $h e quindi false è ignorato
// Funziona come: (($h = true) and false)
$h true and false;

var_dump($g$h);
?>

Il precedente esempio visualizzerà qualcosa simile a:

bool(true)
bool(false)
bool(false)
bool(true)


Operatori di stringa

Ci sono due operatori di stringa. Il primo è l'operatore di concatenazione ('.'), che restituisce la concatenazione dei suoi argomenti di destra e di sinistra. Il secondo è l'operatore di assegnazione concatenato ('.='), che accoda l'argomento sul lato destro all'argomento sul lato sinistro. Vedere Operatori di assegnazione per maggiori informazioni.

<?php
$a 
"Ciao ";
$b $a "Mondo!"// ora $b contiene "Ciao Mondo!"

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

Vedere anche le sezioni Stringhe e Funzioni per le stringhe nel manuale.



Operatori per matrici

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 + restituisce la matrice di destra aggiunta a quella di sinistra; per le chiavi esistenti in entrambe le matrici, vengono usati gli elementi della matrice di sinistra, e gli elementi duplicati in quella di destra sono ignorati.

<?php
$a 
= array("a" => "apple""b" => "banana");
$b = array("a" => "pear""b" => "strawberry""c" => "cherry");

$c $a $b// Unione di $a e $b
echo "Union of \$a and \$b: \n";
var_dump($c);

$c $b $a// Unione di $b e $a
echo "Union of \$b and \$a: \n";
var_dump($c);
?>
Una volta eseguito, lo script visualizzerà:
Union of $a and $b:
array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}
Union of $b and $a:
array(3) {
  ["a"]=>
  string(4) "pear"
  ["b"]=>
  string(10) "strawberry"
  ["c"]=>
  string(6) "cherry"
}

Gli elementi di una matrice sono uguali nel confronto se hanno le stesse chiavi e gli stessi valori.

Example #1 Confrontare le matrici

<?php
$a 
= array("apple""banana");
$b = array(=> "banana""0" => "apple");

var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>

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



Operatori di tipi

instanceof è utilizzato per determinare se una variabile PHP è un oggetto istanza di una certa classe:

Example #1 Utilizzo di instanceof con le classi

<?php
class MyClass
{
}

class 
NotMyClass
{
}
$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof NotMyClass);
?>

Il precedente esempio visualizzerà:

bool(true)
bool(false)

instanceof può essere usato anche per determinare se una variabile è un oggetto istanziato da una classe che eredita da una classe parente:

Example #2 Utilizzo di instanceof con le classi ereditate

<?php
class ParentClass
{
}

class 
MyClass extends ParentClass
{
}

$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof ParentClass);
?>

Il precedente esempio visualizzerà:

bool(true)
bool(true)

Al fine di controllare se un oggetto non è un instanceof di una classe, si può usare l'operatore logico not .

Example #3 Utilizzo di instanceof per controllare se un oggetto non è un'instanceof di una classe

<?php
class MyClass
{
}

$a = new MyClass;
var_dump(!($a instanceof stdClass));
?>

Il precedente esempio visualizzerà:

bool(true)

Infine, instanceof può essere usato anche per deretmnare se una variable è un oggetto istanziato da una classe che implementa una interfaccia:

Example #4 Utilizzo di instanceof per una classe

<?php
interface MyInterface
{
}

class 
MyClass implements MyInterface
{
}

$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof MyInterface);
?>

Il precedente esempio visualizzerà:

bool(true)
bool(true)

Anche se instanceof è normalmente usata con un nome di classe letterale, può essere usata con un altro oggetto o con una variabile stringa:

Example #5 Utilizzo di instanceof con altre variabili

<?php
interface MyInterface
{
}

class 
MyClass implements MyInterface
{
}

$a = new MyClass;
$b = new MyClass;
$c 'MyClass';
$d 'NotMyClass';

var_dump($a instanceof $b); // $b è un oggetto di classe MyClass
var_dump($a instanceof $c); // $c è la stringa 'MyClass'
var_dump($a instanceof $d); // $d è la stringa 'NotMyClass'
?>

Il precedente esempio visualizzerà:

bool(true)
bool(true)
bool(false)

instanceof non genera errori se la variabile che viene controllata non è un oggetto, ma ritorna semplicemente FALSE. Le costanti non sono comunque ammesse.

Example #6 Utilizzo di instanceof per controllare altre variabili

<?php
$a 
1;
$b NULL;
$c imagecreate(55);
var_dump($a instanceof stdClass); // $a è un integer
var_dump($b instanceof stdClass); // $b è NULL
var_dump($c instanceof stdClass); // $c è una risorsa
var_dump(FALSE instanceof stdClass);
?>

Il precedente esempio visualizzerà:

bool(false)
bool(false)
bool(false)
PHP Fatal error:  instanceof expects an object instance, constant given

Ci sono alcune trappole da evitare. Prima di PHP 5.1.0, instanceof chiama __autoload() se il nome della classe non esiste. Inoltre, se la classe non è stata caricata, viene generato un errore fatale. Ciò può essere evitato usando un riferimento dinamico alla classe, o una variabile stringa che contenga il nome della classe:

Example #7 Evitare richerce del nome della classe ed errori fatali con instanceof in PHP 5.0

<?php
$d 
'NotMyClass';
var_dump($a instanceof $d); // l'errore fatale non avviene
?>

Il precedente esempio visualizzerà:

bool(false)

L'operatore instanceof è stato introdotto in PHP 5. Prima di questo si utilizzava is_a(), ma ora is_a() è deprecata in favore di instanceof. Si noti che dal PHP 5.3.0, is_a() non è più deprecata.

Vedere anche get_class() e is_a().




Strutture di controllo

Indice dei contenuti


Introduzione

Qualsiasi script PHP è costituito da una serie di istruzioni. Una istruzione può essere un'assegnazione, una chiamata di funzione, un loop, una istruzione condizionale che non fa nulla (istruzione vuota). Le istruzioni terminano con un punto e virgola. Inoltre, le istruzioni si possono raggruppare in blocchi di istruzioni racchiudendole tra parentesi graffa. Un gruppo di istruzioni è, a sua volta, un'istruzione. Il presente capitolo descrive i differenti tipi di istruzioni.



if

(PHP 4, PHP 5)

The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C:

if (expr)
  statement

As described in the section about expressions, expression is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it. More information about what values evaluate to FALSE can be found in the 'Converting to boolean' section.

The following example would display a is bigger than b if $a is bigger than $b:

<?php
if ($a $b)
  echo 
"a is bigger than b";
?>

Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group. For example, this code would display a is bigger than b if $a is bigger than $b, and would then assign the value of $a into $b:

<?php
if ($a $b) {
  echo 
"a is bigger than b";
  
$b $a;
}
?>

If statements can be nested infinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program.



else

(PHP 4, PHP 5)

Often you'd want to execute a statement if a certain condition is met, and a different statement if the condition is not met. This is what else is for. else extends an if statement to execute a statement in case the expression in the if statement evaluates to FALSE. For example, the following code would display a is greater than b if $a is greater than $b, and a is NOT greater than b otherwise:

<?php
if ($a $b) {
  echo 
"a is greater than b";
} else {
  echo 
"a is NOT greater than b";
}
?>
The else statement is only executed if the if expression evaluated to FALSE, and if there were any elseif expressions - only if they evaluated to FALSE as well (see elseif).



elseif/else if

(PHP 4, PHP 5)

elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE. For example, the following code would display a is bigger than b, a equal to b or a is smaller than b:

<?php
if ($a $b) {
    echo 
"a is bigger than b";
} elseif (
$a == $b) {
    echo 
"a is equal to b";
} else {
    echo 
"a is smaller than b";
}
?>

There may be several elseifs within the same if statement. The first elseif expression (if any) that evaluates to TRUE would be executed. In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior.

The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.

Nota: Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error.

<?php

/* Incorrect Method: */
if($a $b):
    echo 
$a." is greater than ".$b;
else if(
$a == $b): // Will not compile.
    
echo "The above line causes a parse error.";
endif;


/* Correct Method: */
if($a $b):
    echo 
$a." is greater than ".$b;
elseif(
$a == $b): // Note the combination of the words.
    
echo $a." equals ".$b;
else:
    echo 
$a." is neither greater than or equal to ".$b;
endif;

?>



Sintassi alternativa per le strutture di controllo

(PHP 4, PHP 5)

PHP offre una sintassi alternativa per alcune delle sue strutture di controllo, ovvero: if, while, for, foreach, e switch. In ognuno di questi casi, l'approccio di base della sintassi alternativa è quello di cambiare la parentesi graffa aperta con il segno di duepunti (:) e la parentesi graffa chiusa rispettivamente con endif;, endwhile;, endfor;, endforeach;, o endswitch;.

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

Nell'esempio presentato, il blocco HTML "A è uguale a 5" è inserito all'interno in un blocco if scritto con la sintassi alternativa. Il blocco HTML sarà visualizzato solo se $a è uguale a 5.

La sintassi alternativa si applica nello stesso modo anche ad else e ad elseif. Quanto segue è un esempio della struttura if con sezioni elseif ed else nel formato alternativo:

<?php
if ($a == 5):
    echo 
"a è uguale a 5";
    echo 
"...";
elseif (
$a == 6):
    echo 
"a è uguale a 6";
    echo 
"!!!";
else:
    echo 
"a è diverso sia da 5 che da 6";
endif;
?>

Nota:

L'utilizzo delle due sintassi all'interno dello stesso blocco non è supportato.

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



while

(PHP 4, PHP 5)

I cicli while sono i più semplici tipi di loop in PHP. Questi cicli si comportano esattamente come nel C. La forma base di un'istruzione while è:

while (expr)
    statement

The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once.

Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax:

while (expr):
    statement
    ...
endwhile;

Gli esempi seguenti sono identici, ed entrambi stampano i numeri da 1 a 10:

<?php
/* example 1 */

$i 1;
while (
$i <= 10) {
    echo 
$i++;  /* the printed value would be
                   $i before the increment
                   (post-increment) */
}

/* example 2 */

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



do-while

(PHP 4, PHP 5)

do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular while loops is that the first iteration of a do-while loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately).

There is just one syntax for do-while loops:

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

The above loop would run one time exactly, since after the first iteration, when truth expression is checked, it evaluates to FALSE ($i is not bigger than 0) and the loop execution ends.

Advanced C users may be familiar with a different usage of the do-while loop, to allow stopping execution in the middle of code blocks, by encapsulating them with do-while (0), and using the break statement. The following code fragment demonstrates this:

<?php
do {
    if (
$i 5) {
        echo 
"i is not big enough";
        break;
    }
    
$i *= $factor;
    if (
$i $minimum_limit) {
        break;
    }
   echo 
"i is ok";

    
/* process i */

} while (0);
?>

Don't worry if you don't understand this right away or at all. You can code scripts and even powerful scripts without using this 'feature'. Since PHP 5.3.0, it is possible to use goto operator instead of this hack.



for

(PHP 4, PHP 5)

for loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is:

for (expr1; expr2; expr3)
    statement

The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.

In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.

At the end of each iteration, expr3 is evaluated (executed).

Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression.

Consider the following examples. All of them display the numbers 1 through 10:

<?php
/* example 1 */

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

/* example 2 */

for ($i 1; ; $i++) {
    if (
$i 10) {
        break;
    }
    echo 
$i;
}

/* example 3 */

$i 1;
for (; ; ) {
    if (
$i 10) {
        break;
    }
    echo 
$i;
    
$i++;
}

/* example 4 */

for ($i 1$j 0$i <= 10$j += $i, print $i$i++);
?>

Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in for loops comes in handy in many occasions.

PHP also supports the alternate "colon syntax" for for loops.

for (expr1; expr2; expr3):
    statement
    ...
endfor;

It's a common thing to many users to iterate through arrays like in the example below.

<?php
/*
 * This is an array with some data we want to modify
 * when running through the for loop.
 */
$people = array(
    array(
'name' => 'Kalle''salt' => 856412),
    array(
'name' => 'Pierre''salt' => 215863)
);

for(
$i 0$i count($people); ++$i) {
    
$people[$i]['salt'] = mt_rand(000000999999);
}
?>

The above code can be slow, because the array size is fetched on every iteration. Since the size never changes, the loop be easily optimized by using an intermediate variable to store the size instead of repeatedly calling count():

<?php
$people 
= array(
    array(
'name' => 'Kalle''salt' => 856412),
    array(
'name' => 'Pierre''salt' => 215863)
);

for(
$i 0$size count($people); $i $size; ++$i) {
    
$people[$i]['salt'] = mt_rand(000000999999);
}
?>



foreach

(PHP 4, PHP 5)

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:

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

The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).

The second form will additionally assign the current element's key to the $key variable on each iteration.

It is possible to customize object iteration.

Nota:

When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.

As foreach relies on the internal array pointer, changing it within the loop may lead to unexpected behavior.

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

<?php
$arr 
= array(1234);
foreach (
$arr as &$value) {
    
$value $value 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

Referencing $value is only possible if the iterated array can be referenced (i.e. if it is a variable). The following code won't work:

<?php
foreach (array(1234) as &$value) {
    
$value $value 2;
}
?>

Avviso

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

Nota:

foreach does not support the ability to suppress error messages using '@'.

You may have noticed that the following are functionally identical:

<?php
$arr 
= array("one""two""three");
reset($arr);
while (list(, 
$value) = each($arr)) {
    echo 
"Value: $value<br />\n";
}

foreach (
$arr as $value) {
    echo 
"Value: $value<br />\n";
}
?>

The following are also functionally identical:

<?php
$arr 
= array("one""two""three");
reset($arr);
while (list(
$key$value) = each($arr)) {
    echo 
"Key: $key; Value: $value<br />\n";
}

foreach (
$arr as $key => $value) {
    echo 
"Key: $key; Value: $value<br />\n";
}
?>

Some more examples to demonstrate usage:

<?php
/* foreach example 1: value only */

$a = array(12317);

foreach (
$a as $v) {
    echo 
"Current value of \$a: $v.\n";
}

/* foreach example 2: value (with its manual access notation printed for illustration) */

$a = array(12317);

$i 0/* for illustrative purposes only */

foreach ($a as $v) {
    echo 
"\$a[$i] => $v.\n";
    
$i++;
}

/* foreach example 3: key and value */

$a = array(
    
"one" => 1,
    
"two" => 2,
    
"three" => 3,
    
"seventeen" => 17
);

foreach (
$a as $k => $v) {
    echo 
"\$a[$k] => $v.\n";
}

/* foreach example 4: multi-dimensional arrays */
$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";
    }
}

/* foreach example 5: dynamic arrays */

foreach (array(12345) as $v) {
    echo 
"$v\n";
}
?>

Unpacking nested arrays with list()

(PHP 5 >= 5.5.0)

PHP 5.5 added the ability to iterate over an array of arrays and unpack the nested array into loop variables by providing a list() as the value.

For example:

<?php
$array 
= [
    [
12],
    [
34],
];

foreach (
$array as list($a$b)) {
    
// $a contains the first element of the nested array,
    // and $b contains the second element.
    
echo "A: $a; B: $b\n";
}
?>

Il precedente esempio visualizzerà:

A: 1; B: 2
A: 3; B: 4

You can provide fewer elements in the list() than there are in the nested array, in which case the leftover array values will be ignored:

<?php
$array 
= [
    [
12],
    [
34],
];

foreach (
$array as list($a)) {
    
// Note that there is no $b here.
    
echo "$a\n";
}
?>

Il precedente esempio visualizzerà:

1
3

A notice will be generated if there aren't enough array elements to fill the list():

<?php
$array 
= [
    [
12],
    [
34],
];

foreach (
$array as list($a$b$c)) {
    echo 
"A: $a; B: $b; C: $c\n";
}
?>

Il precedente esempio visualizzerà:


Notice: Undefined offset: 2 in example.php on line 7
A: 1; B: 2; C: 

Notice: Undefined offset: 2 in example.php on line 7
A: 3; B: 4; C: 



break

(PHP 4, PHP 5)

break termina l'esecuzione della struttura di controllo for, foreach, while, do-while o switch corrente.

break accetta un argomento numerico che indica da quanti livelli di strutture annidate si intende "uscire".

<?php
$arr 
= array('one''two''three''four''stop''five');
while (list(, 
$val) = each($arr)) {
    if (
$val == 'stop') {
        break;    
/* Equivalente a 'break 1;' */
    
}
    echo 
"$val<br />\n";
}

/* Utilizzo dell'argomento facoltativo */

$i 0;
while (++
$i) {
    switch (
$i) {
    case 
5:
        echo 
"At 5<br />\n";
        break 
1;  /* Termina solo lo switch. */
    
case 10:
        echo 
"At 10; quitting<br />\n";
        break 
2;  /* Termina lo switch ed il while. */
    
default:
        break;
    }
}
?>

Changelog per break
Versione Descrizione
5.4.0 break 0; non è più valido. Nelle versioni precedenti era interpretato come break 1;.
5.4.0 Rimossa la possibilità di passare le variabili (ad esempio, $num = 2; break $num;) come argomento numerico.



continue

(PHP 4, PHP 5)

continue è impiegato all'interno delle strutture di iterazione per saltare il resto del ciclo corrente e riprendere l'esecuzione dalla verifica della condizione di controllo e quindi dall'inizio dell'iterazione successiva.

Nota: Si noti che in PHP la struttura switch è considerata una struttura di iterazione ai fini del comando continue.

continue accetta un argomento numerico facoltativo che indica il numero di livelli di strutture iterative annidate per i quali si intende concludere il ciclo attuale. Il valore predefinito è 1, perciò salta alla fine del ciclo corrente.

<?php
while (list($key$value) = each($arr)) {
    if (!(
$key 2)) { // salta i numeri dispari
        
continue;
    }
    
do_something_odd($value);
}

$i 0;
while (
$i++ < 5) {
    echo 
"Esterno<br />\n";
    while (
1) {
        echo 
"Medio<br />\n";
        while (
1) {
            echo 
"Interno<br />\n";
            continue 
3;
        }
        echo 
"Questa frase non viene mai mostrata.<br />\n";
    }
    echo 
"Neanche questa.<br />\n";
}
?>

Omettere il punto e virgola dopo continue può creare confusione. Segue un esempio di cosa non andrebbe fatto.

<?php
for ($i 0$i 5; ++$i) {
    if (
$i == 2)
        continue
    print 
"$i\n";
}
?>

Ci si potrebbe aspettare come risultato il seguente :

0
1
3
4

ma questo script produrrà in output :

2

poiché le istruzioni continue print "$i\n"; sono valutate una singola espressione, e quindi print viene chiamata solo quando $i == 2 è vero. (Il valore restituito da print è passato a continue come argomento numerico).

Changelog per continue
Versione Descrizione
5.4.0 continue 0; non è più valido. Nelle versioni precedenti questo veniva interpretato come continue 1;.
5.4.0 Rimossa la possibilità di passare le variabili (per esempio, $num = 2; continue $num;) come argomento numerico.



switch

(PHP 4, PHP 5)

The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.

Nota: Note that unlike some other languages, the continue statement applies to switch and acts similar to break. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2.

Nota:

Note that switch/case does loose comparison.

The following two examples are two different ways to write the same thing, one using a series of if and elseif statements, and the other using the switch statement:

Example #1 switch structure

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

switch (
$i) {
    case 
0:
        echo 
"i equals 0";
        break;
    case 
1:
        echo 
"i equals 1";
        break;
    case 
2:
        echo 
"i equals 2";
        break;
}
?>

Example #2 switch structure allows usage of strings

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

It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:

<?php
switch ($i) {
    case 
0:
        echo 
"i equals 0";
    case 
1:
        echo 
"i equals 1";
    case 
2:
        echo 
"i equals 2";
}
?>

Here, if $i is equal to 0, PHP would execute all of the echo statements! If $i is equal to 1, PHP would execute the last two echo statements. You would get the expected behavior ('i equals 2' would be displayed) only if $i is equal to 2. Thus, it is important not to forget break statements (even though you may want to avoid supplying them on purpose under certain circumstances).

In a switch statement, the condition is evaluated only once and the result is compared to each case statement. In an elseif statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster.

The statement list for a case can also be empty, which simply passes control into the statement list for the next case.

<?php
switch ($i) {
case 
0:
case 
1:
case 
2:
    echo 
"i is less than 3 but not negative";
    break;
case 
3:
    echo 
"i is 3";
}
?>

A special case is the default case. This case matches anything that wasn't matched by the other cases. For example:

<?php
switch ($i) {
    case 
0:
        echo 
"i equals 0";
        break;
    case 
1:
        echo 
"i equals 1";
        break;
    case 
2:
        echo 
"i equals 2";
        break;
    default:
       echo 
"i is not equal to 0, 1 or 2";
}
?>

The case expression may be any expression that evaluates to a simple type, that is, integer or floating-point numbers and strings. Arrays or objects cannot be used here unless they are dereferenced to a simple type.

The alternative syntax for control structures is supported with switches. For more information, see Alternative syntax for control structures.

<?php
switch ($i):
    case 
0:
        echo 
"i equals 0";
        break;
    case 
1:
        echo 
"i equals 1";
        break;
    case 
2:
        echo 
"i equals 2";
        break;
    default:
        echo 
"i is not equal to 0, 1 or 2";
endswitch;
?>

It's possible to use a semicolon instead of a colon after a case like:

<?php
switch($beer)
{
    case 
'tuborg';
    case 
'carlsberg';
    case 
'heineken';
        echo 
'Good choice';
    break;
    default;
        echo 
'Please make a new selection...';
    break;
}
?>



declare

(PHP 4, PHP 5)

The declare construct is used to set execution directives for a block of code. The syntax of declare is similar to the syntax of other flow control constructs:

declare (directive)
    statement

The directive section allows the behavior of the declare block to be set. Currently only two directives are recognized: the ticks directive (See below for more information on the ticks directive) and the encoding directive (See below for more information on the encoding directive).

Nota: The encoding directive was added in PHP 5.3.0

The statement part of the declare block will be executed - how it is executed and what side effects occur during execution may depend on the directive set in the directive block.

The declare construct can also be used in the global scope, affecting all code following it (however if the file with declare was included then it does not affect the parent file).

<?php
// these are the same:

// you can use this:
declare(ticks=1) {
    
// entire script here
}

// or you can use this:
declare(ticks=1);
// entire script here
?>

Ticks

A tick is an event that occurs for every N low-level tickable statements executed by the parser within the declare block. The value for N is specified using ticks=N within the declare block's directive section.

Not all statements are tickable. Typically, condition expressions and argument expressions are not tickable.

The event(s) that occur on each tick are specified using the register_tick_function(). See the example below for more details. Note that more than one event can occur for each tick.

Example #1 Tick usage example

<?php

declare(ticks=1);

// A function called on each tick event
function tick_handler()
{
    echo 
"tick_handler() called\n";
}

register_tick_function('tick_handler');

$a 1;

if (
$a 0) {
    
$a += 2;
    print(
$a);
}

?>

Example #2 Ticks usage example

<?php

function tick_handler()
{
  echo 
"tick_handler() called\n";
}

$a 1;
tick_handler();

if (
$a 0) {
    
$a += 2;
    
tick_handler();
    print(
$a);
    
tick_handler();
}
tick_handler();

?>

See also register_tick_function() and unregister_tick_function().

Encoding

A script's encoding can be specified per-script using the encoding directive.

Example #3 Declaring an encoding for the script.

<?php
declare(encoding='ISO-8859-1');
// code here
?>

Attenzione

When combined with namespaces, the only legal syntax for declare is declare(encoding='...'); where ... is the encoding value. declare(encoding='...') {} will result in a parse error when combined with namespaces.

The encoding declare value is ignored in PHP 5.3 unless php is compiled with --enable-zend-multibyte.

Note that PHP does not expose whether --enable-zend-multibyte was used to compile PHP other than by phpinfo().

See also zend.script_encoding.



return

(PHP 4, PHP 5)

return returns program control to the calling module. Execution resumes at the statement following the called module's invocation.

If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. return also ends the execution of an eval() statement or script file.

If called from the global scope, then execution of the current script file is ended. If the current script file was included or required, then control is passed back to the calling file. Furthermore, if the current script file was included, then the value given to return will be returned as the value of the include call. If return is called from within the main script file, then script execution ends. If the current script file was named by the auto_prepend_file or auto_append_file configuration options in php.ini, then that script file's execution is ended.

For more information, see Returning values.

Nota: Note that since return is a language construct and not a function, the parentheses surrounding its arguments are not required. It is common to leave them out, and you actually should do so as PHP has less work to do in this case.

Nota: If no parameter is supplied, then the parentheses must be omitted and NULL will be returned. Calling return with parentheses but with no arguments will result in a parse error.

Nota: You should never use parentheses around your return variable when returning by reference, as this will not work. You can only return variables by reference, not the result of a statement. If you use return ($a); then you're not returning a variable, but the result of the expression ($a) (which is, of course, the value of $a).



require

(PHP 4, PHP 5)

require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.

See the include documentation for how this works.



include

(PHP 4, PHP 5)

The include statement includes and evaluates the specified file.

The documentation below also applies to require.

Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing. The include construct will emit a warning if it cannot find a file; this is different behavior from require, which will emit a fatal error.

If a path is defined — whether absolute (starting with a drive letter or \ on Windows, or / on Unix/Linux systems) or relative to the current directory (starting with . or ..) — the include_path will be ignored altogether. For example, if a filename begins with ../, the parser will look in the parent directory to find the requested file.

For more information on how PHP handles including files and the include path, see the documentation for include_path.

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

Example #1 Basic include example

vars.php
<?php

$color 
'green';
$fruit 'apple';

?>

test.php
<?php

echo "A $color $fruit"// A

include 'vars.php';

echo 
"A $color $fruit"// A green apple

?>

If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function. An exception to this rule are magic constants which are evaluated by the parser before the include occurs.

Example #2 Including within functions

<?php

function foo()
{
    global 
$color;

    include 
'vars.php';

    echo 
"A $color $fruit";
}

/* vars.php is in the scope of foo() so     *
* $fruit is NOT available outside of this  *
* scope.  $color is because we declared it *
* as global.                               */

foo();                    // A green apple
echo "A $color $fruit";   // A green

?>

When a file is included, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes again at the end. For this reason, any code inside the target file which should be executed as PHP code must be enclosed within valid PHP start and end tags.

If "URL include wrappers" are enabled in PHP, you can specify the file to be included using a URL (via HTTP or other supported wrapper - see Supported Protocols and Wrappers for a list of protocols) instead of a local pathname. If the target server interprets the target file as PHP code, variables may be passed to the included file using a URL request string as used with HTTP GET. This is not strictly speaking the same thing as including the file and having it inherit the parent file's variable scope; the script is actually being run on the remote server and the result is then being included into the local script.

Avviso

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.

Example #3 include through HTTP

<?php

/* This example assumes that www.example.com is configured to parse .php
* files and not .txt files. Also, 'Works' here means that the variables
* $foo and $bar are available within the included file. */

// Won't work; file.txt wasn't handled by www.example.com as PHP
include 'http://www.example.com/file.txt?foo=1&bar=2';

// Won't work; looks for a file named 'file.php?foo=1&bar=2' on the
// local filesystem.
include 'file.php?foo=1&bar=2';

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

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

?>

Avviso

Security warning

Remote file may be processed at the remote server (depending on the file extension and the fact if the remote server runs PHP or not) but it still has to produce a valid PHP script because it will be processed at the local server. If the file from the remote server should be processed there and outputted only, readfile() is much better function to use. Otherwise, special care should be taken to secure the remote script to produce a valid and desired code.

See also Remote files, fopen() and file() for related information.

Handling Returns: include returns FALSE on failure and raises a warning. Successful includes, unless overridden by the included file, return 1. It is possible to execute a return statement inside an included file in order to terminate processing in that file and return to the script which called it. Also, it's possible to return values from included files. You can take the value of the include call as you would for a normal function. This is not, however, possible when including remote files unless the output of the remote file has valid PHP start and end tags (as with any local file). You can declare the needed variables within those tags and they will be introduced at whichever point the file was included.

Because include is a special language construct, parentheses are not needed around its argument. Take care when comparing return value.

Example #4 Comparing return value of include

<?php
// won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('')
if (include('vars.php') == 'OK') {
    echo 
'OK';
}

// works
if ((include 'vars.php') == 'OK') {
    echo 
'OK';
}
?>

Example #5 include and the return statement

return.php
<?php

$var 
'PHP';

return 
$var;

?>

noreturn.php
<?php

$var 
'PHP';

?>

testreturns.php
<?php

$foo 
= include 'return.php';

echo 
$foo// prints 'PHP'

$bar = include 'noreturn.php';

echo 
$bar// prints 1

?>

$bar is the value 1 because the include was successful. Notice the difference between the above examples. The first uses return within the included file while the other does not. If the file can't be included, FALSE is returned and E_WARNING is issued.

If there are functions defined in the included file, they can be used in the main file independent if they are before return or after. If the file is included twice, PHP 5 issues fatal error because functions were already declared, while PHP 4 doesn't complain about functions defined after return. It is recommended to use include_once instead of checking if the file was already included and conditionally return inside the included file.

Another way to "include" a PHP file into a variable is to capture the output by using the Output Control Functions with include. For example:

Example #6 Using output buffering to include a PHP file into a string

<?php
$string 
get_include_contents('somefile.php');

function 
get_include_contents($filename) {
    if (
is_file($filename)) {
        
ob_start();
        include 
$filename;
        return 
ob_get_clean();
    }
    return 
false;
}

?>

In order to automatically include files within scripts, see also the auto_prepend_file and auto_append_file configuration options in php.ini.

Nota: Poiché questo è un costrutto del linguaggio e non una funzione, non può essere chiamato con le variabili funzione

See also require, require_once, include_once, get_included_files(), readfile(), virtual(), and include_path.



require_once

(PHP 4, PHP 5)

The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again.

See the include_once documentation for information about the _once behaviour, and how it differs from its non _once siblings.



include_once

(PHP 4, PHP 5)

The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.

include_once may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so in this case it may help avoid problems such as function redefinitions, variable value reassignments, etc.

See the include documentation for information about how this function works.

Nota:

With PHP 4, _once functionality differs with case-insensitive operating systems (like Windows) so for example:

Example #1 include_once with a case insensitive OS in PHP 4

<?php
include_once "a.php"// this will include a.php
include_once "A.php"// this will include a.php again! (PHP 4 only)
?>

This behaviour changed in PHP 5, so for example with Windows the path is normalized first so that C:\PROGRA~1\A.php is realized the same as C:\Program Files\a.php and the file is included just once.



goto

(PHP 5 >= 5.3.0)

L'operatore goto può essere utilizzato per saltare ad un altra sezione nel programma. Il punto d'arrivo è specificato da un'etichetta seguita dai due punti, e l'istruzione è data con goto seguito dall'etichetta desiderata. Questo non è un goto completamente libero da restrizioni. L'etichetta deve essere all'interno dello stesso file e contesto, ciò significa che non si può saltare fuori da una funzione o metodo, e neanche saltare all'interno di un'altra funzione. Inoltre non si può saltare all'interno di qualsiasi loop o struttura di switch. Si può saltarne fuori, e un caso comune è l'utilizzo di goto al posto di un break multilivello.

Example #1 esempio d'uso di goto

<?php
goto a;
echo 
'Foo';
 
a:
echo 
'Bar';
?>

Il precedente esempio visualizzerà:

Bar

Example #2 Esempio di loop con goto

<?php
for($i=0,$j=50$i<100$i++) {
  while(
$j--) {
    if(
$j==17) goto end
  }  
}
echo 
"i = $i";
end:
echo 
'j hit 17';
?>

Il precedente esempio visualizzerà:

j hit 17

Example #3 Questo non funziona

<?php
goto loop;
for(
$i=0,$j=50$i<100$i++) {
  while(
$j--) {
    
loop:
  }
}
echo 
"$i = $i";
?>

Il precedente esempio visualizzerà:

Fatal error: 'goto' into loop or switch statement is disallowed in
script on line 2

Nota:

L'operatore goto è disponibile dal PHP 5.3.

Qual è la cosa peggiore che può succedere quando si usa goto?
Image gentilmente fornita da » xkcd




Funzioni

Indice dei contenuti


Funzioni definite dall'utente

Una funzione può essere definita usando la seguente sintassi:

Example #1 Psuedo codice per dimostrare l'uso delle funzioni

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

All'interno di una funzione può apparire qualunque codice PHP valido, persino altre funzioni e definizioni di classe.

I nomi di funzione seguono le stesse regole delle altre etichette PHP. Un nome di funzione valido comincia con una lettera o un underscore, seguito da un qualsiasi numero di lettere, numeri o underscore. Come espressione regolare, questo viene rappresentato così: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.

Suggerimento

Si può anche consultare Userland Naming Guide.

Le funzioni devono essere definite prima di essere referenziate 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.

Example #2 Funzioni condizionali

<?php

$makefoo 
true;

/* Qui non possiamo chiamare foo()
   poiché non esiste ancora,
   ma possiamo chiamare bar() */

bar();

if (
$makefoo) {
  function 
foo()
  {
    echo 
"Io non esisto sino a quando il programma non mi raggiunge.\n";
  }
}

/* Ora possiamo chiamare foo()
   poiché $makefoo vale true */

if ($makefoofoo();

function 
bar()
{
  echo 
"Io esco immediatamente dopo l'avvio del programma.\n";
}

?>

Example #3 Funzioni dentro a funzioni

<?php
function foo() 
{
  function 
bar() 
  {
    echo 
"Io non esiste fino a quando non si esegue foo().\n";
  }
}

/* Non possiamo chiamare bar()
   poiché non esiste ancora. */

foo();

/* Ora si può eseguire bar(),
   l'elaborazione di foo()
   l'ha resa accessibile. */

bar();

?>

Tutte le funzioni e le classi, in PHP, hanno visibilità globale - possono essere chiamate dall'esterno di una funzione anche se sono definite all'interno di questa e vice-versa.

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

Nota: I nomi delle funzioni non distinguono tra maiuscolo e minuscolo, ma, solitamente, è buona norma richiamare le funzioni nel modo con cui sono state definite.

Sia un numero variabile di argomenti che gli argomenti di default sono ammessi nelle funzioni. Vedere anche 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.

Example #4 Funzioni ricorsive

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



Argomenti delle funzioni

L'informazione può essere passata alle funzioni tramite la lista degli argomenti, che sono liste di espressioni delimitati dalla virgola. Gli argomenti sono valutati da sinistra a destra.

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 ugualmente supportate, vedere anche i riferimenti alle funzioni func_num_args(), func_get_arg(), e func_get_args() per maggiori informazioni.

Example #1 Passaggio di array a funzioni

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

Costruire argomenti passati per riferimento

Di default, gli argomenti della funzione sono passati per valore (così se cambiate il valore dell'argomento all'interno della funzione , esso non cambierà fuori della funzione). Se volete permettere ad una funzione di modificare i suoi argomenti, dovete passarli per riferimento.

Se volete che una argomento sia passato sempre per riferimento ad una funzione, dovete anteporre un ampersand (&) al nome dell'argomento nella definizione della funzione:

Example #2 Passaggio di parametri per riferimento

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

Valori predefiniti degli argomenti

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

Example #3 Utilizzo dei parametri default in una funzione

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

Il precedente esempio visualizzerà:

Sto facendo una tazza di cappuccino.
Sto facendo una tazza di.
Sto facendo una tazza di espresso.

Anche il PHP permette di utilizzare array ed il tipo speciale NULL come valore di default, ad esempio:

Example #4 Utilizzo di tipi non scalari come valori di default

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

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

Da notare che quando vengono usati argomenti predefiniti, qualunque argomento predefinito dovrebbe essere a destra degli argomenti non-predefiniti; diversamente, le cose non funzioneranno come ci si aspetti. Si consideri il seguente frammento di codice:

Example #5 Utilizzo incorretto degli argomenti di default

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

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

Il precedente esempio visualizzerà:

Warning: Missing argument 2 in call to fare_lo_yogurt() in 
/usr/local/etc/httpd/htdocs/phptest/functest.html on line 41
Fare una vaschetta di fragola a.

Ora, si confronti il codice di sopra con questo:

Example #6 Utilizzo corretto degli argomenti di default

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

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

Il precedente esempio visualizzerà:

Fare una vaschetta di yogurt a fragola.

Nota: Dal PHP 5 i valori di default possono essere passati per riferimento.

Liste di argomenti a lunghezza variabile

PHP 4 ha il supporto per le liste di argomenti a lunghezza variabile nelle funzioni definite dall'utente. Ciò è realmente abbastanza semplice, usando le funzioni func_num_args(), func_get_arg(), e func_get_args().

Non è richiesta una speciale sintassi, e le liste di argomenti possono ancora essere provviste esplicitamente con le definizioni di funzioni e si comporteranno normalmente.



Valori restituiti

I valori vengono restituiti usando l'istruzione opzionale return. Può essere restituito qualsiasi tipo, incluse liste ed oggetti. Ciò provoca l'interruzione dell'esecuzione della funzione immediatamente e la restituzione del controllo alla linea da cui è stata chiamata. Vedere return per maggiori informazioni.

Nota:

Se return è omesso, verrà restituito il valore NULL.

Example #1 Esempio di uso di return

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

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

Example #2 Restituzione di un array per ottenere più valori

<?php
function numeri_piccoli()
{
    return array (
012);
}
list (
$zero$uno$due) = numeri_piccoli();
?>

Per restituire un riferimento da una funzione, è necessario usare l'operatore di passaggio per riferimento & in entrambe le dichiarazioni di funzioni e quando viene assegnato il valore restituito ad una variabile:

Example #3 Restituzione di un riferimento ad una funzione

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

$nuovo_riferimento =& restituisce_riferimento();
?>

Per maggiori informazioni sui riferimenti, consultare References Explained.



Funzioni variabili

PHP supporta il concetto di funzioni variabili. Ciò significa che se un nome di variabile ha le parentesi accodate ad esso, PHP cercherà una funzione con lo stesso nome del valore della variabile, e cercherà di eseguirla. Tra le altre cose, ciò puo essere usato per implementare delle callbacks, tabelle di funzioni e così via.

Le funzioni variabili non funzionano con costrutti di linguaggio come echo, print, unset(), isset(), empty(), include, require e simili. Occorre costruire una propria funzione per utilizzare questi costrutti come variabili per funzioni.

Example #1 Esempio di funzioni variabili

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

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

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

$func 'foo';
$func();        // questa chiama foo()

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

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

Tramite le funzioni variabili si possono eseguire anche metodi di oggetti.

Example #2 Esempio di un metodo variabile

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

$foo = new Foo();
$funcname "Variable";
$foo->$funcname();  // Questo esegue $foo->Variable()

?>

Quando si chiamano dei metodi statici, la chiamata a funzione ha la precedenza sull'operatore di proprietà statica:

Example #3 Esempio di metodo variabile con proprietà statiche

<?php
class Foo
{
    static 
$variable 'static property';
    static function 
Variable()
    {
        echo 
'Method Variable called';
    }
}

echo 
Foo::$variable// Questo stampa 'static property'. Non ha bisogno di una $variable in questo ambito.
$variable "Variable";
Foo::$variable();  // Questo chiama $foo->Variable() leggendo $variable da questo ambito.

?>

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



Funzioni interne (built-in)

Il PHP possiede diverse funzioni e costrutti standard. Esistono, inoltre, funzioni che richiedono la compila di specifici moduli del PHP, altrimenti si ottiene l'errore "undefined function" errors. Ad esempio, per utilizzare le funzioni image, tipo imagecreatetruecolor(), occorre che il PHP sia compilato con il supporto GD. Oppure, per utilizzare mysql_connect() occorre che il PHP sia compilato con il supporto per MySQL Esistono anche diversi funzioni di base incluse in ogni versione del PHP tipo le funzioni stringa e per variabili. L'esecuzione di phpinfo() o di get_loaded_extensions() visualizzerà quali moduli sono caricati nel PHP. Inoltre si noti che diverse estensioni sono abilitate per default e che il manule PHP è suddiviso per estensione. Vedere i capitoli configurazione, installazione, ed i capitoli dei singoli moduli per avere maggiori dettagli su come configurare il PHP.

Come leggere e comprendere il prototipo di una funzione è spiegato nella sezione del manuale intitolata come leggere la definizione di una funzione. E' importante comprendere che cosa restituisce una funzione o se una funzione lavora direttamente sui dati passati. Ad esempio str_replace() restituisce la stringa modificata, mentre usort() lavora sulla variabile passata. Ciascuna pagina del manuale fornisce informazioni specifiche per ogni funzione tipo notizie sui parametri, modifiche di funzionamento, 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.

Nota: Se i parametri passati ad una funzioni non sono quelli attesi, come per esempio passare un array quando è attesa una string, il valore di ritorno della funziona è indefinito. In questo caso restituirà probabilmente NULL ma questa è solo una convenzione, e non ci si può fare affidamento.

Vedere anche function_exists(), the function reference, get_extension_funcs(), e dl().



Funzioni anonime

Le funzioni anonime, chiamate anche chiusure o closures, permettono la creazione di funzioni che non possiedono un nome. Sono molto utili come valore dei parametri callback, ma hanno moltri altri utilizzi.

Example #1 Esempio di funzione anonima

<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
    return 
strtoupper($match[1]);
}, 
'hello-world');
// stampa helloWorld
?>

Le chiusure possono essere usate anche come valore di una variabile; il PHP converte automaticamente queste espressioni in istanze della classe interna Closure. L'assegnazione di una chiusura a una variabile usa la stessa sintassi di un qualsiasi altro assegnazione, incluso il punto e virgola alla fine:

Example #2 Esempio di assegnazione di funzione anonima

<?php
$greet 
= function($name)
{
    
printf("Hello %s\r\n"$name);
};

$greet('World');
$greet('PHP');
?>

Le chiusure possono anche ereditare le variabili dal contesto del genitore. Ognuna di queste variabili deve essere dichiarata nell'intestazione della funzione. Ereditare le variabili dall'ambito genitore non la stessa cosa che usare variabili globali. Le variabili globali esistono nell'ambito globale, che è lo stesso, indipendentemente da quale funzione è in esecuzione. L'ambito genitore di una chiusura è la funzione nella quale la chiusura è stata dichiarata (non necessariamente la funzione da cui è stata chiamata). Si veda l'esempio seguente:

Example #3 Chiusure e ambiti di visibilità

<?php
// Un semplice paniere che contiene una lista di prodotti aggiunti
// e la quantità di ciascun prodotto. Include un metodo che
// calcola il prezzo totale degli articoli nel paniere utilizzando
// una chiusura come callback.
class Cart
{
    const 
PRICE_BUTTER  1.00;
    const 
PRICE_MILK    3.00;
    const 
PRICE_EGGS    6.95;

    protected 
$products = array();
    
    public function 
add($product$quantity)
    {
        
$this->products[$product] = $quantity;
    }
    
    public function 
getQuantity($product)
    {
        return isset(
$this->products[$product]) ? $this->products[$product] :
               
FALSE;
    }
    
    public function 
getTotal($tax)
    {
        
$total 0.00;
        
        
$callback =
            function (
$quantity$product) use ($tax, &$total)
            {
                
$pricePerItem constant(__CLASS__ "::PRICE_" .
                    
strtoupper($product));
                
$total += ($pricePerItem $quantity) * ($tax 1.0);
            };
        
        
array_walk($this->products$callback);
        return 
round($total2);
    }
}

$my_cart = new Cart;

// Aggiunta di un elemento nel paniere
$my_cart->add('butter'1);
$my_cart->add('milk'3);
$my_cart->add('eggs'6);

// Stampa del totale con una tassa aggiuntiva del 5%.
print $my_cart->getTotal(0.05) . "\n";
// The result is 54.29
?>

Le funzioni anonime sono implementate usando la classe Closure.

Log delle modifiche

Versione Descrizione
5.4.0 $this può essere usato nelle funzioni anonime.
5.3.0 Le funzioni anonime sono introdotte.

Note

Nota: È possibile usare func_num_args(), func_get_arg() e func_get_args() all'interno di una chiusura.




Classi e Oggetti

Indice dei contenuti


Introduzione

A partire dal PHP 5, il modello a oggetti è stato riscritto per permettere performance migliori e più funzionalità. Dal PHP 4 c'è stato un cambiamento radicale. PHP 5 ora ha un modello ad oggetti completo.

Tra le funzionalità in PHP 5 ci sono l'inclusione della bisibility, abstract e final di classi e metodi, aggiunti anche magic methods, interface, cloning e typehinting.

PHP gestisce gli oggetti allo stesso modo dei riferimenti o handle; ciò significa che ogni variabile contiene un riferimento ad un oggetto piuttosto che una copia dell'intero oggetto. Vedi Oggetti e Riferimenti

Suggerimento

Si può anche consultare Userland Naming Guide.



Nozioni di base

class

La definizione più semplice di una classe è composta dal termine class, seguito dal nome della classe, seguito da una coppia di parentesi graffe che racchiudono le definizioni delle proprietà e dei metodi che fanno parte della classe stessa.

Il nome della classe può essere una qualunque etichetta valida che non sia una parola riservata di PHP. Un nome di classe valido inizia con una lettera o un underscore, seguiti da lettere, numeri, o underscores. Questa regola può essere rappresentata dalla seguente espressione regolare: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.

Una classe può contenere le proprie costanti, variabili (chiamate "proprietà"), e funzioni (chiamate "methods").

Example #1 Semplice definizione di una classe

<?php
class SimpleClass
{
    
// dichiarazione di proprietà
    
public $var 'un valore di default';

    
// dichiarazione di metodi
    
public function mostraVar() {
        echo 
$this->var;
    }
}
?>

La pseudo-variabile $this è disponibile quando un metodo è invocato dall'interno del contesto di un oggetto. $this è il riferimento all'oggetto stesso (solitamente l'oggetto cui il metodo appartiene, ma eventualmente può riferirsi all'oggetto chiamante se il metodo è invocato staticamente dal contesto di un oggetto secondario).

Example #2 Esempi della pseudo-variabile $this

<?php
class A
{
    function 
foo()
    {
        if (isset(
$this)) {
            echo 
'$this è definito (';
            echo 
get_class($this);
            echo 
")\n";
        } else {
            echo 
"\$this non è definito\n";
        }
    }
}

class 
B
{
    function 
bar()
    {
        
// Nota: la seguente operazione darà luogo ad un segnale di Warning se E_STRICT è abilitato.
        
A::foo();
    }
}

$a = new A();
$a->foo();

// Nota: la seguente operazione darà luogo ad un segnale di Warning se E_STRICT è abilitato.
A::foo();
$b = new B();
$b->bar();

// Nota: la seguente operazione darà luogo ad un segnale di Warning se E_STRICT è abilitato.
B::bar();
?>

Il precedente esempio visualizzerà:

$this è definito (A)
$this non è definito
$this è definito (B)
$this non è definito

new

Per creare un'istanza di una classe, deve essere usata la parola chiave new. Un oggetto sarà sempre creato a meno che la classe abbia un costruttore definito il quale sollevi un' eccezione in caso di errore. Le classi dovrebbero essere definite prima dell'istanziazione (in alcuni casi questo è un requisito).

Se viene usata una stringa contenente il nome di una classe con new, verrà creata una nuova istanza di quella classe. Se la classe appartiene ad un namespace, deve essere utilizzato il suo nome completamente qualificato.

Example #3 Creazione di un'istanza

<?php
$instance 
= new SimpleClass();

// è anche possibile istanziare una classe il cui nome sia contenuto in una variabile:
$className 'Foo';
$instance = new $className(); // Foo()
?>

Nel contesto di una classe, è possibile creare un nuovo oggetto con le espressioni new self e new parent.

Quando si assegna un'istanza già creata ad una nuova variabile, la nuova variabile farà riferimento alla stessa istanza cui fa riferimento la variabile originale. Questo stesso comportamento si ha quando vengono passate istanze ad una funzione. Si può ottenere una copia di un oggetto già creato per mezzo della clonazione.

Example #4 Assegnazione di oggetti

<?php

$instance 
= new SimpleClass();

$assigned   =  $instance;
$reference  =& $instance;

$istance->var '$assigned avrà questo valore';

$instance null// $instance e $reference diventano null

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

Il precedente esempio visualizzerà:

NULL
NULL
object(SimpleClass)#1 (1) {
   ["var"]=>
     string(30) "$assigned avrà questo valore"
}

PHP 5.3.0 ha introdotto due nuovi modi per creare istanze di un oggetto:

Example #5 Creazione di nuovi oggetti

<?php
class Test
{
    static public function 
getNew()
    {
        return new static;
    }
}

class 
Child extends Test
{}

$obj1 = new Test();
$obj2 = new $obj1;
var_dump($obj1 !== $obj2);

$obj3 Test::getNew();
var_dump($obj3 instanceof Test);

$obj4 Child::getNew();
var_dump($obj4 instanceof Child);
?>

Il precedente esempio visualizzerà:

bool(true)
bool(true)
bool(true)

extends

Una classe può ereditare i metodi e le proprietà di un'altra classe utilizzando la parola chiave extends nella dichiarazione della classe. Non è possibile estendere più di una classe per volta; ogni classe può ereditare da una sola altra classe.

I metodi e le proprietà ereditate possono essere sovrascritte ridichiarandole nella nuova classe con lo stesso nome definito nella classe padre. Questo non sarà comunque possibile se il metodo che si intende ridefinire è stato dichiarato nella classe padre come final. Si può accedere alle proprietà statiche e ai metodi ridefiniti riferendosi ad essi con parent::.

Nel sovrascrivere i metodi, la lista dei parametri dovrebbe rimanere invariata o PHP genererà un errore di livello E_STRICT. Ciò non si applica al costruttore, che consente di sovrascrivere i parametri.

Example #6 Ereditarietà semplice

<?php
class ExtendClass extends SimpleClass
{
    
// Ridefinisce il metodo presente in ClasseSemplice
    
function displayVar()
    {
        echo 
"Classe figlia\n";
        
parent::displayVar();
    }
}

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

Il precedente esempio visualizzerà:

Classe figlia
un valore di default

::class

Da PHP 5.5, la parola chiave class è anche usata per la risoluzione del nome della classe. Si può ottenere una stringa contenente il nome completo della classe ClassName utilizzando ClassName::class. Questo è particolarmente utile con le classi presenti nei namespace.

Example #7 Risoluzione del nome della classe

<?php
namespace NS {
    class 
ClassName {
    }
    
    echo 
ClassName::class;
}
?>

Il precedente esempio visualizzerà:

NS\ClassName



Properties

Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

See Visibility for more information on the meanings of public, protected, and private.

Nota:

In order to maintain backward compatibility with PHP 4, PHP 5 will still accept the use of the keyword var in property declarations instead of (or in addition to) public, protected, or private. However, var is no longer required. In versions of PHP from 5.0 to 5.1.3, the use of var was considered deprecated and would issue an E_STRICT warning, but since PHP 5.1.3 it is no longer deprecated and does not issue the warning.

If you declare a property using var instead of one of public, protected, or private, then PHP 5 will treat the property as if it had been declared as public.

Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property. See Static Keyword for more information on the difference between static and non-static properties.

The pseudo-variable $this is available inside any class method when that 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 possibly another object, if the method is called statically from the context of a secondary object).

Example #1 property declarations

<?php
class SimpleClass
{
   
// invalid property declarations:
   
public $var1 'hello ' 'world';
   public 
$var2 = <<<EOD
hello world
EOD;
   public 
$var3 1+2;
   public 
$var4 self::myStaticMethod();
   public 
$var5 $myVar;

   
// valid property declarations:
   
public $var6 myConstant;
   public 
$var7 = array(truefalse);

   
// This is allowed only in PHP 5.3.0 and later.
   
public $var8 = <<<'EOD'
hello world
EOD;
}
?>

Nota:

There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions.

Unlike heredocs, nowdocs can be used in any static data context, including property declarations.

Example #2 Example of using a nowdoc to initialize a property

<?php
class foo {
   
// As of PHP 5.3.0
   
public $bar = <<<'EOT'
bar
EOT;
}
?>

Nota:

Nowdoc support was added in PHP 5.3.0.



Costanti di classe

Si possono definire valori costanti relativi ad una classe che rimangano non modificabili. Le costanti si distinguono dalle normali variabili poiché non si utilizza il simbolo $ per dichiararle o riferirsi ad esse.

Il valore deve essere un'espressione costante, non (ad esempio) una variabile, una proprietà, il risultato di una operazione matematica, o la chiamata ad una funzione.

È inoltre possibile dichiarare constants relative alle interfacce. Fare riferimento alla documentazione interfacce per degli esempi.

A partire da PHP 5.3.0, è possibile fare riferimento alla classe utilizzando una variabile. Il valore della variabile non può essere una parola chiave (ad esempio, self parent o static ).

Example #1 Definire ed usare una costante

<?php
class MiaClasse
{
    const 
costante 'valore costante';

    function 
mostraConstante() {
        echo  
self::costante "\n";
    }
}

echo 
MiaClasse::costante "\n";

$nomeclasse "MiaClasse";
echo 
$nomeclasse::costante "\n"// PHP 5.3.0

$classe = new MiaClasse();
$classe->mostraConstante();

echo 
$classe::costante."\n"// PHP 5.3.0
?>

Example #2 Esempio di dati statici

<?php
class foo {
    
// PHP 5.3.0
    
const bar = <<<'EOT'
bar
EOT;
}
?>

A differenza degli heredocs, i nowdocs possono essere usati in qualunque contesto dati statico.

Nota:

Il supporto per Nowdoc è stato aggiunto in PHP 5.3.0.



Caricamento automatico delle classi

Molti sviluppatori che producono applicazioni orientate agli oggetti creano un file sorgente PHP per ogni classe definita. Uno dei più grossi inconvenienti di questo approccio è la necessità di mantenere una lunga lista di inclusioni all'inizio di ogni script (un'inclusione per ogni classe).

In PHP 5, ciò non è più necessario, in quanto è possibile definire una funzione __autoload() che viene automaticamente invocata in caso si stia cercando di usare una classe/interfaccia che non sia stata ancora definita. Chiamando questa funzione, il motore di scripting ha una ultima possibilità di caricare la classe prima che PHP termini l'esecuzione con un errore.

Suggerimento

La funzione spl_autoload_register() fornisce una alternative più flessibile per l'autocaricamento delle classi. Per questa ragione, usare la funzione __autoload() è sconsigliato dato che in futuro potrà essere rimossa o diventare deprecata.

Nota:

Prima di 5.3.0, le eccezioni sollevate dalla funzione __autoload non potevano essere intercettate nel blocco catch e avrebbero portato ad un errore fatale. Da 5.3.0+ le eccezioni sollevate nella funzione __autoload possono essere intercettate nel blocco catch, con la sola precisazione che se si sta sollevando un'eccezione definita dall'utente la classe in cui l'eccezione viene definita deve essere disponibile. La funzione __autoload può essere usata ricorsivamente per caricare la classe dell'eccezione personalizzata.

Nota:

La funzionalità di autocaricamento non è disponibile se si sta usando PHP nella modalità interattiva di CLI.

Nota:

Se il nome di classe è usato ad esempio in call_user_func() esso può contenere alcuni caratteri pericolosi come ../. Si raccomanda di non usare direttamente valori inputati dall'utente in tali funzioni, o quanto meno di verificare l'input __autoload().

Example #1 Esempio di autocaricamento

Questo esempio cerca di caricare le classi MyClass1 e MyClass2 rispettivamente dai file MyClass1.php e MyClass2.php.

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

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

Example #2 Altro esempio di autocaricamento

Questo esempio tenta di caricare l'interfaccia ITest.

<?php

function __autoload($name) {
    
var_dump($name);
}

class 
Foo implements ITest {
}

/*
string(5) "ITest"

Fatal error: Interface 'ITest' not found in ...
*/
?>

Example #3 Autocaricamento con gestione delle eccezioni per 5.3.0+

Questo esempio solleva un'eccezione e dimostra come intercettarla con il blocco try/catch.

<?php
function __autoload($name) {
    echo 
"Si vuole caricare $name.\n";
    throw new 
Exception("Impossibile caricare $name.");
}

try {
    
$obj = new NonLoadableClass();
} catch (
Exception $e) {
    echo 
$e->getMessage(), "\n";
}
?>

Il precedente esempio visualizzerà:

Si vuole caricare NonLoadableClass.
Impossibile caricare NonLoadableClass.

Example #4 Autocaricamento con gestione delle eccezioni per 5.3.0+ - Classe dell'eccezione personalizzata mancante

Questo esempio solleva un'eccezione per una eccezione personalizzata non caricabile.

<?php
function __autoload($name) {
    echo 
"Si vuole caricare $name.\n";
    throw new 
MissingException("Impossibile $name.");
}

try {
    
$obj = new NonLoadableClass();
} catch (
Exception $e) {
    echo 
$e->getMessage(), "\n";
}
?>

Il precedente esempio visualizzerà:

Si vuole caricare NonLoadableClass.
Si vuole caricare MissingException.

Fatal error: Class 'MissingException' not found in testMissingException.php on line 4

Vedere anche: