Thursday 28 September 2017

Cgi Binario Options


Disclaimer: opzioni binarie forex trading e comportano dei rischi. Modello di Business e guadagni: I risultati sono subordinata alla scelta della corretta direzione di un prezzo beni, dalla data prezzo di esercizio, per il periodo di scadenza selezionato. Una volta che viene avviato un commercio, i commercianti ricevono una schermata di conferma che mostra l'attività, prezzo di esercizio, la direzione scelta (call o put), e l'importo dell'investimento. Quando viene richiesto da questo schermo, commerci avvierà in 3 secondi a meno che il commerciante preme il pulsante di annullamento. TRBinaryOptions offre l'opzione più veloce scade a disposizione del pubblico e le transazioni può essere il più veloce di 15 minuti in opzioni binarie regolari, e il più velocemente 60 secondi nella seconda piattaforma 60. Anche se il rischio quando trading di opzioni binarie è fissato per ogni singolo commercio, i mestieri sono in diretta ed è possibile perdere un investimento iniziale, in particolare se un commerciante decide di mettere tutto il suo investimento per un singolo commercio di animali vivi. Si consiglia vivamente che i commercianti scelgono una strategia di gestione del proprio denaro che limita il Totale delle operazioni consecutive o investimento totale in sospeso. Si consiglia di utilizzare Mozilla Firefox o Google Chrome browser web quando gli scambi in TRBinaryOptions. Grazie per la vostra interesse7 Opzioni binarie 7 opzioni binarie Come fare soldi online con le opzioni binarie Trading Dal 2008, l'investimento e fare soldi online con le opzioni binarie è diventato sempre più attraente per gli investitori e gli individui che investono in azioni. azioni, valute e materie prime. Ci sono solo due opzioni in commercio binario qui l'uso del termine binario. E 'quasi come una scommessa, nel senso che si sta scommettendo che un'attività aumenterà o diminuirà di valore nel corso di un determinato periodo di tempo. trading binario fornisce opzioni per il mercato di autoregolarsi e offre l'opportunità di tenere a freno gli stock sopravvalutati speculando che una società vedrà una diminuzione del suo valore. Nel trading di opzioni binarie si sta scommettendo che il prezzo di un bene specifico sarà aumentare o diminuire nel corso di un determinato periodo. Lei ha il lusso di conoscere il vostro rischio e rendimento in attacco, prima che il commercio ha mai luogo. trading binario è un ottimo modo per entrare nel mercato senza un grande esborso di riserva di capitale o di capitale richiesto. Approfitta delle informazioni offerto su 7binaryoptions per ottenere una migliore comprensione delle opzioni binarie e forex trading per fare soldi online. Inizia con 3 semplici passi: Scegliere un broker dalla lista qui sotto Reuters 8211 Financial News CHICAGO (Reuters) - Le Reserve039s US Federal lunga fase di stallo 039liftoff039 dei tassi di interesse può finalmente decollare questo anno, come i politici dal presidente Janet Yellen il Venerdì di regionale leader negli Stati Uniti ha segnalato che l'era del denaro facile sta volgendo al termine. (Reuters) - Johnson amp Johnson ha detto il Venerdì che uno stato tribunale giuria nel Missouri era tornato un verdetto a suo favore nella sua ultima prova per derivare da migliaia di cause legali relativi prodotti di talco a base company039s può aumentare il rischio di cancro ovarico. (Reuters) - L'oleodotto Keystone XL non ha bisogno di essere in acciaio Stati Uniti, nonostante un ordine esecutivo del presidente Donald Trump giorni dopo il suo insediamento che richiedono dell'acciaio sul mercato interno in nuovi gasdotti, la Casa Bianca ha detto il Venerdì. LONDRA (Reuters) - Deutsche Boerse amministratore delegato Carsten Kengeter ha detto che sta continuando i preparativi per una fusione con il London Stock Exchange. nonostante il LSE039s rifiuto di vendere la sua piattaforma di trading MTS italiano. (Reuters) - Il SampP 500 e il Nasdaq ha chiuso la sesta settimana consecutiva di guadagni con una seduta piatta dopo Janet Yellen ha segnalato che la Federal Reserve è impostato ad alzare i tassi di interesse questo mese se l'occupazione e altri dati economici reggono. (Reuters) - Giro società provenienti Uber Technologies Inc UBER. UL ha per anni utilizzato uno strumento segreto per ingannare le autorità nei mercati in cui il suo servizio ha dovuto affrontare la resistenza dalle forze dell'ordine o è stato vietato, il New York Times, citando fonti. (Reuters) - Stati Uniti high-end catena di grandi magazzini Neiman Marcus ha assunto banca di investimenti Lazard Ltd per esplorare modi per rafforzare il suo bilancio che cerca sollievo da 4,9 miliardi di debiti, le persone vicine alla vicenda ha detto il Venerdì. PARISLONDON (Reuters) - France039s PSA Group ha stretto un accordo con General Motors per acquistare la divisione di Opel in perdita gli Stati Uniti carmaker039s, due fonti con conoscenza della materia ha detto a Reuters. (Reuters) - Comcast Corp039s NBCUniversal ha investito 500 milioni di proprietario Snapchat Snap Inc. in base a una nota il Venerdì, la sua ultima mossa volta a guidare la crescita digitale come più spettatori online per i propri contenuti preferiti. (Reuters) - Le borse Caterpillar Inc039s guadagnato il Venerdì, il giorno dopo statunitensi delle forze dell'ordine hanno fatto irruzione tre delle strutture Illinois company039s, come l'amministrazione Trump ha promesso più severo controllo di multinationals039 di importazione ed esportazione delle pratiche. Robot consigliato Chi siamo 038 Disclaimer Disclaimer: Le opzioni binarie 7 non potrà essere ritenuto responsabile per eventuali perdite o danni derivanti da dipendenza sulle informazioni contenute all'interno di questo sito. I dati contenuti in questo sito non sono necessariamente in tempo reale né accurata, e le analisi sono le opinioni dell'autore. 7binaryoptions è solo un sito web che offre informazioni - non un broker regolamentato o consulente per gli investimenti, e nessuna delle informazioni ha lo scopo di garantire i risultati futuri. Binary trading delle opzioni sul margine coinvolge ad alto rischio e non è adatto per tutti gli investitori. Come un prodotto leveraged le perdite sono in grado di superare i depositi iniziali e il capitale è a rischio. Prima di decidere di negoziare opzioni binarie o qualsiasi altro strumento finanziario si dovrebbe considerare con attenzione i vostri obiettivi di investimento, livello di esperienza e propensione al rischio. In accordo con le linee guida FTC, 7BinaryOptions ha rapporti finanziari con alcuni dei prodotti e servizi menzionati in questo sito, e 7BinaryOptions può essere compensata se i consumatori scelgono di fare clic su questi collegamenti nel nostro contenuto e, infine, iscriversi per loro. Utilizzando il presente sito web siete d'accordo con le limitazioni e le esclusioni di responsabilità di cui al presente disclaimer e la pagina di responsabilità separata. Se non sei d'accordo con loro, non si deve utilizzare questo sito web. NewsletterCGI - Maniglia Common Gateway Interface richieste e le risposte DESCRIZIONE CGI. pm è una soluzione stabile, completo e maturo per la lavorazione e la preparazione di richieste HTTP e le risposte. Caratteristiche principali, tra cui l'invio di moduli di elaborazione, upload di file, la lettura e la scrittura, biscotti interrogazione generazione stringa e la manipolazione, e la trasformazione e preparazione di intestazioni HTTP. Alcune utility generazione HTML sono inclusi anche. CGI. pm funziona molto bene in un ambiente di vaniglia CGI. pm e viene fornito con il supporto incorporato per modperl e modperl2 così come FastCGI. Ha il vantaggio di aver sviluppato e perfezionato nel corso di 10 anni, con ingresso da decine di collaboratori e di essere distribuito su migliaia di siti web. CGI. pm è stato incluso nella distribuzione di Perl dal Perl 5.4, ed è diventato uno standard de-facto. PROGRAMMAZIONE DI STILE Ci sono due stili di programmazione con CGI. pm, uno stile orientato agli oggetti e uno stile function-oriented. Nello stile orientato agli oggetti si crea uno o più oggetti CGI e quindi utilizzare i metodi degli oggetti per creare i vari elementi della pagina. Ogni oggetto CGI inizia con l'elenco dei parametri denominati che sono stati passati allo script CGI dal server. È possibile modificare gli oggetti, salvarli in un file o database e ricreare. Poiché ogni oggetto corrisponde allo stato dello script CGI, e poiché ogni oggetti lista di parametri è indipendente dagli altri, questo permette di salvare lo stato dello script e ripristinare in un secondo momento. Ad esempio, utilizzando lo stile orientato agli oggetti, ecco come si crea una semplice pagina HTML Ciao Mondo: Nello stile funzionalità orientata, vi è un oggetto CGI di default che avete a che fare raramente con direttamente. Invece basta chiamare funzioni per recuperare i parametri CGI, creare tag HTML, gestire i cookie, e così via. Ciò fornisce un'interfaccia di programmazione più pulita, ma si limita ad usare un oggetto CGI alla volta. L'esempio seguente stampa la stessa pagina, ma utilizza l'interfaccia function-oriented. Le differenze principali sono che ora abbiamo bisogno di importare un insieme di funzioni nel nostro spazio nome (di solito le funzioni standard), e noi non hanno bisogno per creare l'oggetto CGI. Gli esempi in questo documento usano principalmente lo stile orientato agli oggetti. Vedere come importare le funzioni per importanti informazioni sulla programmazione delle funzioni orientata in CGI. pm CHIAMATA routine CGI. PM ROUTINE maggior CGI. pm accettano vari argomenti, ben 20 quelli talvolta opzionali Per semplificare questa interfaccia, tutte le routine utilizzano una chiamata argomento di nome stile che assomiglia a questo: Ogni nome argomento è preceduto da un trattino. Nessuno dei due casi, né di ordine questioni nella lista degli argomenti. tipo, - Tipo, e TIPO sono tutti accettabili. Infatti, solo il primo argomento deve iniziare con un trattino. Se un trattino è presente nel primo argomento, CGI. pm assume trattini per quelle successive. Diverse routine sono comunemente chiamati con un solo argomento. Nel caso di queste routine è possibile fornire il singolo argomento senza un nome dell'argomento. header () sembra essere una di queste routine. In questo caso, il singolo argomento è il tipo di documento. Altri tali routine sono documentate qui di seguito. A volte gli argomenti con nome si aspettano uno scalare, a volte un riferimento ad un array, e, talvolta, un riferimento ad un hash. Spesso, si può passare qualsiasi tipo di argomento e la routine farà tutto ciò che è più appropriato. Ad esempio, la routine param () viene utilizzato per impostare un parametro CGI a un singolo o un valore più valori. I due casi sono riportati di seguito: Un gran numero di routine in CGI. pm realmente arent specificamente definito nel modulo, ma vengono generati automaticamente in base alle esigenze. Queste sono le scorciatoie HTML, routine che generano i tag HTML per l'utilizzo in pagine generate dinamicamente. tag HTML hanno entrambi gli attributi (le coppie di AttributeValue all'interno del tag stesso) e il contenuto (la parte tra l'apertura e coppie di chiusura.) Per distinguere tra gli attributi e contenuti, CGI. pm utilizza la convenzione di passare attributi HTML come riferimento hash come primo argomento, e il contenuto, se del caso, come tutti gli argomenti successivi. Esso funziona in questo modo: i tag HTML sono descritte in dettaglio più avanti. Molti nuovi arrivati ​​CGI. pm sono perplessi dalla differenza tra le convenzioni di chiamata per i collegamenti HTML, che richiedono parentesi graffe intorno attributi del tag HTML, e le convenzioni di chiamata per altre routine, che riescono a generare attributi senza le parentesi graffe. Non essere confuso. Per comodità le parentesi graffe sono opzionali in tutti, ma le scorciatoie HTML. Se si desidera, è possibile utilizzare le parentesi graffe quando si chiama qualsiasi routine che prende argomenti con nome. Per esempio: se si utilizza l'opzione - w, sarete avvertiti che alcuni CGI. pm nomi degli argomenti conflitto con funzioni built-in Perl. La più frequente di questi è l'argomento - Valori, utilizzato per creare menu con più valori, cluster pulsanti radio e simili. Per ovviare a questo avviso, si dispone di diverse scelte: utilizzare un altro nome per l'argomento, se disponibile. Ad esempio, - value è un alias per - Valori. Modificare la capitalizzazione, per esempio - Valori Mettere le virgolette attorno al nome argomento, ad esempio - Valori molte routine farà qualcosa di utile con un argomento di nome che doesnt riconoscere. Ad esempio, è in grado di produrre campi di intestazione HTTP non standard, fornendo loro come argomenti con nome: Questo produrrà la seguente intestazione HTTP non standard: Si noti il ​​modo in cui sottolineature vengono tradotti automaticamente nella trattini. routine HTML generatrici eseguono un diverso tipo di traduzione. Questa funzione consente di tenere il passo con i rapidi cambiamenti standard HTTP e HTML. Creando un nuovo oggetto QUERY (Object-Oriented STILE): Questo analizzerà l'ingresso (da POST, GET e DELETE metodi) e conservarla in un oggetto chiamato perl5 query. Qualsiasi filehandle dal caricamento di file avranno il loro ripristino posizione all'inizio del file. Creando un nuovo oggetto DOMANDA DA un file di input Se si fornisce un handle di file per il metodo new (), leggerà i parametri dal file (o STDIN, o qualsiasi altra cosa). Il file può essere in una qualsiasi delle forme che descrivono di seguito nella sezione di debug (cioè una serie di ritorno a capo delimitato coppie TAGVALUE funzionerà). Per comodità, questo tipo di file viene creato con il metodo save () (vedi sotto). registrazioni multiple possono essere salvati e ripristinati. puristi Perl saranno felici di sapere che questa sintassi accetta i riferimenti a file maniglie, o anche riferimenti a FILEHANDLE gocce, che è il modo ufficiale per passare un filehandle: È anche possibile inizializzare l'oggetto CGI con un FileHandle o IO :: oggetto File. Se si utilizza la funzione di interfaccia-oriented e desidera inizializzare stato CGI da un handle di file, il modo per farlo è con restoreparameters (). In questo modo (ri) inizializzare l'oggetto predefinito CGI dal manico file indicato. È anche possibile inizializzare l'oggetto query da un riferimento hash: o da una, stringa di query di tipo escape URL correttamente formattato: o da un oggetto CGI preesistente (attualmente questo cloni l'elenco dei parametri, ma nessuno degli altri campi specifici oggetto, ad come autoescaping): Per creare una query vuota, inizializzare da una stringa vuota o hash: recupero di un elenco di parole chiave dalla query: Se lo script è stato invocato come il risultato di una ricerca ltISINDEXgt, le parole chiave analizzati possono essere ottenuti come un array utilizzando le parole chiave () metodo. Recupero I nomi di tutti i parametri passati allo script: Se lo script è stato invocato con una lista di parametri (ad esempio name1value1ampname2value2ampname3value3), il metodo param () restituirà i nomi di parametro in una lista. Se lo script è stato invocato come uno script ltISINDEXgt e contiene una stringa senza e commerciali (ad esempio value1value2value3). ci sarà un unico parametro denominato parole chiave che contengono le parole chiave delimitato da. NOTA: A partire dalla versione 1.5, la serie di nomi di parametro restituiti sarà nello stesso ordine in cui sono state presentate dal browser. Solitamente questo ordine è la stessa come l'ordine in cui sono definiti i parametri nella forma (tuttavia, questa parte è neanche della specifica, e così isnt garantite). Recupero il valore o valori di un parametro denominato UNICO: Passa il metodo param () un singolo argomento per andare a prendere il valore del parametro di nome. Se il parametro è multivalore (ad esempio, da più selezioni in un elenco a scorrimento), si può chiedere di ricevere una matrice. Altrimenti il ​​metodo restituirà un singolo valore. Se un valore non è dato nella stringa di query, come nella query name1ampname2, verrà restituito come una stringa vuota. Se il parametro non esiste affatto, allora param () restituirà undef in un contesto scalare, e la lista vuota in un contesto di lista. Impostando il valore (S) di un parametro denominato: Questo imposta il valore per il parametro foo chiamato ad una matrice di valori. Questo è un modo per modificare il valore di un campo dopo lo script è stata invocata una volta prima. (Un altro modo è con il parametro - override accettato da tutti i metodi che generano elementi dei moduli.) Param () riconosce anche uno stile parametro denominato di convocazione descritto in dettaglio più avanti: AGGIUNTA DI VALORI supplementare ad un parametro denominato: Questo aggiunge un valore o una lista dei valori al parametro di nome. I valori vengono aggiunti alla fine del parametro se esiste già. In caso contrario, si crea il parametro. Si noti che questo metodo riconosce solo l'argomento di nome chiamando sintassi. L'importazione di tutti PARAMETRI IN uno spazio dei nomi: Questo crea una serie di variabili nello spazio dei nomi R. Ad esempio, R :: foo, R: foo. Per elenchi di parole chiave, viene visualizzata una variabile :: parole chiave R. Se non viene dato spazio dei nomi, questo metodo assume D. ATTENZIONE: Non importare nulla in questo formato è un grave rischio per la sicurezza. NOTA 1: Variabile nomi si trasformano quanto occorra, in nomi di variabili legali Perl. Tutti i caratteri non-legali si trasformano in sottolineatura. Se è necessario mantenere i nomi originali, è necessario utilizzare il metodo param () invece di accedere alle variabili CGI per nome. NOTA 2: Nelle versioni più vecchie, questo metodo è stato chiamato import (). A partire dalla versione 2.20, questo nome è stata rimossa completamente per evitare conflitti con il built-in Perl operatore modulo di importazione. ELIMINAZIONE DI UN PARAMETRO COMPLETAMENTE: Questo cancella completamente un elenco di parametri. A volte utile per il ripristino dei parametri che non volete tramandata tra le chiamate di script. Se si utilizza l'interfaccia di chiamata di funzione, utilizzare Delete () invece per evitare conflitti con Perls incorporati operatore delete. CANCELLAZIONE DI TUTTI I PARAMETRI: Questo cancella completamente l'oggetto CGI. Potrebbe essere utile per garantire che tutti i valori di default vengono prese quando si crea un form fill-out. Utilizzare DeleteAll () invece se si utilizza l'interfaccia di chiamata di funzione. Gestire gli argomenti NON-urlencoded Se i dati postato non è di tipo applicationx-www-form-urlencoded o multipartform-dati, quindi i dati inviati non saranno trattati, ma invece essere restituiti così come sono in un parametro denominato POSTDATA. Per recuperarlo, utilizzare il codice in questo modo: Allo stesso modo se i dati puted possono essere recuperati con codice come questo: (se non sai che cosa i mezzi precedenti, non vi preoccupate a questo proposito Interessa solo le persone cercando di utilizzare CGI per l'elaborazione XML e altri specializzati. compiti) aCCESSO dIRETTO aLLA lISTA dEI pARAMETRI:. Se è necessario accedere alla lista dei parametri in modo che isnt coperto da metodi da applicare nei paragrafi precedenti, si può ottenere un riferimento diretto ad esso chiamando il metodo paramfetch () con il il nome del parametro. Ciò restituirà un riferimento ad array al parametro di nome, che poi può manipolare in qualsiasi modo tu voglia. È inoltre possibile utilizzare uno stile di argomento denominato utilizzando l'argomento - name. Recuperare la lista parametri come un hash: Molte persone vogliono per andare a prendere l'intera lista di parametri come un hash in cui le chiavi sono i nomi dei parametri CGI, ei valori sono i valori dei parametri. Il metodo Vars () fa questo. Chiamato in un contesto scalare, restituisce la lista dei parametri come riferimento hash legato. La modifica di una chiave cambia il valore del parametro nell'elenco dei parametri CGI sottostante. Chiamato in un contesto di lista, restituisce l'elenco dei parametri come un hash ordinaria. Ciò consente di leggere il contenuto della lista dei parametri, ma non di modificarlo. Quando si utilizza questo, la cosa che si deve guardare fuori per sono i parametri CGI multivalore. Perché un hash non può distinguere tra scalare e contesto di lista, i parametri multivalore saranno restituiti sotto forma di stringa imballato, separati dal carattere 0 (zero). È necessario suddividere questa stringa confezionato al fine di ottenere i singoli valori. Questa è la convenzione introdotto molto tempo fa da Steve Brenner nel suo modulo cgi-lib. pl per Perl versione 4. Se si desidera utilizzare Vars () in funzione, importare il: set cgi-lib di chiamate di funzione (vedi anche la sezione sulla compatibilità CGI-LIB). Salvare lo stato dello script da un file: Questo scriverà lo stato attuale del modulo per il filehandle fornito. Si può leggere di nuovo nella fornendo un filehandle al metodo new (). Si noti che il filehandle può essere un file, un tubo, o qualunque sia il formato del file salvato è: sia il nome e il valore sono URL sfuggito. parametri CGI più valori sono rappresentati come nomi ripetuti. Un record di sessione è delimitata da un singolo simbolo. È possibile scrivere più record e leggere di nuovo con diverse chiamate alla nuova. È possibile farlo attraverso diverse sessioni aprendo il file in modalità accodamento, che consente di creare primitivi libri degli ospiti, o per mantenere una cronologia delle query degli utenti. Ecco un breve esempio di creazione di più record di sessione: Il formato di file utilizzato per saverestore è identico a quello utilizzato dal formato di scambio dei dati Centri di Whitehead Genome Boulderio, e può essere manipolato e anche databased utilizzando le utilità Boulderio. Vedere per ulteriori dettagli. Se si desidera utilizzare questo metodo dall'interfaccia function-oriented (non-OO), il nome esportato per questo metodo è saveparameters (). Recupero ERRORI CGI Gli errori possono verificarsi durante l'elaborazione di input da parte dell'utente, in particolare durante l'elaborazione di file caricati. Quando si verificano questi errori, CGI si fermerà l'elaborazione e restituire un elenco di parametri vuota. È possibile verificare l'esistenza e la natura degli errori usando la funzione cgierror (). I messaggi di errore sono formattati come codici di stato HTTP. È possibile inserire il testo di errore in una pagina HTML, o usarlo come il valore dello stato HTTP: Quando si utilizza la funzione di interfaccia orientata (vedere la sezione successiva), gli errori si possono verificare solo la prima volta che si chiama param (). Essere pronti per utilizzare l'interfaccia orientata alle funzioni Per utilizzare la funzione di interfaccia orientata, è necessario specificare che le routine di CGI. pm o insiemi di routine per importare nel vostro script namespace. C'è un piccolo overhead associato con tale importazione, ma neanche tanto. I metodi elencati saranno importati nel package corrente è possibile chiamare direttamente senza creare un oggetto CGI prima. Questo esempio mostra come importare il parametro () e l'intestazione () metodi, e poi usarli direttamente: Più frequentemente, youll importare set comune di funzioni facendo riferimento ai gruppi in base al nome. Tutti i set di funzioni sono preceduti con un: carattere come in: HTML3 (per i tag definiti nello standard HTML 3). Ecco un elenco della funzione di imposta è possibile importare: Importa tutti i metodi CGI di gestione, come ad esempio param (). pathinfo () e simili. Importa tutti i metodi sotto forma di generazione di riempimento-out, come il campo di testo (). Importa tutti i metodi che generano HTML 2.0 elementi standard. Importa tutti i metodi che generano HTML 3.0 elementi (come ad esempio lttablegt, ltsupergt e ltsubgt). Importa tutti i metodi che generano HTML 4 elementi (come ad esempio ltabbrevgt, ltacronymgt e lttheadgt). Importare i tag ltblinkgt, ltfontsizegt e ltcentergt. Importa tutti i collegamenti HTML-generazione (cioè HTML2, HTML3, HTML4 e Netscape) Importa caratteristiche standard, HTML2, HTML3, HTML4, forma e CGI. Importare tutti i metodi disponibili. Per l'elenco completo, vedere il codice CGI. pm, dove viene definito il EXPORTTAGS variabili. Se si importa un nome di funzione che non fa parte di CGI. pm, il modulo tratterà come un nuovo tag HTML e generare la subroutine appropriata. È quindi possibile utilizzare come qualsiasi altro tag HTML. Questo è fornire per lo standard HTML rapida evoluzione. Ad esempio, dire Microsoft esce con un nuovo tag chiamato ltgradientgt (che fa sì che il desktop degli utenti di essere invaso da un riempimento sfumato ruotare fino a quando le sue ripartenze della macchina). Non avete bisogno di attendere una nuova versione di CGI. pm per iniziare ad usarlo subito: Si noti che nell'interesse di CGI. pm velocità di esecuzione non usa la sintassi Exporter standard per specificare i simboli di carico. Questo potrebbe cambiare in futuro. Se si importa una delle CGI o di forma che generano i metodi di mantenimento dello stato, un oggetto predefinito CGI verrà creato e inizializzato automaticamente la prima volta che si utilizza uno qualsiasi dei metodi che richiedono uno per essere presente. Questo include param (). campo di testo() . inviare () e simili. (Se avete bisogno di un accesso diretto all'oggetto CGI, lo si può trovare nella variabile globale CGI :: Q). Importando metodi CGI. pm, è possibile creare script visivamente eleganti: Oltre ai set di funzioni, ci sono una serie di pragma che è possibile importare. Pragma, che sono sempre precedute da un trattino, cambiare il modo in cui funziona CGI. pm in vari modi. Pragma, funzione imposta, e singole funzioni possono tutti essere importati nella linea stesso uso (). Ad esempio, l'istruzione seguente uso importa il set standard di funzioni e abilita la modalità di debug (Pragma debug): L'attuale elenco dei pragma è la seguente: quando si utilizza CGI - Qualsiasi. allora qualsiasi metodo che l'oggetto query doesnt riconoscere sarà interpretato come un nuovo tag HTML. Questo consente di supportare la prossima hoc estensione HTML annuncio. Questo ti permette di andare selvaggio con tag nuovi e non supportate: Dato che l'utilizzo ltcitegtanyltcitegt provoca alcun nome del metodo compilato male devono essere interpretati come un tag HTML, usare con cautela o per niente. Questo fa sì che le modalità indicate caricati automaticamente da compilare in anticipo, piuttosto che rimandati a dopo. Questo è utile per gli script che vengono eseguiti per un lungo periodo di tempo sotto FastCGI o modperl, e per quelli destinati ad essere scricchiolava da Malcolm Beatties Perl compilatore. Usalo in combinazione con i metodi o le famiglie di metodo che si intende utilizzare. Si noti che utilizzando il pragma - compile in questo modo avrà sempre l'effetto di importare le funzioni compilate nello spazio dei nomi corrente. Se si desidera compilare senza importare utilizzare il metodo di compilazione () invece: Questo è particolarmente utile in un ambiente modperl, in cui si potrebbe desiderare di precompilare tutte le routine CGI in uno script di avvio, e quindi importare le funzioni singolarmente in ogni script modperl. Di default il modulo CGI implementa un comportamento a preservare stato chiamato campi appiccicose. Il modo in cui funziona è che se si sta rigenerare un modulo, i metodi che generano i valori dei campi modulo interrogherà param () per vedere se i parametri denominato allo stesso modo sono presenti nella stringa di query. Se trovano un parametro come il nome, la useranno per impostare i valori di default. A volte questo non è ciò che si desidera. Il pragma - nosticky impedisce questo comportamento. È inoltre possibile modificare selettivamente il comportamento appiccicoso in ogni elemento che si genera. Aggiungi automaticamente attributi indice scheda per ogni campo del modulo. Con questa opzione disattivata, è comunque possibile aggiungere indici di tabulazione manualmente passando un'opzione - tabindex per ogni metodo di campo generatrice. Ciò mantiene CGI. pm da compresi params undef nella lista dei parametri. Per impostazione predefinita, le versioni CGI. pm 2,69 e superiori emettere XHTML (w3.orgTRxhtml1). Il pragma - noxhtml disabilita questa funzione. Grazie a Michalis Kabrianis ltkabrianishellug. grgt per questa funzione. Se starthtml () s parametro - dtd specifica un HTML 2.0, 3.2, 4.0 o 4.01 DTD, XHTML verrà automaticamente disattivata senza la necessità di utilizzare questo pragma. Questo rende CGI. pm trattare tutti i parametri come stringhe UTF-8. Utilizzare questo con cura, in quanto essa possa interferire con il processo di upload binari. E 'meglio selezionare manualmente i campi sono tenuti a restituire stringhe UTF-8 e convertirli utilizzando il codice in questo modo: Questo rende CGI. pm produrre un adeguato intestazione per un NPH (nessuna intestazione analizzato) script. Potrebbe essere necessario fare altre cose oltre a dire il server che lo script è NPH. Vedere la discussione degli script NPH sotto. Separare le coppie NameValue nel parametro CGI stringhe di query con un punto e virgola, piuttosto che e commerciali. Per esempio: le stringhe di query e virgola-delimitati vengono sempre accettati, e saranno emessi da selfurl () e querystring (). newstyleurls diventato il default nella versione 2.64. Separare le coppie NameValue nel parametro CGI stringhe di query con e commerciali, piuttosto che un punto e virgola. Questo non è più il default. Questo sostituisce il caricatore automatico in modo che qualsiasi funzione nel programma che non viene riconosciuto si riferisce a CGI. pm per una possibile valutazione. Questo permette di utilizzare tutte le funzioni CGI. pm senza aggiungere al vostro tavolo simbolo, che è fonte di preoccupazione per gli utenti ModPerl che sono preoccupati per il consumo di memoria. Attenzione: quando - autoload è a tutti gli effetti, non è possibile utilizzare la modalità di poesia (funzioni senza la parentesi). Utilizzare hr () piuttosto che hr. o aggiungere qualcosa di simile uso sottomarini qwhr intestazione p alla parte superiore dello script. Questo disattiva le funzioni di elaborazione della riga di comando. Se si desidera eseguire uno script CGI. pm dalla riga di comando per la produzione di HTML, e non volete per leggere i parametri CGI dalla riga di comando o STDIN, quindi utilizzare questo pragma: Questo accende pieno debug. Oltre a leggere gli argomenti CGI dalla lavorazione della riga di comando, CGI. pm farà una pausa e cercare di leggere gli argomenti da STDIN, producendo il messaggio (modalità offline: entrare coppie NameValue su standard di input) caratteristiche. Si veda la sezione di debug per ulteriori dettagli. CGI. pm in grado di elaborare file inserito. Di solito si spooling il file caricato in una directory temporanea, quindi elimina il file quando fatto. Tuttavia, questo apre il rischio di intercettazioni come descritto nella sezione di caricamento di file. Un altro CGI script di autore potrebbe sbirciare in questa dati durante il caricamento, anche se si tratta di informazioni riservate. Sui sistemi Unix, il - privatetempfiles pragma farà sì che il file temporaneo di essere scollegato, non appena si è aperta e prima che i dati è scritto in esso, la riduzione, ma non eliminando il rischio di intercettazione (non vi è ancora un potenziale condizione di competizione). Per rendere la vita più difficile per l'attaccante, il programma sceglie i nomi File Temporanei calcolando un 32 bit di checksum delle intestazioni HTTP in ingresso. Per assicurarsi che il file temporaneo non può essere letto da altri script CGI, usare il programma suEXEC o un wrapper CGI per eseguire lo script. Il file temporaneo viene creato con la modalità 0600 (né mondo né gruppo leggibile). La directory temporanea viene selezionato utilizzando il seguente algoritmo: Ognuno di questi luoghi è verificato che si tratta di una directory ed è scrivibile. In caso contrario, l'algoritmo tenta la scelta successiva. FORME SPECIALI PER IMPORTAZIONE FUNZIONI HTML-TAG Molti dei metodi generano tag HTML. Come descritto di seguito, le funzioni di tag generano automaticamente sia il tag di apertura e di chiusura. Per esempio: Ci saranno alcuni momenti in cui si desidera produrre l'inizio e tag di chiusura da soli. In questo caso, è possibile utilizzare il tagname inizio forma e nometag fine. come in: Con poche eccezioni (descritte di seguito), avviare funzioni TagName e TagName finale non vengono generati automaticamente quando si utilizza CGI. Tuttavia, è possibile specificare i tag che si desidera generare funzioni startend per mettendo un asterisco davanti al loro nome, o, in alternativa, la richiesta sia avvia nometag o tagname fine nella lista di importazione. In questo esempio, le seguenti funzioni vengono generate in aggiunta a quelle standard: 1. starttable () (genera un tag lttablegt) 2. endtable () (genera un tag lttablegt) 3. startul () (genera un tag ltulgt) 4 . endul () (genera un tag ltulgt) che genera documenti dinamici la maggior parte delle funzioni CGI. pms che fare con la creazione di documenti al volo. In genere si produrrà l'intestazione HTTP prima, seguito dal documento stesso. CGI. pm fornisce funzioni per la generazione di intestazioni HTTP di vario tipo e per la generazione di HTML. Per la creazione di immagini GIF, vedere il modulo GD. pm. Ognuna di queste funzioni produce un frammento di HTML o HTTP, che è possibile stampare direttamente modo che venga visualizzato nella finestra del browser, aggiungere una stringa, o salvare in un file per un uso successivo. CREAZIONE DI UN HTTP STANDARD INTESTAZIONE: Normalmente la prima cosa che farà in qualsiasi script CGI è stampare un'intestazione HTTP. Questo dice al browser che tipo di documento da aspettarsi, e fornisce altre informazioni facoltative, come la lingua, la data di scadenza, e se memorizzare nella cache il documento. L'intestazione può anche essere manipolato a fini speciali, come server push e pay per view pagine. header () restituisce il Content-type: intestazione. È possibile fornire il proprio tipo MIME se si sceglie, altrimenti il ​​default è texthtml. Un secondo parametro opzionale specifica il codice di stato e un messaggio leggibile. Ad esempio, è possibile specificare 204, Nessuna risposta a creare uno script che indica al browser di non fare niente. Si noti che RFC 2616 si aspetta la fase leggibile per essere lì, così come il codice di stato numerico. L'ultimo esempio mostra lo stile argomenti con il nome per il passaggio di argomenti per i metodi di CGI che utilizzano parametri denominati. parametri riconosciuti sono tipo. - status. - scade . e - Cookie. Eventuali altri parametri denominati saranno spogliati dei loro trattini iniziali e trasformati in campi di intestazione, che consente di specificare qualsiasi intestazione HTTP che desiderate. sottolineature interni saranno trasformati in trattini: maggior parte dei browser non memorizzare nella cache l'output di script CGI. Ogni volta che il browser ricarica la pagina, lo script viene richiamato di nuovo. È possibile modificare questo comportamento con il parametro - expires. Quando si specifica un intervallo di scadenza assoluta o relativa a questo parametro, alcuni browser e server proxy memorizza nella cache l'output script fino alla data di scadenza indicata. Le seguenti forme sono tutte valide per il campo - expires: Il parametro - Cookie genera un colpo di testa che indica al browser di fornire un magic cookie durante tutte le operazioni successive con lo script. Alcuni cookie hanno un formato speciale che include gli attributi interessanti come il tempo di scadenza. Utilizzare il metodo cookie () per creare e recuperare i cookie di sessione. Il parametro - nph, se impostato su un valore vero, emetterà le intestazioni corrette per lavorare con un NPH (no-parse-header) script. Questo è importante utilizzare con alcuni server che si aspettano tutti i loro script da NPH. Il parametro - charset può essere utilizzato per controllare il set di caratteri inviato al browser. Se non fornito, il valore predefinito è ISO-8859-1. Come effetto collaterale, questo imposta il metodo charset () pure. Il parametro - attachment può essere utilizzato per trasformare la pagina in un allegato. Invece di visualizzare la pagina, alcuni browser chiederà all'utente di salvare su disco. Il valore dell'argomento è il nome proposto per il file salvato. Al fine di far funzionare tutto questo, potrebbe essere necessario impostare il tipo di applicationoctet-stream. Il parametro - p3p aggiungerà un tag P3P per l'intestazione in uscita. Il parametro può essere un rifarray o una stringa delimitato da spazi di tag P3P. Ad esempio: In entrambi i casi, l'intestazione in uscita sarà formattato come: CGI. pm accetterà valide intestazioni multilinea quando ogni riga è separata con un valore CRLF (rn sulla maggior parte delle piattaforme) seguita da almeno uno spazio. Per esempio: non valido di ingresso intestazione multi-linea attiverà in un'eccezione. Quando si ricevono le intestazioni multilinea, CGI. pm sarà sempre li uscita posteriore come una singola linea, in base alle regole di piegatura di RFC 2616: le nuove linee saranno rimossi, mentre lo spazio bianco rimane. Generazione di un colpo di testa RIDIREZIONE A volte non avete voglia di produrre un documento da soli, ma semplicemente reindirizzare il browser altrove, forse la scelta di un URL in base all'ora del giorno o l'identità dell'utente. Il metodo redirect () reindirizza il browser a un URL diverso. Se si utilizza il reindirizzamento in questo modo, non si dovrebbe stampare un colpo di testa pure. È consigliabile utilizzare sempre URL completi (tra cui il http: o ftp: parte) nelle richieste di reindirizzamento. Gli URL relativi non funziona correttamente. È inoltre possibile utilizzare argomenti con nome: Tutti i nomi argomenti riconosciuti dalla intestazione () vengono anche riconosciuti dalla redirect (). Tuttavia, la maggior parte delle intestazioni HTTP, inclusi quelli generati da - Cookie e - target, vengono ignorati dal browser. Il parametro - nph, se impostato su un valore vero, emetterà le intestazioni corrette per lavorare con un NPH (no-parse-header) script. Questo è importante per l'uso con alcuni server, come ad esempio Microsoft IIS, che si aspettano tutti i loro script da NPH. Il parametro - status imposterà lo stato del reindirizzamento. HTTP definisce tre diversi codici di stato possibile reindirizzamento: L'impostazione di default se non specificato è 302, che significa spostato temporaneamente. Si può modificare lo stato ad un altro codice di stato, se lo si desidera. Sappiate che la modifica dello stato di qualcosa di diverso da 301, 302 o 303 sarà probabilmente rompere reindirizzamento. Si noti che la frase leggibile si aspetta anche di essere presenti a conformarsi con la RFC 2616, paragrafo 6.1. CREAZIONE DEL intestazione del documento HTML La routine starthtml () crea la parte superiore della pagina, insieme a un sacco di informazioni facoltative che controlla l'aspetto e il comportamento pagine. Questo metodo restituisce un colpo di testa HTML scatola e il tag di apertura ltbodygt. Tutti i parametri sono opzionali. Nella forma parametro denominato, i parametri riconosciuti sono - title, - Autore,-base, - xbase, - dtd, - lang e - target (vedi sotto per la spiegazione). Eventuali parametri aggiuntivi forniti dall'utente, come ad esempio l'attributo BGCOLOR non ufficiale, vengono aggiunti al tag ltbodygt. Ulteriori parametri devono essere precedute da un trattino. L'argomento - xbase consente di fornire un HREF per il tag ltbasegt diverso dalla posizione corrente, come in tutti i link relativi verrà interpretato come relativo a questo tag. L'argomento - target consente di fornire una cornice di destinazione di default per tutti i link e le forme della pagina compilare-out. This is a non-standard HTTP feature which only works with some browsers All relative links will be interpreted relative to this tag. You add arbitrary meta information to the header with the - meta argument. This argument expects a reference to a hash containing namevalue pairs of meta information. These will be turned into a series of header ltmetagt tags that look something like this: To create an HTTP-EQUIV type of ltmetagt tag, use - head . described below. The - style argument is used to incorporate cascading stylesheets into your code. See the section on CASCADING STYLESHEETS for more information. The - lang argument is used to incorporate a language attribute into the lthtmlgt tag. For example: The default if not specified is en-US for US English, unless the - dtd parameter specifies an HTML 2.0 or 3.2 DTD, in which case the lang attribute is left off. You can force the lang attribute to left off in other cases by passing an empty string (-langgt). The - encoding argument can be used to specify the character set for XHTML. It defaults to iso-8859-1 if not specified. The - dtd argument can be used to specify a public DTD identifier string. For example: Alternatively, it can take public and system DTD identifiers as an array: For the public DTD identifier to be considered, it must be valid. Otherwise it will be replaced by the default DTD. If the public DTD contains XHTML, CGI. pm will emit XML. The - declarexml argument, when used in conjunction with XHTML, will put a ltxmlgt declaration at the top of the HTML header. The sole purpose of this declaration is to declare the character set encoding. In the absence of - declarexml, the output HTML will contain a ltmetagt tag that specifies the encoding, allowing the HTML to pass most validators. The default for - declarexml is false. You can place other arbitrary HTML elements to the ltheadgt section with the - head tag. For example, to place a ltlinkgt element in the head section, use this: To incorporate multiple HTML elements into the ltheadgt section, just pass an array reference: And heres how to create an HTTP-EQUIV ltmetagt tag: JAVASCRIPTING: The - script . - noScript . - onLoad . - onMouseOver . - onMouseOut and - onUnload parameters are used to add JavaScript calls to your pages. - script should point to a block of text containing JavaScript function definitions. This block will be placed within a ltscriptgt block inside the HTML (not HTTP) header. The block is placed in the header in order to give your page a fighting chance of having all its JavaScript functions in place even if the user presses the stop button before the page has loaded completely. CGI. pm attempts to format the script in such a way that JavaScript-naive browsers will not choke on the code: unfortunately there are some browsers, such as Chimera for Unix, that get confused by it nevertheless. The - onLoad and - onUnload parameters point to fragments of JavaScript code to execute when the page is respectively opened and closed by the browser. Usually these parameters are calls to functions defined in the - script field: Use the - noScript parameter to pass some HTML text that will be displayed on browsers that do not have JavaScript (or browsers where JavaScript is turned off). The ltscriptgt tag, has several attributes including type, charset and src. src allows you to keep JavaScript code in an external file. To use these attributes pass a HASH reference in the - script parameter containing one or more of - type, - src, or - code: A final feature allows you to incorporate multiple ltscriptgt sections into the header. Just pass the list of script sections as an array reference. this allows you to specify different source files for different dialects of JavaScript. Example: The option - language is a synonym for - type, and is supported for backwards compatibility. The old-style positional parameters are as follows: The authors e-mail address (will create a ltlink revMADEgt tag if present A true flag if you want to include a ltbasegt tag in the header. This helps resolve relative addresses to absolute ones when the document is moved, but makes the document hierarchy non-portable. Use with care Other parameters you want to include in the ltbodygt tag may be appended to these. This is a good place to put HTML extensions, such as colors and wallpaper patterns. ENDING THE HTML DOCUMENT: This ends an HTML document by printing the ltbodygtlthtmlgt tags. CREATING A SELF-REFERENCING URL THAT PRESERVES STATE INFORMATION: selfurl() will return a URL, that, when selected, will reinvoke this script with all its state information intact. This is most useful when you want to jump around within the document using internal anchors but you dont want to disrupt the current contents of the form(s). Something like this will do the trick. If you want more control over whats returned, using the url() method instead. You can also retrieve the unprocessed query string with querystring(): The behavior of calling querystring is currently undefined when the HTTP method is something other than GET. OBTAINING THE SCRIPTS URL url() returns the scripts URL in a variety of formats. Called without any arguments, it returns the full form of the URL, including host name and port number You can modify this format with the following named arguments: If true, produce an absolute URL, e. g. Produce a relative URL. This is useful if you want to reinvoke your script with different parameters. For example: Produce the full URL, exactly as if called without any arguments. This overrides the - relative and - absolute arguments. Append the additional path information to the URL. This can be combined with - full . - absolute or - relative . - pathinfo is provided as a synonym. Append the query string to the URL. This can be combined with - full . - absolute or - relative . - querystring is provided as a synonym. Generate just the protocol and net location, as in foo:8000 If Apaches modrewrite is turned on, then the script name and path info probably wont match the request that the user sent. Set - rewritegt1 (default) to return URLs that match what the user sent (the original request URI). Set - rewritegt0 to return URLs that match the URL after modrewrites rules have run. MIXING POST AND URL PARAMETERS It is possible for a script to receive CGI parameters in the URL as well as in the fill-out form by creating a form that POSTs to a URL containing a query string (a mark followed by arguments). The param() method will always return the contents of the POSTed fill-out form, ignoring the URLs query string. To retrieve URL parameters, call the urlparam() method. Use it in the same way as param() . The main difference is that it allows you to read the parameters, but not set them. Under no circumstances will the contents of the URL query string interfere with similarly-named CGI parameters in POSTed forms. If you try to mix a URL query string with a form submitted with the GET method, the results will not be what you expect. CREATING STANDARD HTML ELEMENTS: CGI. pm defines general HTML shortcut methods for many HTML tags. HTML shortcuts are named after a single HTML element and return a fragment of HTML text. Example: This results in the following HTML code (extra newlines have been added for readability): If you find the syntax for calling the HTML shortcuts awkward, you can import them into your namespace and dispense with the object syntax completely (see the next section for more details): PROVIDING ARGUMENTS TO HTML SHORTCUTS The HTML methods will accept zero, one or multiple arguments. If you provide no arguments, you get a single tag: If you provide one or more string arguments, they are concatenated together with spaces and placed between opening and closing tags: If the first argument is a hash reference, then the keys and values of the hash become the HTML tags attributes: You may dispense with the dashes in front of the attribute names if you prefer: Sometimes an HTML tag attribute has no argument. For example, ordered lists can be marked as COMPACT. The syntax for this is an argument that that points to an undef string: Prior to CGI. pm version 2.41, providing an empty () string as an attribute argument was the same as providing undef. However, this has changed in order to accommodate those who want to create tags of the form ltimg altgt. The difference is shown in these two pieces of code: THE DISTRIBUTIVE PROPERTY OF HTML SHORTCUTS One of the cool features of the HTML shortcuts is that they are distributive. If you give them an argument consisting of a reference to a list, the tag will be distributed across each element of the list. For example, heres one way to make an ordered list: This example will result in HTML output that looks like this: This is extremely useful for creating tables. For example: HTML SHORTCUTS AND LIST INTERPOLATION Consider this bit of code: It will ordinarily return the string that you probably expect, namely: Note the space between the element Hi and the element mom. CGI. pm puts the extra space there using array interpolation, which is controlled by the magic variable. Sometimes this extra space is not what you want, for example, when you are trying to align a series of images. In this case, you can simply change the value of to an empty string. I suggest you put the code in a block as shown here. Otherwise the change to will affect all subsequent code until you explicitly reset it. NON-STANDARD HTML SHORTCUTS A few HTML tags dont follow the standard pattern for various reasons. comment() generates an HTML comment (lt-- comment --gt). Call it like Because of conflicts with built-in Perl functions, the following functions begin with initial caps: In addition, starthtml(), endhtml(), startform(), endform(), startmultipartform() and all the fill-out form tags are special. See their respective sections. AUTOESCAPING HTML By default, all HTML that is emitted by the form-generating functions is passed through a function called escapeHTML(): escapedstring escapeHTML(unescaped string) Escape HTML formatting characters in a string. Provided that you have specified a character set of ISO-8859-1 (the default), the standard HTML escaping rules will be used. The lt character becomes amplt, gt becomes ampgt, amp becomes ampamp, and the quote character becomes ampquot. In addition, the hexadecimal 0x8b and 0x9b characters, which some browsers incorrectly interpret as the left and right angle-bracket characters, are replaced by their numeric character entities (amp8249 and amp8250). If you manually change the charset, either by calling the charset() method explicitly or by passing a - charset argument to header(), then all characters will be replaced by their numeric entities, since CGI. pm has no lookup table for all the possible encodings. escapeHTML ( ) expects the supplied string to be a character string. This means you should Encode::decode data received from outside and Encode::encode your strings before sending them back outside. If your source code UTF-8 encoded and you want to upgrade string literals in your source to character strings, you can use use utf8. See perlunitut. perlunifaq and perlunicode for more information on how Perl handles the difference between bytes and characters. The automatic escaping does not apply to other shortcuts, such as h1(). You should call escapeHTML() yourself on untrusted data in order to protect your pages against nasty tricks that people may enter into guestbooks, etc. To change the character set, use charset(). To turn autoescaping off completely, use autoEscape(0): Get or set the current character set. Get or set the value of the autoescape flag. PRETTY-PRINTING HTML By default, all the HTML produced by these functions comes out as one long line without carriage returns or indentation. This is yuck, but it does reduce the size of the documents by 10-20. To get pretty-printed output, please use CGI::Pretty. a subclass contributed by Brian Paulsen. CREATING FILL-OUT FORMS: General note The various form-creating methods all return strings to the caller, containing the tag or tags that will create the requested form element. You are responsible for actually printing out these strings. Its set up this way so that you can place formatting tags around the form elements. Another note The default values that you specify for the forms are only used the first time the script is invoked (when there is no query string). On subsequent invocations of the script (when there is a query string), the former values are used even if they are blank. If you want to change the value of a field from its previous value, you have two choices: (1) call the param() method to set it. (2) use the - override (alias - force) parameter (a new feature in version 2.15). This forces the default value to be used, regardless of the previous value: Yet another note By default, the text and labels of form elements are escaped according to HTML rules. This means that you can safely use ltCLICK MEgt as the label for a button. However, it also interferes with your ability to incorporate special HTML character sequences, such as ampAacute, into your fields. If you wish to turn off automatic escaping, call the autoEscape() method with a false value immediately after creating the CGI object: Note that autoEscape() is exclusively used to effect the behavior of how some CGI. pm HTML generation functions handle escaping. Calling escapeHTML() explicitly will always escape the HTML. A Lurking Trap Some of the form-element generating methods return multiple tags. In a scalar context, the tags will be concatenated together with spaces, or whatever is the current value of the global. In a list context, the methods will return a list of elements, allowing you to modify them if you wish. Usually you will not notice this behavior, but beware of this: endform() produces several tags, and only the first of them will be printed because the format only expects one value. CREATING AN ISINDEX TAG Prints out an ltisindexgt tag. Non molto eccitante. The parameter - action specifies the URL of the script to process the query. The default is to process the query with the current script. STARTING AND ENDING A FORM startform() will return a ltformgt tag with the optional method, action and form encoding that you specify. The defaults are: endform() returns the closing ltformgt tag. Startform()s enctype argument tells the browser how to package the various fields of the form before sending the form to the server. Two values are possible: Note: These methods were previously named startform() and endform(). These methods are now DEPRECATED. Please use startform() and endform() instead. This is the older type of encoding. It is compatible with many CGI scripts and is suitable for short fields containing text data. For your convenience, CGI. pm stores the name of this encoding type in ampCGI::URLENCODED . This is the newer type of encoding. It is suitable for forms that contain very large fields or that are intended for transferring binary data. Most importantly, it enables the file upload feature. For your convenience, CGI. pm stores the name of this encoding type in ampCGI::MULTIPART Forms that use this type of encoding are not easily interpreted by CGI scripts unless they use CGI. pm or another library designed to handle them. If XHTML is activated (the default), then forms will be automatically created using this type of encoding. The startform() method uses the older form of encoding by default unless XHTML is requested. If you want to use the newer form of encoding by default, you can call startmultipartform() instead of startform() . The method endmultipartform() is an alias to endform() . JAVASCRIPTING: The - name and - onSubmit parameters are provided for use with JavaScript. The - name parameter gives the form a name so that it can be identified and manipulated by JavaScript functions. - onSubmit should point to a JavaScript function that will be executed just before the form is submitted to your server. You can use this opportunity to check the contents of the form for consistency and completeness. If you find something wrong, you can put up an alert box or maybe fix things up yourself. You can abort the submission by returning false from this function. Usually the bulk of JavaScript functions are defined in a ltscriptgt block in the HTML header and - onSubmit points to one of these function call. See starthtml() for details. FORM ELEMENTS After starting a form, you will typically create one or more textfields, popup menus, radio groups and other form elements. Each of these elements takes a standard set of named arguments. Some elements also have optional arguments. The standard arguments are as follows: The name of the field. After submission this name can be used to retrieve the fields value using the param() method. The initial value of the field which will be returned to the script after form submission. Some form elements, such as text fields, take a single scalar - value argument. Others, such as popup menus, take a reference to an array of values. The two arguments are synonyms. A numeric value that sets the order in which the form element receives focus when the user presses the tab key. Elements with lower values receive focus first. A string identifier that can be used to identify this element to JavaScript and DHTML. A boolean, which, if true, forces the element to take on the value specified by - value . overriding the sticky behavior described earlier for the - nosticky pragma. These are used to assign JavaScript event handlers. See the JavaScripting section for more details. Other common arguments are described in the next section. In addition to these, all attributes described in the HTML specifications are supported. CREATING A TEXT FIELD textfield() will return a text input field. The first parameter is the required name for the field (-name). The optional second parameter is the default starting value for the field contents (-value, formerly known as - default). The optional third parameter is the size of the field in characters (-size). The optional fourth parameter is the maximum number of characters the field will accept (-maxlength). As with all these methods, the field will be initialized with its previous contents from earlier invocations of the script. When the form is processed, the value of the text field can be retrieved with: If you want to reset it from its initial value after the script has been called once, you can do so like this: CREATING A BIG TEXT FIELD textarea() is just like textfield, but it allows you to specify rows and columns for a multiline text entry box. You can provide a starting value for the field, which can be long and contain multiple lines. CREATING A PASSWORD FIELD passwordfield() is identical to textfield(), except that its contents will be starred out on the web page. CREATING A FILE UPLOAD FIELD filefield() will return a file upload field. In order to take full advantage of this you must use the new multipart encoding scheme for the form. You can do this either by calling startform() with an encoding type of ampCGI::MULTIPART . or by calling the new method startmultipartform() instead of vanilla startform() . The first parameter is the required name for the field (-name). The optional second parameter is the starting value for the field contents to be used as the default file name (-default). For security reasons, browsers dont pay any attention to this field, and so the starting value will always be blank. Worse, the field loses its sticky behavior and forgets its previous contents. The starting value field is called for in the HTML specification, however, and possibly some browser will eventually provide support for it. The optional third parameter is the size of the field in characters (-size). The optional fourth parameter is the maximum number of characters the field will accept (-maxlength). JAVASCRIPTING: The - onChange . - onFocus . - onBlur . - onMouseOver . - onMouseOut and - onSelect parameters are recognized. See textfield() for details. PROCESSING A FILE UPLOAD FIELD When the form is processed, you can retrieve an IO::Handle compatible handle for a file upload field like this: In a list context, upload() will return an array of filehandles. This makes it possible to process forms that use the same name for multiple upload fields. If you want the entered file name for the file, you can just call param(): Different browsers will return slightly different things for the name. Some browsers return the filename only. Others return the full path to the file, using the path conventions of the users machine. Regardless, the name returned is always the name of the file on the users machine, and is unrelated to the name of the temporary file that CGI. pm creates during upload spooling (see below). When a file is uploaded the browser usually sends along some information along with it in the format of headers. The information usually includes the MIME content type. To retrieve this information, call uploadInfo(). It returns a reference to a hash containing all the document headers. If you are using a machine that recognizes text and binary data modes, be sure to understand when and how to use them (see the Camel book). Otherwise you may find that binary files are corrupted during file uploads. Accessing the temp files directly When processing an uploaded file, CGI. pm creates a temporary file on your hard disk and passes you a file handle to that file. After you are finished with the file handle, CGI. pm unlinks (deletes) the temporary file. If you need to you can access the temporary file directly. You can access the temp file for a file upload by passing the file name to the tmpFileName() method: The temporary file will be deleted automatically when your program exits unless you manually rename it. On some operating systems (such as Windows NT), you will need to close the temporary files filehandle before your program exits. Otherwise the attempt to delete the temporary file will fail. Handling interrupted file uploads There are occasionally problems involving parsing the uploaded file. This usually happens when the user presses Stop before the upload is finished. In this case, CGI. pm will return undef for the name of the uploaded file and set cgierror() to the string 400 Bad request (malformed multipart POST). This error message is designed so that you can incorporate it into a status code to be sent to the browser. Example: You are free to create a custom HTML page to complain about the error, if you wish. Progress bars for file uploads and avoiding temp files CGI. pm gives you low-level access to file upload management through a file upload hook. You can use this feature to completely turn off the temp file storage of file uploads, or potentially write your own file upload progress meter. This is much like the UPLOADHOOK facility available in Apache::Request. with the exception that the first argument to the callback is an Apache::Upload object, here its the remote filename. The data field is optional it lets you pass configuration information (e. g. a database handle) to your hook callback. The usetempfile field is a flag that lets you turn on and off CGI. pms use of a temporary disk-based file during file upload. If you set this to a FALSE value (default true) then q-gtparam(uploadedfile) will no longer work, and the only way to get at the uploaded data is via the hook you provide. If using the function-oriented interface, call the CGI::uploadhook() method before calling param() or any other CGI functions: This method is not exported by default. You will have to import it explicitly if you wish to use it without the CGI. prefix. Troubleshooting file uploads on Windows If you are using CGI. pm on a Windows platform and find that binary files get slightly larger when uploaded but that text files remain the same, then you have forgotten to activate binary mode on the output filehandle. Be sure to call binmode() on any handle that you create to write the uploaded file to disk. Older ways to process file uploads ( This section is here for completeness. if you are building a new application with CGI. pm, you can skip it. ) The original way to process file uploads with CGI. pm was to use param(). The value it returns has a dual nature as both a file name and a lightweight filehandle. This dual nature is problematic if you following the recommended practice of having use strict in your code. Perl will complain when you try to use a string as a filehandle. More seriously, it is possible for the remote user to type garbage into the upload field, in which case what you get from param() is not a filehandle at all, but a string. To solve this problem the upload() method was added, which always returns a lightweight filehandle. This generally works well, but will have trouble interoperating with some other modules because the file handle is not derived from IO::Handle. So that brings us to current recommendation given above, which is to call the handle() method on the file handle returned by upload(). That upgrades the handle to an IO::Handle. Its a big win for compatibility for a small penalty of loading IO::Handle the first time you call it. CREATING A POPUP MENU popupmenu() creates a menu. The required first argument is the menus name (-name). The required second argument (-values) is an array reference containing the list of menu items in the menu. You can pass the method an anonymous array, as shown in the example, or a reference to a named array, such as foo. The optional third parameter (-default) is the name of the default menu choice. If not specified, the first item will be the default. The values of the previous choice will be maintained across queries. Pass an array reference to select multiple defaults. The optional fourth parameter (-labels) is provided for people who want to use different values for the user-visible label inside the popup menu and the value returned to your script. Its a pointer to an hash relating menu values to user-visible labels. If you leave this parameter blank, the menu values will be displayed by default. (You can also leave a label undefined if you want to). The optional fifth parameter (-attributes) is provided to assign any of the common HTML attributes to an individual menu item. Its a pointer to a hash relating menu values to another hash with the attributes name as the key and the attributes value as the value. When the form is processed, the selected value of the popup menu can be retrieved using: CREATING AN OPTION GROUP Named parameter style optgroup() creates an option group within a popup menu. The required first argument ( - name ) is the label attribute of the optgroup and is not inserted in the parameter list of the query. The required second argument ( - values ) is an array reference containing the list of menu items in the menu. You can pass the method an anonymous array, as shown in the example, or a reference to a named array, such as foo. If you pass a HASH reference, the keys will be used for the menu values, and the values will be used for the menu labels (see - labels below). The optional third parameter ( - labels ) allows you to pass a reference to a hash containing user-visible labels for one or more of the menu items. You can use this when you want the user to see one menu string, but have the browser return your program a different one. If you dont specify this, the value string will be used instead (eenie, meenie and minie in this example). This is equivalent to using a hash reference for the - values parameter. An optional fourth parameter ( - labeled ) can be set to a true value and indicates that the values should be used as the label attribute for each option element within the optgroup. An optional fifth parameter (-novals) can be set to a true value and indicates to suppress the val attribute in each option element within the optgroup. An optional sixth parameter (-attributes) is provided to assign any of the common HTML attributes to an individual menu item. Its a pointer to a hash relating menu values to another hash with the attributes name as the key and the attributes value as the value. CREATING A SCROLLING LIST scrollinglist() creates a scrolling list. The first and second arguments are the list name (-name) and values (-values). As in the popup menu, the second argument should be an array reference. The optional third argument (-default) can be either a reference to a list containing the values to be selected by default, or can be a single value to select. If this argument is missing or undefined, then nothing is selected when the list first appears. In the named parameter version, you can use the synonym - defaults for this parameter. The optional fourth argument is the size of the list (-size). The optional fifth argument can be set to true to allow multiple simultaneous selections (-multiple). Otherwise only one selection will be allowed at a time. The optional sixth argument is a pointer to a hash containing long user-visible labels for the list items (-labels). If not provided, the values will be displayed. The optional sixth parameter (-attributes) is provided to assign any of the common HTML attributes to an individual menu item. Its a pointer to a hash relating menu values to another hash with the attributes name as the key and the attributes value as the value. When this form is processed, all selected list items will be returned as a list under the parameter name listname. The values of the selected items can be retrieved with: CREATING A GROUP OF RELATED CHECKBOXES checkboxgroup() creates a list of checkboxes that are related by the same name. The first and second arguments are the checkbox name and values, respectively (-name and - values). As in the popup menu, the second argument should be an array reference. These values are used for the user-readable labels printed next to the checkboxes as well as for the values passed to your script in the query string. The optional third argument (-default) can be either a reference to a list containing the values to be checked by default, or can be a single value to checked. If this argument is missing or undefined, then nothing is selected when the list first appears. The optional fourth argument (-linebreak) can be set to true to place line breaks between the checkboxes so that they appear as a vertical list. Otherwise, they will be strung together on a horizontal line. The optional - labels argument is a pointer to a hash relating the checkbox values to the user-visible labels that will be printed next to them. If not provided, the values will be used as the default. The optional parameters - rows . and - columns cause checkboxgroup() to return an HTML3 compatible table containing the checkbox group formatted with the specified number of rows and columns. You can provide just the - columns parameter if you wish checkboxgroup will calculate the correct number of rows for you. The option - disabled takes an array of checkbox values and disables them by greying them out (this may not be supported by all browsers). The optional - attributes argument is provided to assign any of the common HTML attributes to an individual menu item. Its a pointer to a hash relating menu values to another hash with the attributes name as the key and the attributes value as the value. The optional - tabindex argument can be used to control the order in which radio buttons receive focus when the user presses the tab button. If passed a scalar numeric value, the first element in the group will receive this tab index and subsequent elements will be incremented by one. If given a reference to an array of radio button values, then the indexes will be jiggered so that the order specified in the array will correspond to the tab order. You can also pass a reference to a hash in which the hash keys are the radio button values and the values are the tab indexes of each button. Examples: The optional - labelattributes argument will contain attributes attached to the ltlabelgt element that surrounds each button. When the form is processed, all checked boxes will be returned as a list under the parameter name groupname. The values of the on checkboxes can be retrieved with: The value returned by checkboxgroup() is actually an array of button elements. You can capture them and use them within tables, lists, or in other creative ways: CREATING A STANDALONE CHECKBOX checkbox() is used to create an isolated checkbox that isnt logically related to any others. The first parameter is the required name for the checkbox (-name). It will also be used for the user-readable label printed next to the checkbox. The optional second parameter (-checked) specifies that the checkbox is turned on by default. Synonyms are - selected and - on. The optional third parameter (-value) specifies the value of the checkbox when it is checked. If not provided, the word on is assumed. The optional fourth parameter (-label) is the user-readable label to be attached to the checkbox. If not provided, the checkbox name is used. The value of the checkbox can be retrieved using: CREATING A RADIO BUTTON GROUP radiogroup() creates a set of logically-related radio buttons (turning one member of the group on turns the others off) The first argument is the name of the group and is required (-name). The second argument (-values) is the list of values for the radio buttons. The values and the labels that appear on the page are identical. Pass an array reference in the second argument, either using an anonymous array, as shown, or by referencing a named array as in foo. The optional third parameter (-default) is the name of the default button to turn on. If not specified, the first item will be the default. You can provide a nonexistent button name, such as - to start up with no buttons selected. The optional fourth parameter (-linebreak) can be set to true to put line breaks between the buttons, creating a vertical list. The optional fifth parameter (-labels) is a pointer to an associative array relating the radio button values to user-visible labels to be used in the display. If not provided, the values themselves are displayed. All modern browsers can take advantage of the optional parameters - rows . and - columns . These parameters cause radiogroup() to return an HTML3 compatible table containing the radio group formatted with the specified number of rows and columns. You can provide just the - columns parameter if you wish radiogroup will calculate the correct number of rows for you. To include row and column headings in the returned table, you can use the - rowheaders and - colheaders parameters. Both of these accept a pointer to an array of headings to use. The headings are just decorative. They dont reorganize the interpretation of the radio buttons -- theyre still a single named unit. The optional - tabindex argument can be used to control the order in which radio buttons receive focus when the user presses the tab button. If passed a scalar numeric value, the first element in the group will receive this tab index and subsequent elements will be incremented by one. If given a reference to an array of radio button values, then the indexes will be jiggered so that the order specified in the array will correspond to the tab order. You can also pass a reference to a hash in which the hash keys are the radio button values and the values are the tab indexes of each button. Examples: The optional - attributes argument is provided to assign any of the common HTML attributes to an individual menu item. Its a pointer to a hash relating menu values to another hash with the attributes name as the key and the attributes value as the value. The optional - labelattributes argument will contain attributes attached to the ltlabelgt element that surrounds each button. When the form is processed, the selected radio button can be retrieved using: The value returned by radiogroup() is actually an array of button elements. You can capture them and use them within tables, lists, or in other creative ways: CREATING A SUBMIT BUTTON submit() will create the query submission button. Every form should have one of these. The first argument (-name) is optional. You can give the button a name if you have several submission buttons in your form and you want to distinguish between them. The second argument (-value) is also optional. This gives the button a value that will be passed to your script in the query string. The name will also be used as the user-visible label. You can use - label as an alias for - value. I always get confused about which of - name and - value changes the user-visible label on the button. You can figure out which button was pressed by using different values for each one: CREATING A RESET BUTTON reset() creates the reset button. Note that it restores the form to its value from the last time the script was called, NOT necessarily to the defaults. Note that this conflicts with the Perl reset() built-in. Use CORE::reset() to get the original reset function. CREATING A DEFAULT BUTTON defaults() creates a button that, when invoked, will cause the form to be completely reset to its defaults, wiping out all the changes the user ever made. CREATING A HIDDEN FIELD hidden() produces a text field that cant be seen by the user. It is useful for passing state variable information from one invocation of the script to the next. The first argument is required and specifies the name of this field (-name). The second argument is also required and specifies its value (-default). In the named parameter style of calling, you can provide a single value here or a reference to a whole list Fetch the value of a hidden field this way: Note, that just like all the other form elements, the value of a hidden field is sticky. If you want to replace a hidden field with some other values after the script has been called once youll have to do it manually: CREATING A CLICKABLE IMAGE BUTTON imagebutton() produces a clickable image. When its clicked on the position of the click is returned to your script as buttonname. x and buttonname. y, where buttonname is the name youve assigned to it. The first argument (-name) is required and specifies the name of this field. The second argument (-src) is also required and specifies the URL The third option (-align, optional) is an alignment type, and may be TOP, BOTTOM or MIDDLE Fetch the value of the button this way: x param(buttonname. x) y param(buttonname. y) CREATING A JAVASCRIPT ACTION BUTTON button() produces an ltinputgt tag with type quotbuttonquot. When its pressed the fragment of JavaScript code pointed to by the - onClick parameter will be executed. HTTP COOKIES Browsers support a so-called cookie designed to help maintain state within a browser session. CGI. pm has several methods that support cookies. A cookie is a namevalue pair much like the named parameters in a CGI query string. CGI scripts create one or more cookies and send them to the browser in the HTTP header. The browser maintains a list of cookies that belong to a particular Web server, and returns them to the CGI script during subsequent interactions. In addition to the required namevalue pair, each cookie has several optional attributes: 1. an expiration time This is a timedate string (in a special GMT format) that indicates when a cookie expires. The cookie will be saved and returned to your script until this expiration date is reached if the user exits the browser and restarts it. If an expiration date isnt specified, the cookie will remain active until the user quits the browser. This is a partial or complete domain name for which the cookie is valid. The browser will return the cookie to any host that matches the partial domain name. For example, if you specify a domain name of. capricorn, then the browser will return the cookie to Web servers running on any of the machines capricorn, www2.capricorn, feckless. capricorn, etc. Domain names must contain at least two periods to prevent attempts to match on top level domains like. edu. If no domain is specified, then the browser will only return the cookie to servers on the host the cookie originated from. If you provide a cookie path attribute, the browser will check it against your scripts URL before returning the cookie. For example, if you specify the path cgi-bin, then the cookie will be returned to each of the scripts cgi-bintally. pl, cgi-binorder. pl, and cgi-bincustomerservicecomplain. pl, but not to the script cgi-privatesiteadmin. pl. By default, path is set to , which causes the cookie to be sent to any CGI script on your site. If the secure attribute is set, the cookie will only be sent to your script if the CGI request is occurring on a secure channel, such as SSL. The interface to HTTP cookies is the cookie() method: cookie() creates a new cookie. Its parameters include: The name of the cookie (required). This can be any string at all. Although browsers limit their cookie names to non-whitespace alphanumeric characters, CGI. pm removes this restriction by escaping and unescaping cookies behind the scenes. The value of the cookie. This can be any scalar value, array reference, or even hash reference. For example, you can store an entire hash into a cookie this way: The optional partial path for which this cookie will be valid, as described above. The optional partial domain for which this cookie will be valid, as described above. The optional expiration date for this cookie. The format is as described in the section on the header() method: If set to true, this cookie will only be used within a secure SSL session. The cookie created by cookie() must be incorporated into the HTTP header within the string returned by the header() method: To create multiple cookies, give header() an array reference: To retrieve a cookie, request it by name by calling cookie() method without the - value parameter. This example uses the object-oriented form: Cookies created with a single scalar value, such as the riddlename cookie, will be returned in that form. Cookies with array and hash values can also be retrieved. The cookie and CGI namespaces are separate. If you have a parameter named answers and a cookie named answers, the values retrieved by param() and cookie() are independent of each other. However, its simple to turn a CGI parameter into a cookie, and vice-versa: If you call cookie() without any parameters, it will return a list of the names of all cookies passed to your script: See the cookie. cgi example script for some ideas on how to use cookies effectively. WORKING WITH FRAMES Its possible for CGI. pm scripts to write into several browser panels and windows using the HTML 4 frame mechanism. There are three techniques for defining new frames programmatically: 1. Create a ltFramesetgt document After writing out the HTTP header, instead of creating a standard HTML document using the starthtml() call, create a ltframesetgt document that defines the frames on the page. Specify your script(s) (with appropriate parameters) as the SRC for each of the frames. There is no specific support for creating ltframesetgt sections in CGI. pm, but the HTML is very simple to write. 2. Specify the destination for the document in the HTTP header You may provide a - target parameter to the header() method: This will tell the browser to load the output of your script into the frame named ResultsWindow. If a frame of that name doesnt already exist, the browser will pop up a new window and load your scripts document into that. There are a number of magic names that you can use for targets. See the HTML ltframegt documentation for details. 3. Specify the destination for the document in the ltformgt tag You can specify the frame to load in the FORM tag itself. With CGI. pm it looks like this: When your script is reinvoked by the form, its output will be loaded into the frame named ResultsWindow. If one doesnt already exist a new window will be created. The script frameset. cgi in the examples directory shows one way to create pages in which the fill-out form and the response live in side-by-side frames. SUPPORT FOR JAVASCRIPT The usual way to use JavaScript is to define a set of functions in a ltSCRIPTgt block inside the HTML header and then to register event handlers in the various elements of the page. Events include such things as the mouse passing over a form element, a button being clicked, the contents of a text field changing, or a form being submitted. When an event occurs that involves an element that has registered an event handler, its associated JavaScript code gets called. The elements that can register event handlers include the ltBODYgt of an HTML document, hypertext links, all the various elements of a fill-out form, and the form itself. There are a large number of events, and each applies only to the elements for which it is relevant. Here is a partial list: The browser is loading the current document. Valid in: The browser is closing the current page or frame. Valid for: The user has pressed the submit button of a form. This event happens just before the form is submitted, and your function can return a value of false in order to abort the submission. Valid for: The mouse has clicked on an item in a fill-out form. Valid for: The user has changed the contents of a field. Valid for: The user has selected a field to work with. Valid for: The user has deselected a field (gone to work somewhere else). Valid for: The user has changed the part of a text field that is selected. Valid for: The mouse has moved over an element. The mouse has moved off an element. In order to register a JavaScript event handler with an HTML element, just use the event name as a parameter when you call the corresponding CGI method. For example, to have your validateAge() JavaScript code executed every time the textfield named age changes, generate the field like this: This example assumes that youve already declared the validateAge() function by incorporating it into a ltSCRIPTgt block. The CGI. pm starthtml() method provides a convenient way to create this section. Similarly, you can create a form that checks itself over for consistency and alerts the user if some essential value is missing by creating it this way: print startform(-onSubmitgtvalidateMe(this)) See the javascript. cgi script for a demonstration of how this all works. LIMITED SUPPORT FOR CASCADING STYLE SHEETS CGI. pm has limited support for HTML3s cascading style sheets (css). To incorporate a stylesheet into your document, pass the starthtml() method a - style parameter. The value of this parameter may be a scalar, in which case it is treated as the source URL for the stylesheet, or it may be a hash reference. In the latter case you should provide the hash with one or more of - src or - code . - src points to a URL where an externally-defined stylesheet can be found. - code points to a scalar value to be incorporated into a ltstylegt section. Style definitions in - code override similarly-named ones in - src . hence the name cascading. You may also specify the type of the stylesheet by adding the optional - type parameter to the hash pointed to by - style . If not specified, the style defaults to textcss. To refer to a style within the body of your document, add the - class parameter to any HTML element: Or define styles on the fly with the - style parameter: You may also use the new span() element to apply a style to a section of text: Note that you must import the :html3 definitions to have the span() method available. Heres a quick and dirty example of using CSSs. See the CSS specification at w3.orgStyleCSS for more information. Pass an array reference to - code or - src in order to incorporate multiple stylesheets into your document. Should you wish to incorporate a verbatim stylesheet that includes arbitrary formatting in the header, you may pass a - verbatim tag to the - style hash, as follows: This will generate an HTML header that contains this: Any additional arguments passed in the - style value will be incorporated into the ltlinkgt tag. For example: To make more complicated ltlinkgt tags, use the Link() function and pass it to starthtml() in the - head argument, as in: To create primary and alternate stylesheet, use the - alternate option: If you are running the script from the command line or in the perl debugger, you can pass the script a list of keywords or parametervalue pairs on the command line or from standard input (you dont have to worry about tricking your script into reading from environment variables). You can pass keywords like this: To turn off this feature, use the - nodebug pragma. To test the POST method, you may enable full debugging with the - debug pragma. This will allow you to feed newline-delimited namevalue pairs to the script on standard input. When debugging, you can use quotes and backslashes to escape characters in the familiar shell manner, letting you place spaces and other funny characters in your parametervalue pairs: Finally, you can set the path info for the script by prefixing the first namevalue parameter with the path followed by a question mark (): DUMPING OUT ALL THE NAMEVALUE PAIRS The Dump() method produces a string consisting of all the querys namevalue pairs formatted nicely as a nested list. This is useful for debugging purposes: Produces something that looks like: As a shortcut, you can interpolate the entire CGI object into a string and it will be replaced with the a nice HTML dump shown above: FETCHING ENVIRONMENT VARIABLES Some of the more useful environment variables can be fetched through this interface. The methods are as follows: Return a list of MIME types that the remote browser accepts. If you give this method a single argument corresponding to a MIME type, as in Accept(texthtml), it will return a floating point value corresponding to the browsers preference for this type from 0.0 (dont want) to 1.0. Glob types (e. g. text) in the browsers accept list are handled correctly. Note that the capitalization changed between version 2.43 and 2.44 in order to avoid conflict with Perls accept() function. Returns the HTTPCOOKIE variable. Cookies have a special format, and this method call just returns the raw form (cookie dough). See cookie() for ways of setting and retrieving cooked cookies. Called with no parameters, rawcookie() returns the packed cookie structure. You can separate it into individual cookies by splitting on the character sequence . Called with the name of a cookie, retrieves the unescaped form of the cookie. You can use the regular cookie() method to get the names, or use the rawfetch() method from the CGI::Cookie module. Returns the HTTPUSERAGENT variable. If you give this method a single argument, it will attempt to pattern match on it, allowing you to do something like useragent(Mozilla) Returns additional path information from the script URL. E. G. fetching cgi-binyourscriptadditionalstuff will result in pathinfo() returning additionalstuff. NOTE: The Microsoft Internet Information Server is broken with respect to additional path information. If you use the Perl DLL library, the IIS server will attempt to execute the additional path information as a Perl script. If you use the ordinary file associations mapping, the path information will be present in the environment, but incorrect. The best thing to do is to avoid using additional path information in CGI scripts destined for use with IIS. As per pathinfo() but returns the additional path information translated into a physical path, e. g. usrlocaletchttpdhtdocsadditionalstuff. The Microsoft IIS is broken with respect to the translated path as well. Returns either the remote host name or IP address. if the former is unavailable. Returns the remote host IP address, or 127.0.0.1 if the address is unavailable. scriptname() Return the script name as a partial URL, for self-referring scripts. referer() Return the URL of the page the browser was viewing prior to fetching your script. Not available for all browsers. Return the authorizationverification method in use for this script, if any. Returns the name of the server, usually the machines host name. When using virtual hosts, returns the name of the host that the browser attempted to contact Return the port that the server is listening on. Like serverport() except that it takes virtual hosts into account. Use this when running with virtual hosts. Returns the server software and version number. Return the authorizationverification name used for user verification, if this script is protected. Attempt to obtain the remote users name, using a variety of different techniques. This only works with older browsers such as Mosaic. Newer browsers do not report the user name for privacy reasons Returns the method used to access your script, usually one of POST, GET or HEAD. Returns the contenttype of data submitted in a POST, generally multipartform-data or applicationx-www-form-urlencoded Called with no arguments returns the list of HTTP environment variables, including such things as HTTPUSERAGENT, HTTPACCEPTLANGUAGE, and HTTPACCEPTCHARSET, corresponding to the like-named HTTP header fields in the request. Called with the name of an HTTP header field, returns its value. Capitalization and the use of hyphens versus underscores are not significant. For example, all three of these examples are equivalent: The same as http() . but operates on the HTTPS environment variables present when the SSL protocol is in effect. Can be used to determine whether SSL is turned on. USING NPH SCRIPTS NPH, or no-parsed-header, scripts bypass the server completely by sending the complete HTTP header directly to the browser. This has slight performance benefits, but is of most use for taking advantage of HTTP extensions that are not directly supported by your server, such as server push and PICS headers. Servers use a variety of conventions for designating CGI scripts as NPH. Many Unix servers look at the beginning of the scripts name for the prefix nph-. The Macintosh WebSTAR server and Microsofts Internet Information Server, in contrast, try to decide whether a program is an NPH script by examining the first line of script output. CGI. pm supports NPH scripts with a special NPH mode. When in this mode, CGI. pm will output the necessary extra header information when the header() and redirect() methods are called. The Microsoft Internet Information Server requires NPH mode. As of version 2.30, CGI. pm will automatically detect when the script is running under IIS and put itself into this mode. You do not need to do this manually, although it wont hurt anything if you do. However, note that if you have applied Service Pack 6, much of the functionality of NPH scripts, including the ability to redirect while setting a cookie, do not work at all on IIS without a special patch from Microsoft. See web. archive. orgweb20010812012030support. microsoftsupportkbarticlesQ280341.ASP Non-Parsed Headers Stripped From CGI Applications That Have nph - Prefix in Name. Simply add the - nph pragma to the list of symbols to be imported into your script: Call nph() with a non-zero parameter at any point after using CGI. pm in your program. in the header() and redirect() statements: Server Push CGI. pm provides four simple functions for producing multipart documents of the type needed to implement server push. These functions were graciously provided by Ed Jordan ltedfidalgogt. To import these into your namespace, you must import the :push set. You are also advised to put the script into NPH mode and to set to 1 to avoid buffering problems. Here is a simple script that demonstrates server push: This script initializes server push by calling multipartinit() . It then enters a loop in which it begins a new multipart section by calling multipartstart() . prints the current local time, and ends a multipart section with multipartend() . It then sleeps a second, and begins again. On the final iteration, it ends the multipart section with multipartfinal() rather than with multipartend() . Initialize the multipart system. The - boundary argument specifies what MIME boundary string to use to separate parts of the document. If not provided, CGI. pm chooses a reasonable boundary for you. Start a new part of the multipart document using the specified MIME type. If not specified, texthtml is assumed. End a part. You must remember to call multipartend() once for each multipartstart(), except at the end of the last part of the multipart document when multipartfinal() should be called instead of multipartend(). End all parts. You should call multipartfinal() rather than multipartend() at the end of the last part of the multipart document. Users interested in server push applications should also have a look at the CGI::Push module. Avoiding Denial of Service Attacks A potential problem with CGI. pm is that, by default, it attempts to process form POSTings no matter how large they are. A wily hacker could attack your site by sending a CGI script a huge POST of many megabytes. CGI. pm will attempt to read the entire POST into a variable, growing hugely in size until it runs out of memory. While the script attempts to allocate the memory the system may slow down dramatically. This is a form of denial of service attack. Another possible attack is for the remote user to force CGI. pm to accept a huge file upload. CGI. pm will accept the upload and store it in a temporary directory even if your script doesnt expect to receive an uploaded file. CGI. pm will delete the file automatically when it terminates, but in the meantime the remote user may have filled up the servers disk space, causing problems for other programs. The best way to avoid denial of service attacks is to limit the amount of memory, CPU time and disk space that CGI scripts can use. Some Web servers come with built-in facilities to accomplish this. In other cases, you can use the shell limit or ulimit commands to put ceilings on CGI resource usage. CGI. pm also has some simple built-in protections against denial of service attacks, but you must activate them before you can use them. These take the form of two global variables in the CGI name space: If set to a non-negative integer, this variable puts a ceiling on the size of POSTings, in bytes. If CGI. pm detects a POST that is greater than the ceiling, it will immediately exit with an error message. This value will affect both ordinary POSTs and multipart POSTs, meaning that it limits the maximum size of file uploads as well. You should set this to a reasonably high value, such as 1 megabyte. If set to a non-zero value, this will disable file uploads completely. Other fill-out form values will work as usual. You can use these variables in either of two ways. Set the variable at the top of the script, right after the use statement: Open up CGI. pm, find the definitions for POSTMAX and DISABLEUPLOADS, and set them to the desired values. Youll find them towards the top of the file in a subroutine named initializeglobals(). An attempt to send a POST larger than POSTMAX bytes will cause param() to return an empty CGI parameter list. You can test for this event by checking cgierror() . either after you create the CGI object or, if you are using the function-oriented interface, call ltparam()gt for the first time. If the POST was intercepted, then cgierror() will return the message 413 POST too large. This error message is actually defined by the HTTP protocol, and is designed to be returned to the browser as the CGI scripts status code. For example: However it isnt clear that any browser currently knows what to do with this status code. It might be better just to create an HTML page that warns the user of the problem. COMPATIBILITY WITH CGI-LIB. PL To make it easier to port existing programs that use cgi-lib. pl the compatibility routine ReadParse is provided. Porting is simple: CGI. pms ReadParse() routine creates a tied variable named in, which can be accessed to obtain the query variables. Like ReadParse, you can also provide your own variable. Infrequently used features of ReadParse, such as the creation of in and in variables, are not supported. Once you use ReadParse, you can retrieve the query object itself this way: This allows you to start using the more interesting features of CGI. pm without rewriting your old scripts from scratch. An even simpler way to mix cgi-lib calls with CGI. pm calls is to import both the. cgi - lib and. standard method: Cgi-lib functions that are available in CGI. pm In compatibility mode, the following cgi-lib. pl functions are available for your use: Cgi-lib functions that are not available in CGI. pm AUTHOR INFORMATION The CGI. pm distribution is copyright 1995-2007, Lincoln D. Stein. It is distributed under GPL and the Artistic License 2.0. It is currently maintained by Mark Stosberg with help from many contributors. Address bug reports and comments to: rt. cpan. orgPublicDistDisplay. htmlQueueCGI. pm When sending bug reports, please provide the version of CGI. pm, the version of Perl, the name and version of your Web server, and the name and version of the operating system you are using. If the problem is even remotely browser dependent, please provide information about the affected browsers as well. Thanks very much to: Matt Heffron (heffronfalstaff. css. beckman) James Taylor (james. taylorsrs. gov) Scott Anguish ltsanguishdigifixgt Mike Jewell (mlj3uvirginia. edu) Timothy Shimmin (teskbs. citri. edu. au) Joergen Haegg (jhaxis. se) Laurent Delfosse (delfossedelfosse) Richard Resnick (applepi1aol) Craig Bishop (csbbarwonwater. vic. gov. au) Tony Curtis (tcvcpc. univie. ac. at) Tim Bunce (Tim. Bunceig. co. uk) Tom Christiansen (tchristconvex) Andreas Koenig (kfranz. ww. TU-Berlin. DE) Tim MacKenzie (Tim. MacKenziefulcrum. au) Kevin B. Hendricks (kbhenddogwood. tyler. wm. edu) Stephen Dahmen (joyfireinxpress) Ed Jordan (edfidalgo) David Alan Pisoni (davidcnation) Doug MacEachern (dougmopengroup. org) Robin Houston (robinoneworld. org) . and many many more. for suggestions and bug fixes. A COMPLETE EXAMPLE OF A SIMPLE FORM-BASED SCRIPT Please report them. CGI::Carp - provides a Carp implementation tailored to the CGI environment. CGI::Fast - supports running CGI applications under FastCGI CGI::Pretty - pretty prints HTML generated by CGI. pm (with a performance penalty)

No comments:

Post a Comment