Monday 27 November 2017

Cgi Binære Alternativer


Ansvarsfraskrivelse: Binær opsjoner og forex trading innebærer risiko. Forretningsmodell og inntjening: Resultatene er betinget av å velge riktig retning av en eiendomspris, fra den angitte utsjekkingsprisen, etter valgt utløpsperiode. Når en handel er påbegynt, mottar forhandlere en bekreftelsesskjerm som viser aktiva, strykpris, valgt retning (CALL eller PUT), og investeringsbeløpet. Når du blir bedt om av dette skjermbildet, starter handler om 3 sekunder med mindre Trader trykker på Avbryt-knappen. TRBinaryOptions tilbyr det raskeste alternativet utløper tilgjengelig for offentligheten, og transaksjoner kan være så fort som 15 minutter i vanlige binære alternativer, og så fort som 60 sekunder i 60 sekunders plattform. Selv om risikoen ved handel med binære alternativer er fastsatt for hver enkelt handel, er handelen levende og det er mulig å miste en innledende investering, spesielt hvis en handelsmann velger å plassere hele sin investering til en enkelt handel. Det anbefales sterkt at handelsmenn velger en ordentlig pengehåndteringsstrategi som begrenser de samlede påfølgende handler eller total utestående investeringer. Det anbefales å bruke Mozilla Firefox eller Google Chrome nettlesere når de handler på TRBinaryOptions. Takk for din interesse7 Binære alternativer 7 Binære alternativer Hvordan tjene penger online med binærvalg Trading Siden 2008 har investering og tjene penger på nettet med binære alternativer blitt stadig mer attraktivt for investorer og enkeltpersoner som investerer i aksjer. aksjer, valutaer og varer. Det er bare to alternativer i binær handel, derfor bruken av begrepet binær. Det er nesten som å sette en innsats, fordi du satser på at en eiendel vil øke eller redusere i verdi over en bestemt tidsperiode. Binær handel gir opsjoner for markedet å selvregulere og gir mulighet til å tømme i overvurderte aksjer ved å spekulere på at et selskap vil se en nedgang i verdien. I binær opsjonshandel satser du på at prisen på en bestemt eiendel enten vil øke eller redusere i løpet av en bestemt periode. Du har den luksusen å kjenne din risiko og komme tilbake foran, før handelen noen gang finner sted. Binær handel er en utmerket måte å komme inn på markedet uten et stort utlån av kapital eller kapitalreserven som kreves. Dra nytte av informasjonen som tilbys på 7binaryoptions for å få bedre forståelse av binære alternativer og forex trading for å tjene penger på nettet. Komme i gang med tre enkle trinn: Velg en megler fra listen nedenfor Reuters 8211 Financial News CHICAGO (Reuters) - Den amerikanske Federal Reserve039s langvarige 039liftoff039 av rentene kan endelig få luftbårne i år som politimenn fra stolen Janet Yellen på fredag ​​til regionalt ledere over USA signalerte at æra med enkle penger trekker til slutt. (Reuters) - Johnson Amp Johnson sa på fredag ​​at en domstol i jury i Missouri hadde returnert en dom i sin favør i den siste rettssaken for å oppstå ut av tusenvis av søksmål om at selskapets talksbaserte produkter kan øke risikoen for eggstokkreft. (Reuters) - Keystone XL-oljeledningen trenger ikke å være laget av amerikansk stål, til tross for en utøvende rekkefølge av president Donald Trump dager etter at han tok kontor som krever innenlandsk stål i nye rørledninger, sa det hvite hus fredag. LONDON (Reuters) - Deutsche Boerse, konsernsjef Carsten Kengeter, sa at det fortsetter forberedelsene til en fusjon med London Stock Exchange. til tross for LSE039s nektelse å selge sin italienske MTS trading plattform. (Reuters) - SampP 500 og Nasdaq avsluttet sin sjette rette uke med gevinster med en flatt økt etter at Janet Yellen signaliserte at Federal Reserve vil øke renten denne måneden dersom sysselsetting og andre økonomiske data holder opp. (Reuters) - Ride hailing selskap Uber Technologies Inc UBER. UL har i årevis brukt et hemmelig verktøy for å bedra de myndighetene i markeder hvor tjenesten opplevde motstand ved rettshåndhevelse eller ble utestengt, rapporterte New York Times, med henvisning til kilder. (Reuters) - US high end-varehuskjeden Neiman Marcus har ansatt investeringsbanken Lazard Ltd for å undersøke måter å styrke balansen når den søker nødhjelp fra 4,9 milliarder kroner i gjeld. Folk som er kjent med saken, sa fredag. PARISLONDON (Reuters) - France039s PSA-gruppe slo en avtale med General Motors om å kjøpe den amerikanske carmaker039s tap-making Opel divisjonen, to kilder med kunnskap om saken til Reuters. (Reuters) - Comcast Corp039s NBCUniversal har investert 500 millioner i Snapchat eier Snap Inc. ifølge et notat på fredag, sitt siste trekk for å drive digital vekst ettersom flere seere går online for deres favorittinnhold. (Reuters) - Caterpillar Inc039s aksjer ble oppnådd fredag ​​dagen etter at amerikanske politimyndigheter slo på tre av selskapets Illinois-anlegg, da Trump-administrasjonen lovet strengere granskning av multinasjonale selskaper039 import og eksport praksis. Anbefalt robot om oss 038 Ansvarsfraskrivelse Ansvarsfraskrivelse: 7 Binary Options vil ikke holdes ansvarlig for tap eller skade som skyldes tillit til informasjonen på dette nettstedet. Dataene på denne nettsiden er ikke nødvendigvis sanntidsklar eller nøyaktige, og analyser er forfatterens meninger. 7binaryoptions er bare et nettsted som tilbyr informasjon - ikke en regulert megler eller investeringsrådgiver, og ingen av informasjonene er ment å garantere fremtidige resultater. Binær opsjonshandel på margin innebærer høy risiko, og er ikke egnet for alle investorer. Som et løfteprodukt kan tap overstige innledende innskudd og kapital er i fare. Før du bestemmer deg for å handle binære alternativer eller et annet finansielt instrument, bør du nøye vurdere investeringsmålene dine, nivået på erfaring og risikoen for appetitten. I henhold til FTC-retningslinjene har 7BinaryOptions økonomiske forhold til noen av produktene og tjenestene nevnt på denne nettsiden, og 7BinaryOptions kan kompenseres dersom forbrukerne velger å klikke disse koblingene i innholdet og til slutt registrere seg for dem. Ved å bruke dette nettstedet aksepterer du de begrensninger og utelukkelser av ansvar som er angitt i denne ansvarsfraskrivelsen og den separate ansvarsfraskrivelsen. Hvis du ikke er enig med dem, må du ikke bruke denne nettsiden. NyhetsbrevCGI - Håndter Common Gateway Interface forespørsler og svar BESKRIVELSE CGI. pm er en stabil, komplett og moden løsning for behandling og forberedelse av HTTP forespørsler og svar. Viktige funksjoner, inkludert behandling av skjemainnlegg, filopplastinger, lesing og skriving av informasjonskapsler, generering og manipulering av spørringsstrenger, og behandling og forbereding av HTTP-overskrifter. Noen HTML generasjonsverktøy er også inkludert. CGI. pm virker veldig bra i et vanilje CGI. pm miljø og leveres også med innebygd støtte for modperl og modperl2 samt FastCGI. Det har fordelen av å ha utviklet og raffinert over 10 år med innspill fra dusinvis av bidragsytere og blitt distribuert på tusenvis av nettsteder. CGI. pm har vært inkludert i Perl-distribusjonen siden Perl 5.4, og har blitt en de facto-standard. PROGRAMMERINGSTIL Det er to typer programmering med CGI. pm, en objektorientert stil og en funksjonsorientert stil. I objektorienterte stilen oppretter du en eller flere CGI-objekter, og bruker deretter objektmetoder for å lage de ulike elementene på siden. Hvert CGI-objekt starter med listen over navngitte parametere som ble sendt til CGI-scriptet av serveren. Du kan endre objektene, lagre dem til en fil eller database og gjenskape dem. Fordi hvert objekt tilsvarer tilstanden til CGI-skriptet, og fordi hver objektparameterliste er uavhengig av de andre, kan du lagre tilstanden til skriptet og gjenopprette det senere. For eksempel, ved hjelp av objektorientert stil, her er hvordan du lager en enkel Hello World HTML-side: I den funksjonsorienterte stilen finnes det ett standard CGI-objekt som du sjelden håndterer med. I stedet kaller du bare funksjoner for å hente CGI-parametere, lage HTML-koder, administrere informasjonskapsler og så videre. Dette gir deg et renere programmeringsgrensesnitt, men begrenser deg til å bruke ett CGI-objekt om gangen. Følgende eksempel skriver ut den samme siden, men bruker det funksjonsorienterte grensesnittet. De viktigste forskjellene er at vi nå må importere et sett med funksjoner i vårt navneområde (vanligvis standardfunksjonene), og vi trenger ikke å lage CGI-objektet. Eksemplene i dette dokumentet bruker hovedsakelig objektorienterte stiler. Se HVORDAN DU IMPORTER FUNKSJONER for viktig informasjon om funksjonsorientert programmering i CGI. pm. CALLING CGI. PM ROUTINES De fleste CGI. pm-rutiner godtar flere argumenter, noen ganger så mange som 20 valgfrie. For å forenkle dette grensesnittet bruker alle rutiner et navngitt argument som ringer stil som ser slik ut: Hver argumentnavn går foran med et dash. Hverken sak eller orden er viktig i argumentlisten. - type, - Type, og - TYPE er alle akseptable. Faktisk må bare det første argumentet begynne med et dash. Hvis et dash er til stede i det første argumentet, antar CGI. pm bindestrek for de etterfølgende. Flere rutiner kalles vanligvis med bare ett argument. I tilfelle av disse rutinene kan du gi det enkle argumentet uten et argumentnavn. header () skjer for å være en av disse rutinene. I dette tilfellet er det eneste argumentet dokumenttypen. Andre slike rutiner er dokumentert nedenfor. Noen ganger kaller navngitte argumenter en skalar, noen ganger en referanse til en matrise, og noen ganger en referanse til en hash. Ofte kan du passere alle typer argument, og rutinen vil gjøre det som passer best. For eksempel brukes param () rutinen til å sette en CGI-parameter til en enkeltverdig eller en verdivurdering. De to sakene er vist nedenfor: Et stort antall rutiner i CGI. pm faktisk arent spesifikt definert i modulen, men genereres automatisk etter behov. Dette er HTML-snarveiene, rutiner som genererer HTML-koder for bruk i dynamisk genererte sider. HTML-koder har begge attributter (attributevalue-parene i selve tagget) og innhold (delen mellom åpnings - og lukkeparene.) For å skille mellom attributter og innhold bruker CGI. pm konvensjonen om å sende HTML-attributter som en hashreferanse som første argument, og innholdet, hvis noen, som noen etterfølgende argumenter. Det virker slik: HTML-koder beskrives mer detaljert senere. Mange nybegynnere til CGI. pm er forundret av forskjellen mellom kallkonvensjonene for HTML-snarveiene, som krever krøllete braces rundt HTML-tagattributtene, og kallkonvensjonene for andre rutiner, som klarer å generere attributter uten de krøllete parentesene. Ikke vær forvirret. Som en bekvemmelighet er de krøllete armbåndene valgfrie i alle, men HTML-snarveiene. Hvis du vil, kan du bruke krøllete braces når du ringer til en hvilken som helst rutine som tar navngitte argumenter. For eksempel: Hvis du bruker - w-bryteren, blir du advart om at noen CGI. pm-argument heter konflikt med innebygde Perl-funksjoner. De hyppigste av disse er argumentene for verdier, som brukes til å lage flere verdifulle menyer, klyngeklynger og lignende. For å omgå denne advarselen har du flere valg: Bruk et annet navn for argumentet, hvis en er tilgjengelig. For eksempel er - value et alias for - verdier. Endre kapitalisering, f. eks. - Values ​​Sett anførselstegn rundt argumentnavnet, f. eks. - verdier Mange rutiner vil gjøre noe nyttig med et navngitt argument som det ikke gjenkjenner. Du kan for eksempel produsere ikke-standardiserte HTTP-headerfelt ved å gi dem som navngitte argumenter: Dette vil produsere følgende ikke-standardiserte HTTP-header: Legg merke til at understreker oversettes automatisk til bindestreker. HTML-genererende rutiner utfører en annen type oversettelse. Denne funksjonen lar deg følge med raskt endrede HTTP - og HTML-standarder. OPPSTILLING AV EN NEW QUERY OBJECT (OBJECT ORIENTED STYLE): Dette vil analysere inngangen (fra POST, GET og DELETE metoder) og lagre den i et perl5 objekt som heter spørring. Eventuelle filhåndteringer fra filopplastinger vil ha sin posisjon tilbakestilt til begynnelsen av filen. Opprette et nytt kvoterobjekt fra en inngangsfil Hvis du gir et filhåndtak til den nye () - metoden, vil den lese parametere fra filen (eller STDIN, eller hva som helst). Filen kan være i noen av skjemaene som er beskrevet nedenfor under feilsøking (det vil si at en serie av nybegrensede TAGVALUE-par vil fungere). Denne typen fil er hensiktsmessig opprettet ved hjelp av save () - metoden (se nedenfor). Flere poster kan lagres og gjenopprettes. Perl purister vil gjerne vite at denne syntaksen aksepterer referanser til filhåndtak, eller til og med referanser til filhandle globs, som er den offisielle måten å sende en filhåndtering på. Du kan også initialisere CGI-objektet med et FileHandle eller IO :: File-objekt. Hvis du bruker det funksjonsorienterte grensesnittet og vil initialisere CGI-tilstanden fra et filhåndtak, er måten å gjøre dette på med restoreparameters (). Dette vil (re) initialisere standard CGI-objektet fra det angitte filhåndtaket. Du kan også initialisere spørringsobjektet fra en hashreferanse: eller fra en riktig formatert spørringsstreng med URL-rømming: eller fra et tidligere eksisterende CGI-objekt (for øyeblikket klonrer parameterlisten, men ingen av de andre objektspesifikke feltene, slik som som autoscaping): For å opprette et tomt spørsmål, initialiser det fra en tom streng eller hash: FÅ EN LISTE OVER NØYTORD FRA KVARTALET: Hvis skriptet ble påkalt som et resultat av et ltISINDEXgt søk, kan de analyserte søkeordene oppnås som en matrise ved hjelp av søkeordene () - metoden. FETCHE NAMNENE AV ALLE PARAMETREPASSENE TIL SKRIVET: Hvis skriptet ble påkalt med en parameterliste (for eksempel navn1value1ampnavn2value2navnnavn3value3), vil param () - metoden returnere parameternavnene som en liste. Hvis skriptet ble påkalt som et ltISINDEXgt-skript og inneholder en streng uten ampersands (for eksempel value1value2value3). Det vil være en enkelt parameter kalt søkeord som inneholder de avgrensede søkeordene. MERK: Fra versjon 1.5 vil rekkefølgen av parameternavn som returneres, være i samme rekkefølge som de ble sendt inn av nettleseren. Vanligvis er denne bestillingen den samme som ordren der parametrene er definert i skjemaet (men dette er ikke en del av spesifikasjonen, og det er ikke garantert). FÅ VÆRD ELLER VÆRDIER AV EN ENKELT NAVN PARAMETER: Pass param () - metoden et enkelt argument for å hente verdien av den nevnte parameteren. Hvis parameteren er multivalent (for eksempel fra flere valg i en rulleliste), kan du be om å motta en matrise. Ellers vil metoden returnere en enkelt verdi. Hvis en verdi ikke er oppgitt i spørringsstrengen, som i spørsmålene navn1navn2, vil den bli returnert som en tom streng. Hvis parameteren ikke eksisterer i det hele tatt, vil param () returnere undef i en skalar kontekst, og den tomme listen i en liste kontekst. INNSTILLING AV VERDIEN AV EN NAVN PARAMETER: Dette setter verdien for den navngitte parameteren foo til en rekke verdier. Dette er en måte å endre verdien av et felt etter at skriptet er påkalt en gang før. (En annen måte er med overgangsparameteren akseptert av alle metoder som genererer formelementer.) Param () gjenkjenner også en navngitt parameter stil av anrop som beskrives mer detaljert senere: TILBYGGE YTTERLIGERE VÆRDIER TIL EN NAVN PARAMETER: Dette legger til en verdi eller liste av verdier til den navngitte parameteren. Verdiene er vedlagt til slutten av parameteren hvis den allerede eksisterer. Ellers er parameteren opprettet. Merk at denne metoden bare gjenkjenner det navngitte argumentet som kalles syntax. IMPORTERE ALLE PARAMETRE I ET NAVN: Dette skaper en rekke variabler i R-navneområdet. For eksempel, R :: foo, R: foo. For søkeordlister vises en variabel R :: søkeord. Hvis ingen navneområde er oppgitt, antar denne metoden Q. ADVARSEL: Ikke importer noe til hoved Dette er en stor sikkerhetsrisiko. MERK 1: Variable navn transformeres etter behov i juridiske Perl-variabelnavn. Alle ikke-juridiske tegn blir forvandlet til underskrifter. Hvis du trenger å beholde de opprinnelige navnene, bør du bruke param () - metoden i stedet for å få tilgang til CGI-variabler ved navn. MERK 2: I eldre versjoner ble denne metoden kalt import (). Fra versjon 2.20 er dette navnet fjernet helt for å unngå konflikt med den innebygde Perl-modulen importoperatøren. SLETTING AV EN PARAMETER HELT: Dette sletter helt en liste over parametere. Det er noen ganger nyttig for å tilbakestille parametere som du ikke vil ha gått ned mellom scriptinvitasjoner. Hvis du bruker funksjonsanropsgrensesnittet, bruker du Slett () i stedet for å unngå konflikter med Perls innebygde sletteoperatør. SLETT ALLE PARAMETRE: Dette fjerner CGI-objektet helt. Det kan være nyttig å sikre at alle standardinnstillingene blir tatt når du oppretter et utfyllingsskjema. Bruk Deleteall () i stedet hvis du bruker funksjonsoppringingsgrensesnittet. HÅNDTERING AV IKKE-URLENCODED ARGUMENTS Hvis POSTed data ikke er av typen applicationx-www-form-urlencoded eller multipartform-data, blir ikke POSTed-dataene behandlet, men returneres i stedet som-er i en parameter som heter POSTDATA. For å hente det, bruk kode som dette: På samme måte hvis PUTed data kan hentes med kode som dette: (Hvis du ikke vet hva det foregående betyr, ikke bekymre deg for det. Det påvirker bare folk som prøver å bruke CGI for XML-behandling og andre spesialiserte Oppgaver.) DIREKTE TILGANG TIL PARAMETERLISTE: Hvis du trenger tilgang til parameterlisten på en måte som ikke er dekket av metodene som er gitt i de forrige avsnittene, kan du få en direkte referanse til den ved å ringe paramfetch () - metoden med navn på parameteren. Dette vil returnere en arrayreferanse til den navngitte parameteren, som du deretter kan manipulere på en måte du liker. Du kan også bruke en navngitt argumentstype ved hjelp av navnet-argumentet. FÅ PARAMETERLISTEET SOM EN HASH: Mange ønsker å hente hele parameterlisten som en hash der nøklene er navnene på CGI-parametrene, og verdiene er parameterverdiene. Metoden Vars () gjør dette. Kalt i en skalar kontekst, returnerer den parameterlisten som en bundet hashreferanse. Hvis du endrer en nøkkel, endres verdien av parameteren i den underliggende CGI-parameterlisten. Kalt i en liste kontekst, returnerer den parameterlisten som en vanlig hash. Dette lar deg lese innholdet i parameterlisten, men ikke for å endre det. Når du bruker dette, må du passe på CGI-parametere med flere verdier. Fordi en hash ikke kan skille mellom skalar og listekontekst, vil multivalued parametere bli returnert som en pakket streng, adskilt av 0 (null) tegn. Du må dele denne pakkede strengen for å komme til de individuelle verdiene. Dette er konvensjonen som ble introdusert for lenge siden av Steve Brenner i sin cgi-lib. pl-modul for Perl versjon 4. Hvis du vil bruke Vars () som en funksjon, importerer du: cgi-lib-settet med funksjonssamtaler (se også delen på CGI-LIB-kompatibilitet). SPARER STATENS SKRIFT TIL EN FIL: Dette vil skrive gjeldende tilstand for skjemaet til den angitte filhåndtaket. Du kan lese det inn igjen ved å gi en filhåndtering til den nye () - metoden. Merk at filhåndtaket kan være en fil, et rør eller hva som helst Formatet til den lagrede filen er: Både navn og verdi er URL-rømmet. Flerverdierte CGI-parametere er representert som gjentatte navn. En øktpost er avgrenset av et enkelt symbol. Du kan skrive ut flere poster og lese dem inn igjen med flere samtaler til nye. Du kan gjøre dette på tvers av flere økter ved å åpne filen i append-modus, slik at du kan opprette primitive gjestebøker, eller for å holde en historie om brukerens søk. Heres et kort eksempel på å opprette flere økt poster: Filformatet som brukes for saverestore er identisk med det som brukes av Whitehead Genome Centers datautvekslingsformat Boulderio, og kan manipuleres og til og med databasert ved hjelp av Boulderio-verktøy. Se for ytterligere detaljer. Hvis du vil bruke denne metoden fra det funksjonsorienterte (ikke-OO) grensesnittet, er det eksporterte navnet for denne metoden saveparameters (). RETRIEVING CGI ERRORS Feil kan oppstå under behandling av brukerinngang, spesielt når du behandler opplastede filer. Når disse feilene oppstår, vil CGI slutte å behandle og returnere en tom parameterliste. Du kan teste for eksistensen og arten av feil ved hjelp av cgierror () - funksjonen. Feilmeldingene er formatert som HTTP-statuskoder. Du kan enten inkorporere feilteksten i en HTML-side, eller bruke den som verdien av HTTP-statusen: Når du bruker det funksjonsorienterte grensesnittet (se neste avsnitt), kan feil bare oppstå første gang du ringer param (). Vær klar til dette BRUK AV FUNKSJONSORIENTERT INTERFACE For å bruke det funksjonsorienterte grensesnittet må du angi hvilke CGI. pm-rutiner eller sett av rutiner som skal importeres til skriptnavnene dine. Det er en liten overhead forbundet med denne importen, men det er ikke mye. De oppførte metodene blir importert til den nåværende pakken, du kan ringe dem direkte uten å opprette et CGI-objekt først. Dette eksemplet viser hvordan du importerer param () og header () metoder, og bruker dem direkte: Oftere, vil du importere vanlige sett med funksjoner ved å referere til gruppene etter navn. Alle funksjonssettene foregår med et: tegn som i: html3 (for koder definert i HTML 3-standarden). Her er en liste over funksjonssettene du kan importere: Importer alle CGI-håndteringsmetoder, for eksempel param (). pathinfo () og lignende. Importer alle utfyllingsform generere metoder, for eksempel tekstfelt (). Importer alle metoder som genererer HTML 2.0 standardelementer. Importer alle metoder som genererer HTML 3.0-elementer (for eksempel lttablegt, ltsupergt og ltsubgt). Importer alle metoder som genererer HTML 4 elementer (for eksempel labb, ltacronymgt og lttheadgt). Importer ltblinkgt, ltfontsizegt og ltcentergt-koder. Importer alle HTML-genererende snarveier (dvs. html2, html3, html4 og netscape) Importer standardfunksjoner, html2, html3, html4, skjema og cgi. Importer alle tilgjengelige metoder. For den fullstendige listen, se CGI. pm-koden, der variabelen EXPORTTAGS er definert. Hvis du importerer et funksjonsnavn som ikke er en del av CGI. pm, behandler modulen den som en ny HTML-kode og genererer den aktuelle subrutinen. Du kan da bruke den som en hvilken som helst annen HTML-kode. Dette er å sørge for den raskt utviklede HTML-standarden. For eksempel, sier Microsoft kommer ut med en ny tag kalt ltgradientgt (som får brukerens skrivebord til å bli oversvømt med en roterende gradient fylling til maskinen starter på nytt). Du trenger ikke å vente på en ny versjon av CGI. pm for å begynne å bruke den umiddelbart: Merk at i CGI. pms interesse ikke bruker standardeksportsekstaxen for å angi lastsymboler. Dette kan endres i fremtiden. Hvis du importerer noen av de statlige opprettholde CGI - eller formgenererende metodene, vil et standard CGI-objekt bli opprettet og initialisert automatisk første gang du bruker noen av metodene som krever at man er til stede. Dette inkluderer param (). tekstfelt() . send () og lignende. (Hvis du trenger direkte tilgang til CGI-objektet, kan du finne det i den globale variabelen CGI :: Q). Ved å importere CGI. pm metoder, kan du opprette visuelt elegante skript: I tillegg til funksjonssettene, finnes det en rekke pragmas du kan importere. Pragmas, som alltid foregår av en bindestrek, endrer måten CGI. pm fungerer på forskjellige måter. Pragmas, funksjonssett og individuelle funksjoner kan alle importeres i samme bruk () - linje. For eksempel importerer følgende bruksoppgave standard sett av funksjoner og aktiverer feilsøkingsmodus (pragma - debug): Den nåværende listen over pragmas er som følger: Når du bruker CGI - any. så vil enhver metode som spørringsobjektet ikke gjenkjenner tolkes som en ny HTML-kode. Dette lar deg støtte neste ad hoc-HTML-utvidelse. Dette gjør at du kan gå vill med nye og ikke støttede tagger: Siden du bruker ltcitegtanyltcitegt, forårsaker det at noe feilkjente metodenavn skal tolkes som en HTML-kode, bruk den med forsiktighet eller ikke i det hele tatt. Dette fører til at de angitte autoloaded-metodene blir samlet opp foran, snarere enn utsatt til senere. Dette er nyttig for skript som kjører i lengre tid under FastCGI eller modperl, og for de som er bestemt for å bli knust av Malcolm Beatties Perl-kompilatoren. Bruk den sammen med metodene eller metoden familier du planlegger å bruke. Vær oppmerksom på at bruk av kompilert pragma på denne måten alltid vil føre til at de kompilerte funksjonene blir importert til det nåværende navneområdet. Hvis du vil kompilere uten å importere, bruk kompilatoren () - metoden i stedet: Dette er spesielt nyttig i et modperl-miljø, der du kanskje vil forkompilere alle CGI-rutiner i et oppstartsskript, og deretter importere funksjonene individuelt i hvert modperl-skript. Som standard implementerer CGI-modulen en tilstandsbevarende atferd som kalles klebrig felt. Måten dette virker på er at hvis du regenererer et skjema, vil metodene som genererer formfeltverdiene, forhøre param () for å se om tilsvarende parametere er tilstede i spørringsstrengen. Hvis de finner en like-navngitt parameter, vil de bruke den til å angi standardverdiene. Noen ganger er dette ikke hva du vil. Den - nostiske pragma forhindrer denne oppførselen. Du kan også selektivt endre klistret oppførsel i hvert element du genererer. Legg automatisk til fanefeltattributtene til hvert skjemafelt. Når dette alternativet er slått av, kan du fortsatt legge til fanindekser manuelt ved å sende et - tabindex-alternativ til hver feltgenereringsmetode. Dette holder CGI. pm fra å inkludere undef-parametere i parameterlisten. Som standard sender CGI. pm-versjoner 2,69 og høyere XHTML (w3.orgTRxhtml1). - noxhtml pragma deaktiverer denne funksjonen. Takk til Michalis Kabrianis ltkabrianishellug. grgt for denne funksjonen. Hvis parameteren starthtml () s-dtd spesifiserer en HTML 2.0, 3.2, 4.0 eller 4.01 DTD, blir XHTML automatisk deaktivert uten å måtte bruke denne pragmaen. Dette gjør at CGI. pm behandler alle parametere som UTF-8-strenger. Bruk dette med forsiktighet, da det vil forstyrre behandlingen av binære opplastinger. Det er bedre å manuelt velge hvilke felt som forventes å returnere utf-8 strenger og konvertere dem ved hjelp av kode som dette: Dette gjør at CGI. pm produserer en header som er riktig for et NPH (ikke-parsert overskrift) - skript. Du må kanskje også gjøre andre ting for å fortelle serveren at skriptet er NPH. Se diskusjonen om NPH-skript nedenfor. Separer namevalue-parene i CGI-parameterens spørringsstrenger med semikoloner i stedet for ampersands. For eksempel: Semikolonavgrensede søksnor er alltid akseptert, og vil bli sendt ut av selfurl () og spørringstring (). newstyleurls ble standard i versjon 2.64. Separer namevalue-parene i CGI-parameterens spørringsstrenger med ampersands i stedet for semikoloner. Dette er ikke lenger standard. Dette overstyrer autoloaderen slik at enhver funksjon i programmet ditt som ikke er gjenkjent, blir referert til CGI. pm for mulig evaluering. Dette gjør det mulig å bruke alle CGI. pm-funksjonene uten å legge dem til symboltabellen, noe som har betydning for modperl-brukere som er bekymret for minnekonsumtion. Advarsel: Når - autoload er i kraft, kan du ikke bruke poesi-modus (funksjoner uten parentes). Bruk hr () i stedet for hr. eller legg til noe som å bruke subs qwhr p header til toppen av scriptet ditt. Dette slår av på kommandolinjebehandlingsfunksjonene. Hvis du vil kjøre et CGI. pm-skript fra kommandolinjen for å lage HTML, og du ikke vil at den skal lese CGI-parametere fra kommandolinjen eller STDIN, bruk denne pragmaen: Dette slår på full feilsøking. I tillegg til å lese CGI-argumenter fra kommandolinjebehandlingen, vil CGI. pm pause og prøve å lese argumenter fra STDIN, som produserer meldingen (offline modus: angi navnevalupar på standardinngang). Se delen om feilsøking for flere detaljer. CGI. pm kan behandle opplastet fil. Vanligvis spoler den opplastede filen til en midlertidig katalog, og sletter filen når den er ferdig. Dette åpner imidlertid risikoen for avlytting som beskrevet i filopplastingsseksjonen. En annen CGI-skriptforfatter kan se på disse dataene under opplasting, selv om det er konfidensiell informasjon. På Unix-systemer vil pragma-privatemempfilene føre til at den midlertidige filen kobles fra når den er åpnet, og før data blir skrevet inn i den, reduserer, men eliminerer ikke risikoen for avlytting (det er fortsatt en potensiell rasebetingelse). For å gjøre livet vanskeligere for angriperen velger programmet tempfile-navn ved å beregne et 32-bits kontrollsum for de innkommende HTTP-overskriftene. For å sikre at den midlertidige filen ikke kan leses av andre CGI-skript, bruk suEXEC eller et CGI wrapper-program for å kjøre skriptet. Den midlertidige filen er opprettet med modus 0600 (verken verden eller gruppelesbar). Den midlertidige katalogen er valgt ved hjelp av følgende algoritme: Hver av disse stedene er sjekket at den er en katalog og kan skrives. Hvis ikke, prøver algoritmen neste valg. SPESIELLE FORMER FOR IMPORT AV HTML-TAG-FUNKSJONER Mange av metodene genererer HTML-koder. Som beskrevet nedenfor genererer tagfunksjoner automatisk både åpnings - og lukkekoder. For eksempel: Det vil være noen ganger når du vil produsere start - og sluttkoder selv. I dette tilfellet kan du bruke skjemaet start tagname og slutt tagname. som i: Med noen få unntak (beskrevet nedenfor), startes tagnam og slutt tagnamfunksjoner ikke genereres automatisk når du bruker CGI. Du kan imidlertid angi kodene du vil generere startende funksjoner for ved å sette en stjerne foran navnet sitt, eller alternativt be om å starte enten tagnamess eller slutt tagnam i importlisten. I dette eksemplet genereres følgende funksjoner i tillegg til standardene: 1. starttable () (genererer en lttablegt-tag) 2. endtable () (genererer en lttablegt-tag) 3. startul () (genererer en ltulgt-tag) 4 . endul () (genererer en ltulgt-tag) GENERERENDE DYNAMISK DOKUMENTER De fleste av CGI. pms-funksjonene omhandler å lage dokumenter på fluen. Vanligvis produserer du HTTP-header først, etterfulgt av selve dokumentet. CGI. pm gir funksjoner for generering av HTTP-overskrifter av ulike typer, samt for generering av HTML. For å lage GIF-bilder, se GD. pm-modulen. Hver av disse funksjonene produserer et fragment av HTML eller HTTP som du kan skrive ut direkte slik det vises i nettleservinduet, legge til en streng eller lagre til en fil for senere bruk. Opprette en standard HTTP-hoved: Normalt er det første du vil gjøre i et CGI-skript, utskrift av en HTTP-header. Dette forteller nettleseren hvilken type dokument du kan forvente, og gir annen valgfri informasjon, for eksempel språket, utløpsdatoen og om du vil cache dokumentet. Overskriften kan også manipuleres til spesielle formål, for eksempel server push og pay per visningssider. header () returnerer Innholdstype: header. Du kan angi din egen MIME-type hvis du velger, ellers er det standard for texthtml. En valgfri andre parameter angir statuskoden og en menneskelig lesbar melding. For eksempel kan du spesifisere 204, Ingen svar på å lage et skript som forteller at nettleseren ikke skal gjøre noe i det hele tatt. Merk at RFC 2616 forventer at den menneskelige lesbare fasen skal være der, så vel som den numeriske statuskoden. Det siste eksempelet viser den navngitte argumentstilen for å sende argumenter til CGI-metodene ved å bruke navngitte parametere. Anerkjente parametere er - type. - status. - utløper. og - cookie. Eventuelle andre navngitte parametere vil bli fjernet av deres første bindestreker og omgjort til headerfelt, slik at du kan angi hvilken HTTP-header du ønsker. Interne underskrifter blir omgjort til bindestreker: De fleste nettlesere vil ikke cache utdataene fra CGI-skript. Hver gang nettleseren oppdaterer siden, skrives manuskriptet på nytt. Du kan endre denne oppførselen med parameteren - expires. Når du angir et absolutt eller relativ utløpsintervall med denne parameteren, vil noen nettlesere og proxy-servere cache skriptutgangene til den angitte utløpsdatoen. Følgende skjemaer er alle gyldige for expires-feltet: - cookie-parameteren genererer en header som forteller nettleseren å gi en magisk informasjonskapsel under alle påfølgende transaksjoner med skriptet. Noen informasjonskapsler har et spesielt format som inneholder interessante attributter som forfallstid. Bruk metoden cookie () til å opprette og hente øktkaker. Parameteren - nph, hvis den er satt til en ekte verdi, vil utstede de riktige overskriftene for å fungere med et NPH (no-parse-header) - skript. Dette er viktig å bruke med enkelte servere som forventer at alle deres skript skal være NPH. Parameter - karet kan brukes til å kontrollere tegnsettet som er sendt til nettleseren. Hvis ikke oppgitt, er standard ISO-8859-1. Som en bivirkning setter dette også metoden charset (). Tilkoblingsparameteren kan brukes til å slå siden til et vedlegg. I stedet for å vise siden, vil noen nettlesere be brukeren om å lagre den på disk. Verdien av argumentet er det foreslåtte navnet på den lagrede filen. For at dette skal fungere, må du kanskje angi typen til applicationoctet-stream. Parameteren - p3p vil legge til en P3P-tag til den utgående overskriften. Parameteren kan være en arrayref eller en romavgrenset streng av P3P-koder. For eksempel: I begge tilfeller blir den utgående overskriften formatert som: CGI. pm vil godta gyldige linjer med flere linjer når hver linje er separert med en CRLF-verdi (rn på de fleste plattformer) etterfulgt av minst ett mellomrom. For eksempel: Ugyldig linje med flere overskrifter vil utløse i et unntak. Når flere linjers overskrifter er mottatt, vil CGI. pm alltid sende dem tilbake som en enkelt linje, i henhold til brettreglene for RFC 2616: Newlines vil bli fjernet, mens den hvite plassen forblir. GENERERE EN REDIREKSJONSHODER Noen ganger vil du ikke selv lage et dokument, men bare omdirigere nettleseren andre steder, kanskje velge en URL basert på klokkeslett eller brukerens identitet. Metoden omdirigering () omdirigerer nettleseren til en annen URL. Hvis du bruker omadressering som dette, bør du ikke skrive ut en header også. Du bør alltid bruke hele nettadressene (inkludert http: eller ftp: delen) i omadresseringsforespørsler. Relative nettadresser virker ikke riktig. Du kan også bruke navngitte argumenter: Alle navneargumenter gjenkjent av overskrift () blir også gjenkjent av omdirigering (). Imidlertid ignoreres de fleste HTTP-overskrifter, inkludert de som genereres av - cookie og - target, av nettleseren. Parameteren - nph, hvis den er satt til en ekte verdi, vil utstede de riktige overskriftene for å fungere med et NPH (no-parse-header) - skript. Dette er viktig å bruke med visse servere, for eksempel Microsoft IIS, som forventer at alle deres skript skal være NPH. Status-parameteren vil angi status for omadresseringen. HTTP definerer tre forskjellige mulige omadresseringsstatuskoder: Standard hvis ikke spesifisert er 302, noe som betyr at det er midlertidig flyttet. Du kan endre statusen til en annen statuskode hvis du ønsker det. Vær oppmerksom på at endring av status til noe annet enn 301, 302 eller 303 vil trolig bryte omdirigering. Merk at den menneskelige lesbare setningen også forventes å være til stede for å overholde RFC 2616, avsnitt 6.1. SKAPE HTML-DOKUMENT HEADER Starthtml () - rutinen oppretter toppen av siden, sammen med mye valgfri informasjon som styrer utseende og oppførsel av sider. Denne metoden returnerer en hakket HTML-overskrift og åpningen ltbodygt-taggen. Alle parametere er valgfrie. I den nevnte parameterformen er kjente parametre - title, - author, - base, - xbase, - dtd, - lang og - target (se nedenfor for forklaringen). Eventuelle tilleggsparametre du oppgir, som det uoffisielle BGCOLOR-attributtet, blir lagt til ltbodygt-taggen. Ytterligere parametere må videreføres av en bindestrek. Argumentet - xbase gir deg mulighet til å gi en HREF for ltbasegt-taggen som er forskjellig fra den nåværende plasseringen, som i Alle relative lenker vil bli tolket i forhold til denne taggen. Argumentet - target lar deg angi en standard målramme for alle koblinger og utfyllingsskjemaer på siden. Dette er en ikke-standard HTTP-funksjon som bare fungerer med noen nettlesere. Alle relative lenker blir tolket i forhold til denne taggen. Du legger til vilkårlig meta-informasjon i overskriften med - meta-argumentet. Dette argumentet forventer en referanse til en hash som inneholder namevalue par meta-informasjon. Disse blir omgjort til en serie header ltmetagt-koder som ser slik ut: For å opprette en HTTP-EQUIV-type ltmetagt-tag, bruk-hoved. beskrevet nedenfor. Stilargumentet brukes til å inkorporere kaskade stilark i koden din. Se delen om CASCADING STYLESHEETS for mer informasjon. Det lange argumentet brukes til å inkludere et språkattributt i lthtmlgt-taggen. For eksempel: Standard hvis ikke spesifisert er en-US for US English, med mindre parameteren - dtd angir en HTML 2.0 eller 3.2 DTD, i så fall er lang attributten slått av. Du kan tvinge langattributtet til å gå av i andre tilfeller ved å sende en tom streng (-langt). Argumentet kan brukes til å angi tegnsettet for XHTML. Den er standard til iso-8859-1 hvis den ikke er spesifisert. - dtd-argumentet kan brukes til å spesifisere en offentlig DTD-identifikatorstreng. For eksempel: Alternativt kan det ta offentlige og system DTD-identifikatorer som en matrise: For at den offentlige DTD-identifikatoren skal vurderes, må den være gyldig. Ellers vil den bli erstattet av standard 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 ove r 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. Ikke veldig spennende. 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. EKSEMPEL: 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