17 Novembre 2005Stefano Clemente1 Scrivere CGI con Perl Finora si è visto come creare semplici...
-
Upload
marzia-russo -
Category
Documents
-
view
213 -
download
0
Transcript of 17 Novembre 2005Stefano Clemente1 Scrivere CGI con Perl Finora si è visto come creare semplici...
17 Novembre 2005 Stefano Clemente 1
Scrivere CGI con PerlScrivere CGI con Perl
• Finora si è visto come creare semplici applicazioni Perl che restituiscano dei risultati sullo standard output del computer che li esegue
• Attraverso CGI è possibile comunicare con il server web e con i suoi client permettendo ai programmi Perl di−ricevere l’input da Internet−restituire l’output su Internet
17 Novembre 2005 Stefano Clemente 2
Scrivere CGI con PerlScrivere CGI con Perl
• Le funzioni utili per la scrittura di CGI in Perl sono contenute nel modulo CGICGI che può essere incluso in un programma attraverso l’istruzione useuse
• Attraverso la use si può indicare anche quali funzioni importare dal modulo specificato−Es: use CGI qw( :standard );use CGI qw( :standard );
richiede l’importazione di un insieme standard di funzioni dal modulo CGICGI
17 Novembre 2005 Stefano Clemente 3
Scrivere CGI con PerlScrivere CGI con Perl• Quando si usa Perl per creare pagine web a
contenuto dinamico, si usano le funzioni printprint per generare XHTML
• Per generare un’intestazione HTTP valida, si utilizza la funzione headerheader della libreria CGICGI, che restituisce la stringa “Content-type: Content-type: text/html\n\ntext/html\n\n”
• La funzione start_htmlstart_html genera i tag di apertura (<html><html>, <head><head>, <title><title>, …, <body><body>)
17 Novembre 2005 Stefano Clemente 4
Scrivere CGI con PerlScrivere CGI con Perl
• Alcune informazioni addizionali come ad esempio gli attributi dei tag possono essere passate alle funzioni CGI nel modo seguente{ <chiave_1> => <valore_1>{ <chiave_1> => <valore_1>
[,… , <chiave_n> => <valore_n>] }[,… , <chiave_n> => <valore_n>] }
es: print ( start_html ( { dtd => print ( start_html ( { dtd => "-//W3C//DTD XHTML 1.0 "-//W3C//DTD XHTML 1.0 Transitional//EN\" Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd", title => -transitional.dtd", title => "Environment Variables..." } ) );"Environment Variables..." } ) );
17 Novembre 2005 Stefano Clemente 5
Scrivere CGI con PerlScrivere CGI con Perl
• Esistono varie funzioni che generano i tag HTMLes: TrTr, tdtd, thth, hrhr, spanspan, divdiv, brbr, ecc.
• I tag di chiusura della pagina vengono generati con la funzione end_htmlend_html
17 Novembre 2005 Stefano Clemente 6
Configurazione dei web serverConfigurazione dei web serverLe altre directory: cgi-binLe altre directory: cgi-bin• Apache tratta diversamente il tentativo di accesso alla
cgi-bin (comportamento dovuto alla definizione di default per questa directory in httpd.conf)− La directory cgi-bin è la directory usata da Apache per CGI
(Common Gateway Interface)
• CGI è un protocollo standard per l’interazione degli utenti con applicativi sul server web
• L’interazione avviene attraverso l’esecuzione di programmi o script
• La directory sotto cui risiedono gli script e i programmi CGI è pur sempre una directory virtuale o alias, ma deve avere dei diritti diversi, deve cioè permettere al client web di eseguire programmi sul server
17 Novembre 2005 Stefano Clemente 7
Configurazione dei web serverConfigurazione dei web serverLe altre directory: cgi-binLe altre directory: cgi-bin
• Creiamo in cgi-bin il file test.pl (perl)
17 Novembre 2005 Stefano Clemente 8
cgi-bin: configurazione di IIScgi-bin: configurazione di IIS
17 Novembre 2005 Stefano Clemente 9
cgi-bin: configurazione di IIScgi-bin: configurazione di IIS
17 Novembre 2005 Stefano Clemente 10
cgi-bin: configurazione di IIScgi-bin: configurazione di IIS
17 Novembre 2005 Stefano Clemente 11
cgi-bin: configurazione di IIScgi-bin: configurazione di IIS
17 Novembre 2005 Stefano Clemente 12
cgi-bin: configurazione di IIScgi-bin: configurazione di IIS
• Bisogna aggiungere a IIS il supporto per PERL!!!
17 Novembre 2005 Stefano Clemente 13
cgi-bin: configurazione di IIScgi-bin: configurazione di IIS
17 Novembre 2005 Stefano Clemente 14
cgi-bin: configurazione di Apachecgi-bin: configurazione di Apache
• Modifiche a httpd.conf−ScriptAlias /cgi-bin/ "C:/web/cgi-bin/"
−<Directory "C:/web/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
• Riavvio di Apache!!!
17 Novembre 2005 Stefano Clemente 15
Esempio 6: Variabili d’ambienteEsempio 6: Variabili d’ambiente
• Le variabili d’ambiente contengono le informazioni riguardanti l’ambiente in cui viene eseguito lo script− Es. browser utilizzato, l’host HTTP, la connessione HTTP, ecc
• Le informazioni contenute nelle variabili d’ambiente possono essere utilizzate dal server web per generare pagine web specifiche per il particolare browser
• La variabile hash %ENV di Perl contiene i nomi e i valori di tutte le variabili d’ambiente
• L’esempio mostra uno script Perl che genera una pagina XHTML contenente nomi e valori delle variabili d’ambiente presentati in forma tabellare
17 Novembre 2005 Stefano Clemente 16
Esempio 6: Variabili Esempio 6: Variabili d’ambiented’ambiente#!c:\perl\bin\perl.exe#!c:\perl\bin\perl.exe# Fig. 27.11: fig27_11.pl# Fig. 27.11: fig27_11.pl# Program to display CGI environment variables.# Program to display CGI environment variables.use CGI qw( :standard );use CGI qw( :standard );$dtd =$dtd ="-//W3C//DTD XHTML 1.0 Transitional//EN\""-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";print( header() );print( header() );print( start_html( { dtd => $dtd,print( start_html( { dtd => $dtd, title => "Environment Variables..." } ) );title => "Environment Variables..." } ) );print( "<table style = \"border: 0; padding: 2;print( "<table style = \"border: 0; padding: 2; font-weight: bold\">" );font-weight: bold\">" );print( Tr( th( "Variable Name" ),print( Tr( th( "Variable Name" ), th( "Value" ) ) );th( "Value" ) ) );print( Tr( td( hr() ), td( hr() ) ) );print( Tr( td( hr() ), td( hr() ) ) );foreach $variable ( sort( keys( %ENV ) ) ) {foreach $variable ( sort( keys( %ENV ) ) ) { print( Tr( td( { style => "background-color: #11bbff" }, print( Tr( td( { style => "background-color: #11bbff" }, $variable ),$variable ), td( { style => "font-size: 12pt" }, td( { style => "font-size: 12pt" }, $ENV{ $variable } ) ) );$ENV{ $variable } ) ) ); print( Tr( td( hr() ), td( hr() ) ) );print( Tr( td( hr() ), td( hr() ) ) );}}print( "</table>" );print( "</table>" );print( end_html() );print( end_html() );
17 Novembre 2005 Stefano Clemente 17
17 Novembre 2005 Stefano Clemente 18
17 Novembre 2005 Stefano Clemente 19
Form e validazione dei datiForm e validazione dei dati
• Le form permettono di raccogliere dati dagli utenti e di inviare questi dati al server web per l’elaborazione
• Quando l’utente fa una POSTPOST, i nomi dei campi della form e i valori assegnati agli stessi possono essere ricevuti da uno script che controlla la validità dei dati
• La funzione del modulo CGICGI per accedere ai campi della form è la paramparam$<variabile> = param ( "<nome_parametro>" );$<variabile> = param ( "<nome_parametro>" );
17 Novembre 2005 Stefano Clemente 20
Esempio 7: form e validazione Esempio 7: form e validazione datidati
<form method = "post" <form method = "post" action = action = "/cgi-bin/esempio7.pl">"/cgi-bin/esempio7.pl">
17 Novembre 2005 Stefano Clemente 21
17 Novembre 2005 Stefano Clemente 22
17 Novembre 2005 Stefano Clemente 23
Esempio 7: form e validazione Esempio 7: form e validazione datidati
17 Novembre 2005 Stefano Clemente 24
Esempio 7: form e validazione Esempio 7: form e validazione datidati
17 Novembre 2005 Stefano Clemente 25
Esempio 7: form e validazione Esempio 7: form e validazione datidati#!/usr/bin/perl#!/usr/bin/perl# Fig. 27.13: fig27_13.pl# Fig. 27.13: fig27_13.pl# Program to read information sent to the server# Program to read information sent to the server# from the form in the fig27_12.xhtml document.# from the form in the fig27_12.xhtml document.use CGI qw( :standard );use CGI qw( :standard );$os = param( "os" );$os = param( "os" );$firstName = param( "fname" );$firstName = param( "fname" );$lastName = param( "lname" );$lastName = param( "lname" );$email = param( "email" );$email = param( "email" );$phone = param( "phone" );$phone = param( "phone" );$book = param( "book" );$book = param( "book" );$dtd =$dtd ="-//W3C//DTD XHTML 1.0 Transitional//EN\""-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd";transitional.dtd";print( header() );print( header() );
17 Novembre 2005 Stefano Clemente 26
Esempio 7: form e validazione Esempio 7: form e validazione datidatiprint( start_html( { dtd => $dtd,print( start_html( { dtd => $dtd, title => "Form Results" } ) );title => "Form Results" } ) );if ( $phone =~ / ^ \( \d{3} \) \d{3} - \d{4} $ /x ) {if ( $phone =~ / ^ \( \d{3} \) \d{3} - \d{4} $ /x ) { print( "Hi " );print( "Hi " ); print( span( { style => "color: blue; font-weight: print( span( { style => "color: blue; font-weight:
bold" }, bold" }, $firstName ) );$firstName ) ); print( "!" );print( "!" ); print( "\nThank you for completing the survey." );print( "\nThank you for completing the survey." ); print( br(), "You have been added to the " );print( br(), "You have been added to the " ); print( span( { style => "color: blue; font-weight: print( span( { style => "color: blue; font-weight:
bold" },bold" }, $book ) );$book ) ); print( " mailing list.", br(), br() );print( " mailing list.", br(), br() ); print( span( { style => "font-weight: bold" },print( span( { style => "font-weight: bold" }, "The following information has"The following information has been saved in our database: " ), been saved in our database: " ),
br() );br() );
17 Novembre 2005 Stefano Clemente 27
Esempio 7: form e validazione Esempio 7: form e validazione datidati print( table(print( table( Tr( th( { style => "background-color: #ee82ee" }, Tr( th( { style => "background-color: #ee82ee" }, "Name" ),"Name" ), th( { style => "background-color: #9370db" }, th( { style => "background-color: #9370db" }, "E-mail" ),"E-mail" ), th( { style => "background-color: #4169e1" }, th( { style => "background-color: #4169e1" }, "Phone" ),"Phone" ), th( { style => "background-color: #40e0d0" }, th( { style => "background-color: #40e0d0" }, "OS" ) ),"OS" ) ), Tr( { style => "background-color: #c0c0c0" },Tr( { style => "background-color: #c0c0c0" }, td( "$firstName $lastName" ),td( "$firstName $lastName" ), td( $email ),td( $email ), td( $phone ),td( $phone ), td( $os ) ) ) );td( $os ) ) ) ); print( br() );print( br() );
17 Novembre 2005 Stefano Clemente 28
Esempio 7: form e validazione Esempio 7: form e validazione datidati print( div( { style => "font-size: x-small" },print( div( { style => "font-size: x-small" }, "This is only a sample form. You have not been"This is only a sample form. You have not been added to a mailing list." ) ); added to a mailing list." ) ); }}else {else { print( div( { style => "color: red; font-size: x-large" },print( div( { style => "color: red; font-size: x-large" }, "INVALID PHONE NUMBER" ), br() );"INVALID PHONE NUMBER" ), br() ); print( "A valid phone number must be in the form " );print( "A valid phone number must be in the form " ); print( span( { style => "font-weight: bold" },print( span( { style => "font-weight: bold" }, "(555)555-5555." ) );"(555)555-5555." ) ); print( div( { style => "color: blue" },print( div( { style => "color: blue" }, "Click the Back button, and enter a"Click the Back button, and enter a valid phone number and resubmit." ) );valid phone number and resubmit." ) ); print( br(), br() );print( br(), br() ); print( "Thank you." );print( "Thank you." );}}print( end_html() );print( end_html() );
17 Novembre 2005 Stefano Clemente 29
Server-Side Includes (SSI)Server-Side Includes (SSI)
• Server-Side Includes (SSI) sono comandi inseriti in documenti XHTML che permettono la creazione di semplici contenuti dinamici
• Alcuni comandi SSI−EXECEXEC permette l’esecuzione di script CGI e inserisce
l’output di questi direttamente nella pagina web−ECHOECHO e INCLUDEINCLUDE permettono di inserire nelle pagine
web elementi che cambiano continuamente come l’orario o informazioni contenute in un database
17 Novembre 2005 Stefano Clemente 30
Server-Side Includes (SSI)Server-Side Includes (SSI)
• Non tutti i web server supportano SSI, per cui i comandi vengono inseriti nelle pagine web come commenti<!--#EXEC CGI=“/cgi-bin/file.pl” --><!--#EXEC CGI=“/cgi-bin/file.pl” -->
• I documenti contenenti i comandi SSI hanno solitamente estensione .shtml.shtml dove la ss iniziale sta per server
• I file .shtml.shtml sono analizzati dal server che esegue i comandi SSI, riscrive il documento con gli output dei comandi e lo invia al client
17 Novembre 2005 Stefano Clemente 31
Server-Side Includes (SSI)Server-Side Includes (SSI)• IIS è già configurato per l’esecuzione di SSI• Apache richiede alcune modifiche al file httpd.confhttpd.conf
− Le seguenti direttive permettono ad Apache di gestire i file .shtml.shtml AddType text/html .shtmlAddType text/html .shtmlAddOutputFilter INCLUDES .shtmlAddOutputFilter INCLUDES .shtml
− La direttiva seguente deve essere impostata nelle directory che contengono i file .shtml.shtml (in una sezione <Directory><Directory>):Options +IncludesOptions +Includes
− Nel caso del file httpd.confhttpd.conf visto finoraDocumentRoot "C:/web/html“DocumentRoot "C:/web/html“<Directory /><Directory />
Options FollowSymLinksOptions FollowSymLinksOptions +IncludesOptions +IncludesAllowOverride NoneAllowOverride None
</Directory></Directory>
17 Novembre 2005 Stefano Clemente 32
Esempio 8: SSIEsempio 8: SSI
• In questo esempio verrà mostrato un documento .shtml che−esegue uno script CGI per tenere traccia
degli accessi alla pagina web appoggiandosi a un file su server nel quale memorizza il valore del contatore
−esegue vari comandi ECHOECHO per visualizzare il valore di alcune informazioni variabili
−DATE_GMTDATE_GMT−DOCUMENT_NAMEDOCUMENT_NAME−DATE_LOCALDATE_LOCAL−LAST_MODIFIEDLAST_MODIFIED−REMOTE_ADDRREMOTE_ADDR
−SERVER_NAMESERVER_NAME−SERVER_SOFTWARESERVER_SOFTWARE−HTTP_USER_AGENTHTTP_USER_AGENT−GATEWAY_INTERFACEGATEWAY_INTERFACE
17 Novembre 2005 Stefano Clemente 33
Esempio 8: SSIEsempio 8: SSI
17 Novembre 2005 Stefano Clemente 34
Esempio 8: SSIEsempio 8: SSI
17 Novembre 2005 Stefano Clemente 35
Esempio 8: SSIEsempio 8: SSI
17 Novembre 2005 Stefano Clemente 36
Esempio 8: SSIEsempio 8: SSI<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- esempio8.shtml --><!-- esempio8.shtml -->
<html><html> <head><head> <title>Using Server Side Includes</title><title>Using Server Side Includes</title> </head></head>
<body> <body> <h3 style = "text-align: center"><h3 style = "text-align: center"> Using Server Side IncludesUsing Server Side Includes </h3></h3> <!--#EXEC CGI="/cgi-bin/esempio8.pl" --><br /><!--#EXEC CGI="/cgi-bin/esempio8.pl" --><br />
17 Novembre 2005 Stefano Clemente 37
Esempio 8: SSIEsempio 8: SSI The Greenwich Mean Time is The Greenwich Mean Time is <span style = "color: blue"><span style = "color: blue"> <!--#ECHO VAR="DATE_GMT" -->.<!--#ECHO VAR="DATE_GMT" -->. </span><br /></span><br /> The name of this document is The name of this document is <span style = "color: blue"><span style = "color: blue"> <!--#ECHO VAR="DOCUMENT_NAME" -->.<!--#ECHO VAR="DOCUMENT_NAME" -->. </span><br /></span><br />
The local date is The local date is <span style = "color: blue"> <span style = "color: blue"> <!--#ECHO VAR="DATE_LOCAL" -->.<!--#ECHO VAR="DATE_LOCAL" -->. </span><br /></span><br />
This document was last modified on This document was last modified on <span style = "color: blue"><span style = "color: blue"> <!--#ECHO VAR="LAST_MODIFIED" -->.<!--#ECHO VAR="LAST_MODIFIED" -->. </span><br /></span><br />
17 Novembre 2005 Stefano Clemente 38
Esempio 8: SSIEsempio 8: SSI Your current IP Address is Your current IP Address is <span style = "color: blue"> <span style = "color: blue"> <!--#ECHO VAR="REMOTE_ADDR" -->.<!--#ECHO VAR="REMOTE_ADDR" -->. </span><br /></span><br />
My server name is My server name is <span style = "color: blue"><span style = "color: blue"> <!--#ECHO VAR="SERVER_NAME" -->.<!--#ECHO VAR="SERVER_NAME" -->. </span><br /></span><br />
And I am using the And I am using the <span style = "color: blue"> <span style = "color: blue"> <!--#ECHO VAR="SERVER_SOFTWARE" --><!--#ECHO VAR="SERVER_SOFTWARE" --> Web Server.Web Server. </span><br /></span><br />
17 Novembre 2005 Stefano Clemente 39
Esempio 8: SSIEsempio 8: SSI You are usingYou are using <span style = "color: blue"> <span style = "color: blue"> <!--#ECHO VAR="HTTP_USER_AGENT" -->.<!--#ECHO VAR="HTTP_USER_AGENT" -->. </span><br /></span><br />
This server is using This server is using <span style = "color: blue"> <span style = "color: blue"> <!--#ECHO VAR="GATEWAY_INTERFACE" -->.<!--#ECHO VAR="GATEWAY_INTERFACE" -->. </span><br /></span><br />
<br /><br /><br /><br /> <div style = "text-align: center;<div style = "text-align: center; font-size: xx-small">font-size: xx-small"> <hr /><hr /> This document was last modified on This document was last modified on <!--#ECHO VAR="LAST_MODIFIED" -->.<!--#ECHO VAR="LAST_MODIFIED" -->. </div></div> </body></body></html></html>
17 Novembre 2005 Stefano Clemente 40
Esempio 8: SSIEsempio 8: SSI#!c:\perl\bin\perl.exe#!c:\perl\bin\perl.exe# esempio8.pl# esempio8.pl# Program to track the number of times a Web page has been accessed.# Program to track the number of times a Web page has been accessed.use CGI qw( :standard );use CGI qw( :standard );open( COUNTREAD, "counter.dat" ); open( COUNTREAD, "counter.dat" ); # apre il file in lettura# apre il file in lettura$data = <COUNTREAD>; $data = <COUNTREAD>; # legge una riga# legge una riga $data++; $data++; # incrementa di uno# incrementa di unoclose( COUNTREAD ); close( COUNTREAD ); # chiude counter.dat# chiude counter.datopen( COUNTWRITE, ">counter.dat" ); open( COUNTWRITE, ">counter.dat" ); # apre in scrittura# apre in scritturaprint( COUNTWRITE $data ); print( COUNTWRITE $data ); # Scrive il valore ++# Scrive il valore ++close( COUNTWRITE ); close( COUNTWRITE ); # chiude counter.dat# chiude counter.datprint( header(), "<div style = \"text-align: center; font-weight: print( header(), "<div style = \"text-align: center; font-weight:
bold\">“ );bold\">“ );print( "You are visitor number", br() );print( "You are visitor number", br() );for ( $count = 0; $count < length( $data ); $count++ ) {for ( $count = 0; $count < length( $data ); $count++ ) { $number = substr( $data, $count, 1 );$number = substr( $data, $count, 1 ); print( img( { src => "images/$number.gif" } ), "\n" );print( img( { src => "images/$number.gif" } ), "\n" );}}print( "</div>" );print( "</div>" );
17 Novembre 2005 Stefano Clemente 41
Esempio 9: Verifica di Username Esempio 9: Verifica di Username e Passworde Password• In questo esempio verrà mostrato un semplice metodo per
l’autenticazione degli utenti basato su un elenco di utenti memorizzato su un file di testo (password.txt) nella formanomeutente,passwordnomeutente,password
• Lo script Perl introduce le istruzioni• while ( $line = <FILE> ) {while ( $line = <FILE> ) {
… …}}che ad ogni ciclo legge una riga dal file e termina quando viene raggiunta la fine del file
• chomp ( $line );chomp ( $line );che rimuove da $line$line il carattere di newline
• split ( “,”, $line )split ( “,”, $line )che divide la stringa contenuta in $line$line in due sottostringhe, quelle a destra e a sinistra della virgola.
17 Novembre 2005 Stefano Clemente 42
Esempio 9:Esempio 9:file password.txtfile password.txt
17 Novembre 2005 Stefano Clemente 43
Esempio 9Esempio 9
17 Novembre 2005 Stefano Clemente 44
Esempio 9Esempio 9
17 Novembre 2005 Stefano Clemente 45
Esempio 9Esempio 9
• Attenzione a proteggere i file con le password!
IISIIS APACHEAPACHE
17 Novembre 2005 Stefano Clemente 46
Esempio 9Esempio 9
17 Novembre 2005 Stefano Clemente 47
Esempio 9:Esempio 9:file esempio9.htmlfile esempio9.html<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><!-- esempio9 --> <!-- esempio9 --> <html><html> <head><head> <title>Verifying a username and a password</title><title>Verifying a username and a password</title> </head></head> <body><body> <p><p> <div style = "font-family = arial"><div style = "font-family = arial"> Type in your username and password below.Type in your username and password below. </div><br /></div><br /> <div style = "color: #0000ff; font-family: arial;<div style = "color: #0000ff; font-family: arial; font-weight: bold; font-size: x-small">font-weight: bold; font-size: x-small"> Note that the password will be sent as plain text.Note that the password will be sent as plain text. </div></div> </p></p> <form action = "/cgi-bin/esempio9.pl" method = "post"><form action = "/cgi-bin/esempio9.pl" method = "post">
<table style = "background-color: #dddddd"><table style = "background-color: #dddddd"> <tr><tr>
17 Novembre 2005 Stefano Clemente 48
Esempio 9:Esempio 9:file esempio9.htmlfile esempio9.html <td style = "font-face: arial;<td style = "font-face: arial; font-weight: bold">Username:</td>font-weight: bold">Username:</td> </tr></tr> <tr><tr> <td><td> <input name = "username" /><input name = "username" /> </td></td> </tr></tr> <tr><tr> <td style = "font-face: arial;<td style = "font-face: arial; font-weight: bold">Password:</td>font-weight: bold">Password:</td> </tr></tr> <tr><tr> <td><td> <input name = "password" type = "password" /><input name = "password" type = "password" /> </td></td> </tr></tr> <tr><tr> <td><td> <input type = "submit" value = "Enter" /><input type = "submit" value = "Enter" /> </td></td> </tr></tr> </table></table> </form></form> </body></body></html></html>
17 Novembre 2005 Stefano Clemente 49
Esempio 9:Esempio 9:file esempio9.plfile esempio9.pl#!c:\perl\bin\perl.exe#!c:\perl\bin\perl.exe# Fig. 27.17: fig27_17.pl# Fig. 27.17: fig27_17.pl# Program to search a database for usernames and # Program to search a database for usernames and
passwords.passwords.
use CGI qw( :standard );use CGI qw( :standard );
$dtd =$dtd ="-//W3C//DTD XHTML 1.0 Transitional//EN\""-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd";transitional.dtd";
$testUsername = param( "username" );$testUsername = param( "username" );$testPassword = param( "password" );$testPassword = param( "password" );
open( FILE, "password.txt" ) or open( FILE, "password.txt" ) or die( "The database could not be opened." );die( "The database could not be opened." );
17 Novembre 2005 Stefano Clemente 50
Esempio 9:Esempio 9:file esempio9.plfile esempio9.plwhile ( $line = <FILE> ) {while ( $line = <FILE> ) { chomp( $line );chomp( $line ); ( $username, $password ) = split( ",", $line );( $username, $password ) = split( ",", $line ); if ( $testUsername eq $username ) {if ( $testUsername eq $username ) { $userVerified = 1;$userVerified = 1;
if ( $testPassword eq $password ) {if ( $testPassword eq $password ) { $passwordVerified = 1;$passwordVerified = 1; last;last; }} } } }}
close( FILE );close( FILE );
print( header() );print( header() );print( start_html( { dtd => $dtd,print( start_html( { dtd => $dtd, title => "Password Analyzed" } ) );title => "Password Analyzed" } ) );
17 Novembre 2005 Stefano Clemente 51
Esempio 9:Esempio 9:file esempio9.plfile esempio9.plif ( $userVerified && $passwordVerified ) {if ( $userVerified && $passwordVerified ) { accessGranted();accessGranted();}}elsif ( $userVerified && !$passwordVerified ) {elsif ( $userVerified && !$passwordVerified ) { wrongPassword();wrongPassword();}}else {else { accessDenied();accessDenied();}}
print( end_html() );print( end_html() );
sub accessGrantedsub accessGranted{{ print( div( { style => "font-face: arial;print( div( { style => "font-face: arial; color: blue;color: blue; font-weight: bold" },font-weight: bold" }, "Permission has been granted,"Permission has been granted, $username.", br(), "Enjoy the site." ) );$username.", br(), "Enjoy the site." ) );}}
17 Novembre 2005 Stefano Clemente 52
Esempio 9:Esempio 9:file esempio9.plfile esempio9.plsub wrongPasswordsub wrongPassword{{ print( div( { style => "font-face: arial;print( div( { style => "font-face: arial; color: red;color: red; font-weight: bold" },font-weight: bold" }, "You entered an invalid password.", br(), "You entered an invalid password.", br(), "Access has been denied." ) );"Access has been denied." ) );}}
sub accessDeniedsub accessDenied{{ print( div( { style => "font-face: arial;print( div( { style => "font-face: arial; color: red; color: red; font-size: larger;font-size: larger; font-weight: bold" },font-weight: bold" }, "You have been denied access to this site." ) );"You have been denied access to this site." ) );}}
17 Novembre 2005 Stefano Clemente 53
CookieCookie• HTTP è stateless• I cookie permettono di mantenere le informazioni di
stato per un client che sta utilizzando il web server• I dati e i settaggi memorizzati nei cookie possono
essere conservati anche tra più sessioni• Microsoft Internet Explorer memorizza i cookie
sull’hard disk del client come piccoli file di testo (es. C:\Documents and Settings\clest\Impostazioni locali\Temporary Internet Files\)
• Ogni volta che il client fa una richiesta, i dati contenuti nel cookie vengono inviati al server
• Il server può rispondere con XHTML specifico in base alle informazioni contenute nel cookie
17 Novembre 2005 Stefano Clemente 54
Esempio 10Esempio 10• In questo esempio verrà mostrata una pagina
XHTML con una form attraverso la quale l’utente inserirà dei dati
• Quando l’utente cliccherà sul bottone “Write Cookie”, verrà eseguito uno script Perl che legge i dati inviati dall’utente, crea un cookie e restituisce all’utente una pagina nella quale conferma la creazione del cookie, visualizza i dati salvati e mostra un link per leggere il cookie
• Cliccando sul link viene eseguito uno script Perl che crea una pagina XHTML che visualizza i dati salvati nel cookie usando il colore preferito dall’utente
17 Novembre 2005 Stefano Clemente 55
Esempio 10Esempio 10
17 Novembre 2005 Stefano Clemente 56
Esempio 10Esempio 10
17 Novembre 2005 Stefano Clemente 57
Esempio 10Esempio 10
17 Novembre 2005 Stefano Clemente 58
17 Novembre 2005 Stefano Clemente 59
Esempio 10Esempio 10<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><!-- Fig. 27.21: fig27_21.html --><!-- Fig. 27.21: fig27_21.html --><html><html> <head><head> <title>Writing a cookie to the client computer</title><title>Writing a cookie to the client computer</title> </head></head> <body style = "font-face: arial"><body style = "font-face: arial"> <div style = "font-size: large;<div style = "font-size: large; font-weight: bold">font-weight: bold"> Click Write Cookie to save your cookie data.Click Write Cookie to save your cookie data. </div><br /> </div><br /> <form method = "post" action = "cgi-bin/esempio10_1.pl"<form method = "post" action = "cgi-bin/esempio10_1.pl" style = "font-weight: bold">style = "font-weight: bold"> Name:<br />Name:<br /> <input type = "text" name = "name" /><br /><input type = "text" name = "name" /><br /> Height:<br />Height:<br /> <input type = "text" name = "height" /><br /><input type = "text" name = "height" /><br /> Favorite Color:<br />Favorite Color:<br /> <input type = "text" name = "color" /><br /><input type = "text" name = "color" /><br /> <input type = "submit" value = "Write Cookie" /><input type = "submit" value = "Write Cookie" /> </form></form> </font></font> </body></body></html></html>
17 Novembre 2005 Stefano Clemente 60
Esempio 10Esempio 10#!c:\perl\bin\perl.exe#!c:\perl\bin\perl.exe# Fig. 27.22: fig27_22.pl# Fig. 27.22: fig27_22.pl# Program to write a cookie to a client’s machine.# Program to write a cookie to a client’s machine.
use CGI qw( :standard );use CGI qw( :standard );
$name = param( "name" );$name = param( "name" );$height = param( "height" );$height = param( "height" );$color = param( "color" );$color = param( "color" );
$expires = “Tuesday, 11-JUN-05 16:00:00 GMT";$expires = “Tuesday, 11-JUN-05 16:00:00 GMT";
print( "Set-Cookie: Name=$name; expires=$expires; path=\n" );print( "Set-Cookie: Name=$name; expires=$expires; path=\n" );print( "Set-Cookie: Height=$height; expires=$expires; path=\n" );print( "Set-Cookie: Height=$height; expires=$expires; path=\n" );print( "Set-Cookie: Color=$color; expires=$expires; path=\n" );print( "Set-Cookie: Color=$color; expires=$expires; path=\n" );
$dtd =$dtd ="-//W3C//DTD XHTML 1.0 Transitional//EN\""-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";
17 Novembre 2005 Stefano Clemente 61
Esempio 10Esempio 10print( header() );print( header() );print( start_html( { dtd => $dtd,print( start_html( { dtd => $dtd, title => "Cookie Saved" } ) );title => "Cookie Saved" } ) );
print <<End_Data;print <<End_Data;<div style = "font-face: arial; font-size: larger"><div style = "font-face: arial; font-size: larger"> The cookie has been set with the following data:The cookie has been set with the following data:</div><br /><br /></div><br /><br />
<span style = "color: blue"><span style = "color: blue">Name: <span style = "color: black">$name</span><br />Name: <span style = "color: black">$name</span><br />Height: <span style = "color: black">$height</span><br />Height: <span style = "color: black">$height</span><br />Favorite Color:</span>Favorite Color:</span>
<span style = "color: $color"> $color</span><br /><span style = "color: $color"> $color</span><br /><br />Click <a href = "esempio10_2.pl">here</a><br />Click <a href = "esempio10_2.pl">here</a>to read saved cookie.to read saved cookie.End_DataEnd_Data
print( end_html() );print( end_html() );
17 Novembre 2005 Stefano Clemente 62
Esempio 10Esempio 10#!c:\perl\bin\perl.exe#!c:\perl\bin\perl.exe# Fig. 27.25: fig27_25.pl# Fig. 27.25: fig27_25.pl# Program to read cookies from the client's computer.# Program to read cookies from the client's computer.
use CGI qw( :standard );use CGI qw( :standard );
$dtd =$dtd ="-//W3C//DTD XHTML 1.0 Transitional//EN\""-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";
print( header() );print( header() );print( start_html( { dtd => $dtd,print( start_html( { dtd => $dtd, title => "Read Cookies" } ) );title => "Read Cookies" } ) );
print( div( { style => "font-face: arial;print( div( { style => "font-face: arial; font-size: larger;font-size: larger; font-weight: bold" },font-weight: bold" }, "The following data is saved in a"The following data is saved in a cookie on your computer." ), br() );cookie on your computer." ), br() );
print( "<table style = \"background-color: #aaaaaa\"print( "<table style = \"background-color: #aaaaaa\" border = 5 cellpadding = 10border = 5 cellpadding = 10 cellspacing = 0>" );cellspacing = 0>" );
17 Novembre 2005 Stefano Clemente 63
Esempio 10Esempio 10
%cookies = readCookies(); %cookies = readCookies(); $color = $cookies{ Color };$color = $cookies{ Color };
foreach $cookieName ( "Name", "Height", "Color" ) {foreach $cookieName ( "Name", "Height", "Color" ) { print( Tr( td( { style => "background-color: $color" },print( Tr( td( { style => "background-color: $color" }, $cookieName ),$cookieName ), td( $cookies{ $cookieName } ) ) );td( $cookies{ $cookieName } ) ) );}}
print( "<table>" );print( "<table>" );print( end_html() );print( end_html() );
sub readCookiessub readCookies{{ @cookieArray = split( "; ", $ENV{ 'HTTP_COOKIE' } );@cookieArray = split( "; ", $ENV{ 'HTTP_COOKIE' } );
foreach ( @cookieArray ) {foreach ( @cookieArray ) { ( $cookieName, $cookieValue ) = split( "=", $_ );( $cookieName, $cookieValue ) = split( "=", $_ ); $cookieHash{ $cookieName } = $cookieValue;$cookieHash{ $cookieName } = $cookieValue; } } return %cookieHash; return %cookieHash; }}