Download presentation
Presentation is loading. Please wait.
Published byDamon Rudolph Norris Modified over 9 years ago
1
Ch27 - Common Gateway Interface (CGI) and Perl
Outline Server-side processing Common Gateway Interface (CGI) Other server-side programming technologies (Active Server Pages (ASP)) Java Servlets and Java Server Pages (JSP) PHP Hypertext Processor Python Perl Simple Perl examples Handling HTTP Requests – GET and POST CGI Environment Variables Viewing CGI Environment Variables in Perl Using Perl DBI to Connect to a Database (Hel sida välj 75%, Stlk 9 OK) Dynamic creation of Web pages – the key to interactivity and performing transactions on the web The web page is based on data submitted by the user E.g. results page from search engines and order confirmation pages at on-line stores The web page is derived from data that changes frequently E.g., a weather report or a news headlines page The web page uses information from databases or other server-side resources E.g. an e-commerce site could build a Web page that lists the current price and availability of each item that is for sale Going dynamic – an overview of technologies for dynamic web programming På kursen lär vi oss inte Perl utan kommer bara använda en bråkdel för att illustrera principerna för CGI Not covered Web Server Extensions (using ISAPI, NSAPI) (String Processing and Regular Expressions) (Server-Side Includes) (Verifying a Username and Password) (Form Processing and Business Logic) (Cookies and Perl) (Operator Precedence Chart) (Internet and World Wide Web Resources)
2
Web Programming Technologies
Content Authoring: HTML Protocols: HTTP Client Side Processing Server Side Processing Client-Side Processing vs Server-Side Processing - Putting it All Together Många tekniker som vill bli standarder Börjar rensas upp och de-facto standarder skapas Har växt enormt under 1990-talet 1990- statiska webbsidor, (Web servers were originally designed to serve static HTML pages) enklare dynamiska webbsidor - Utveckling främst I Perl, asvancerade dynamiska webbsidor - Integration med andra program, webbapplikationer - E-handel, ASP, avancerade webbapplikationer - PHP Webbapplikation Relativt nytt begrepp för en avancerad dynamisk webbsida Webbapplikation – grundpelare (CGI och formulär, Java) Lägeslös miljö ( sessioner, cookies) Lagring av data (Databas) A program is a sequence of written instructions which is compiled and executed by a computer A script is a program which runs directly without pre-compilation Web pages can be thought of as scripts which are interpreted by web browsers Creating HTML pages and organizing them into web sites (HTML, DHTML,XML) Where should my functionality reside? Server-side or client-side? Server-side technologies (CGI, mod_perl, s/s JavaScript, PHP, JSP, ASP) Scripting on the server side for content delivery (Perl, ASP) Client-side technologies Scripting on the client side for interactive content (Javascript). JavaScript most popular client-side script Programming on the client side and server side (Java) - ? Client-side scripting Validates user input, Accesses the browser, Enhances Web pages with ActiveX® controls, applets, etc., Manipulates browser documents Client-side validation Reduces number of requests that need to be passed to server Client-side scripting limitations Browser dependency, Viewable to users through View Source command Client-server communication relies on network protocols. HTTP handles transfer of web pages. Server processing can be handled be CGI-protocol HTTP Request Web Server Web Browser HTML Pages CLIENT SERVER Client Scripts: JavaScript Client Programs: Java Applets HTTP Response HTML Page Server Scripts: Perl, ASP, PHP, JSP Protocols: CGI Server Programs: Java Servlets
3
What is server-side processing?
The use of programs on the server-side to process client input and produce client output Generates custom responses for clients Has access to server-side software that extend server functionality Provides programmers greater flexibility Contains greater programmatic capabilities than client-side equivalents There are several technologies that can be used to create server-side scripts Common Gateway Interface (CGI) Microsoft Active Server Pages (ASP) – HTML embedding VBScript PHP Hypertext Processor (PHP) Java Servlets and Java Server Pages (JSP) Common script languages Perl, VBScript, Python, Java Exekvering på server istället för på klient. Server-side processing of HTML data such as form input • Kan göra exekveringen säkrare (ur både klient och serverhänseende). Kräver inget speciellt av klienten (plug-ins etc) Server-side scripts Ger tillgång till kataloger, filer och andra program på servern Has access to server-side software that extend server functionality What needs to be on the server side? Any functionality that uses the web to change the status of a database or file system on the server side, e.g., online shops back-ends, online booking systems Any functionality that requires access to resources not available on the client (e.g., search engines, web-cam, etc.) Any functionality designed to safeguard the security of the server Anything else that can’t or shouldn’t be done on the client What shouldn’t be on the server side? Functionality that can be implemented on the client side without compromising server security. Will usually make your site appear faster! Applications that are to handle sensitive data on the client that are not to be shared with the server. Acceptance issues! Webbutveckling bedrivs vanligen i interpreterande språk ex. Perl, ASP och PHP Enklare att hantera i moderna webbspråk, exempelvis PHP och ASP. Hastigheten är inte så betydelsefull Other forms of server side processing Web Server Extensions (using ISAPI, NSAPI) Ny? LT 5-6 Web Server Extensions SSI
4
Common Gateway Interface (CGI)
A standard for how a web server interact and transfer information to an application program (called CGI script) Application is responsible for generating some dynamic content Application can call database Extend servers beyond simple HTML file serving CGI = Common Gateway Interface. Common - supported by almost all web servers, can be used by many platforms and programming languages such as Perl, C, C++, VBScript, etc Gateway - pathway between server and application programs Interface - provides a well-defined way to call up its features CGI is Not… a programming language AL –11Se ävenLT 5-6 Example uses for CGI Forms On-the-fly Pages Database Interaction Logging/Counters Animation CGI is… a gateway which allows programs or scripts written in either languages to run over the internet Gateway: potential access it offers to other systems ( a standard environment) Gateway program (CGI) on server gets data from client and passes it to a CGI application Practically the oldest widespread server-side technology for dynamic generation of content CGI = protocol, JAVA = programming language Ett CGI-script kan skrivas i många olika språk, tex Perl, C/C++, TCL, C Shell, Visual Basic, Python, JavaScript (has client-side and server-side parts, part of Netscape servers ), (Java, Smalltalk) och AppleScript Which one you prefer depends on your background C and C++ must be compiled code is not platform dependent Because CGI-applications tend to be fairly trivial large languages such as C++ are often overkill
5
CGI at work Web Server Client (Browser) CGI script
Read explicit data (form data) and implicit data (request headers) sent by client Generate the results and send explicit data (HTML) and implicit data (status code and response headers) back to client Client (Browser) Web Server 2. Sets data Environment variables 1. Sends HTTP-request HTML- Form Se även Calgary eller LT 5-12 CGI Operation: A Closer Look Many CGI scripts access databases – but we focus on the CGI script communication with server Connection established Server receives client request for script via GET or POST (Parameters can be passed to the program.) Request is sent by clicking buttons or links Instead of path to a file, the resource specifies a program to be executed. Server starts script as an external process and passes any client data via environment variables A web server usually holds many CGI scripts Script can access environment variables and outputs document Script process and makes decisions on data Output is piped to server, which may parse it and transmits it back to client Connection closed (HTTP is stateless) CGI-programs generally executes then quits and is restarted each time is it needed. CGI Web Server Interaction User invokes a script Request and Relay data CGI script wakes up Carry out request Return request to server Send results back to user User sees and/or hears results 4. Reads data Internet CGI script 3. Calls script 6. Sends HTTP-response (HTML Page) 5. Returns output Database
6
CGI Advantages and Disadvantages
Web server and language independence (such as C/C++ or Perl) Wide acceptance. De facto standard (One of the earliest server-side options). Many free example CGI scripts Simple to use Disadvantages Each request starts up a new process of the CGI script Stateless protocol. Can’t retain information between requests Communication to application must go through the web server Advantages (se AL 15): Vast majority of Web servers run Unix. Majority of servers does not support ASP at the moment. Web masters want free software with wide range of technical support in the Internet. Nackdelar Långsamt jämfört med ASP och PHP (resource intensive) Går ej att kompinera HTML och scriptkod eftersom scriptkoden måste ligga I en separat fil Helt enkel föråldrat (Karlstad) Why is state hard for Perl/CGI? HTTP is stateless. Each CGI invocation starts a new process. No association between HTTP connections. When clientsat an on-line store add an item to their shopping chart, how does the server know what’s already in the chart? When clients decide to proceed to checkout, how can the server determine which preciously created shopping cart is theirs? Solution cookies: Introduced by Netscape Not actually part of official HTTP specification. Basic idea: “Set-cookie” header in HTTP response defines a cookie providing: value, name, domain, path Client sends cookie value and name in request header when domain and path match. Good when state must survive the current session. What about security? Prone to security problems Client attacking the program to gain unauthorized access Innocent script = dangerous to the integrity of a system
7
Java Servlets and Java Server Pages (JSP)
Java servlet is like an applet that runs inside a web server, extending the servers functionality A web server must provide an API so Java servlets can be written JSP is part of the servlet API that allows Java to be embedded inside HTML Same concept as ASP Advantages of servlets and JSP When written in Java, servlets and JSP are plattform independent Wide support: from Netscape, Sun, Apache, Oracle, IBM Servlets and JSPs are compiled, loaded once at server startup, and service Web requests using separate lightweight threads Java Servlets and JSP are part of Java 2 Enterprise Edition (J2EE), a collection of enterprise APIs Se Deitel ch 30 och 31, även AL-24, LT 5-9 Servlets Javas motsvarighet till CGI fast anpassat till Java The servlet API is defined by Sun Microsystems JSP Similar to ASP or PHP in terms of ability to separate static and dynamic content In-process Easier to run offline (container) Platform-independent Java is becoming very popular as a server-side language Servlets/JSP provide high performance Java is portable and supported by many servers Biggest difference between CGI applications and servlets is that a servlet is persistent. each user request is invoked as a thread once it is started, it stays in memory and can fulfill multiple requests makes them faster because there's no wasted time in setting up and tearing down the process
8
PHP Hypertext Preprocessor
PHP is a script language in Web programming, which is platform independent but used primarily on Linux Web servers Initials come originally from the earliest version of the program, which was called "Personal Home Page Tools“. Now acronym for PHP Hypertext Preprocessor PHP is free and offered under an open source license. The latest version is PHP4. Interpreter is freely available. An alternative and works similar to ASP technology LAMP - Linux, Apache, MySQL and PHP. Four parts to build fast, robust Web applications. PHP is a project of the Apache Software Foundation. As with ASP, the PHP script is embedded within a Web page along with its HTML. Before the page is sent to a user that has requested it, the Web server calls PHP to interpret and perform the operations called for in the PHP script. An HTML page that includes a PHP script is typically given a file name suffix of ".php" ".php3," or ".phtml". Like ASP, PHP can be thought of as "dynamic HTML pages," since content will vary based on the results of interpreting the script. Se Deitel ch 29, Står för PHP Hypertext Preprocessor Ingår i de-facto standarden LAMP (Linux, Apache MySQL, PHP) Very mature and extensive language Similar to Perl. Nyare scriptspråk som från början var ett supplement till Perl Works similar to ASP, but with (to my knowlegde) a larger range of functions Via CGI or in-process server Enables separation of static and dynamic content
9
Perl Perl (Practical Extraction Report Language) is an interpreted language (not compiled, like Java) which is ideally suited for CGI programming. written by Larry Wall in Combines syntax from several UNIX utilities and languages. has also been adapted to non-UNIX platforms. ActivePerl, the standard Perl implementation for Windows is freely available Perl is a text processing language that provides comprehensive string handling functions designed to handle a variety of system administrator functions It is widely used to write Web server programs for such tasks as automatically updating user accounts and newsgroup postings processing removal requests synchronizing databases and generating reports Vad är Perl? Perl är ett interpreterande programspråk inspirerat av C och cshell (Unix-shell) Används som scriptspråk, precis som VBscript. Finns på många plattformar. Perl comes as part of the Unix system. Larry Wall now works for O’Reilly Kör på Win genom att ladda hem (även bok CD) och installera Perl interpretator, ex ActivePerl Många funktioner för bla mönstermatchning Perl approach: TIMTOWTDI There Is More Than One Way To Do It It has its roots in Unix system administration (similar to Unix, SED, AWK, and Shell Script) and offers several features like regular expressions and file manipulation which make it extremely powerful. It’s arguably the most popular CGI scripting language Många specialfunktioner för att hitta och byta ut tecken/ord – regular expression The ActiveState Tool Corporation is the company which develops and maintains ActivePerl, the standard binary Perl distribution for Win32. Is included in book CD It's learning curve has been described as long and shallow. It is very easy to pick up at first, (går snabbt att konstruera kraftfulla program, especially if you are at all familiar with Unix. However, it does take quite a bit of time to become familiar with all the little nuances of the language. For most CGI work, however, these little nuances aren't really necessary. Varför Perl? Relativt enkelt att använda Går att provköra som vanligt program från terminal Finns på flera plattformar Dock inbjuder inte Perl till välstrukturerade (speciellt stora) program Troligaste användningsområde: att ta emot data från formulär. Perl is now an OO language too
10
Python An interpreted, object-oriented programming language developed by Guido van Rossum. Can be used to write: CGI-scripts ASP-scripts Large-scale Internet search engines Small administration scripts GUI applications Python is very portable since Python interpreters are available for most operating system platforms. Although Python is copyrighted, the source code is freely available, and unlike GNU software, it can be commercially re-sold. Se Deitel ch 28 The name comes from one of van Rossum's favorite television shows, Monty Python's (Pajton) Flying Circus. Ett alternativ till Perl Uppbyggt som ett eget språk från grunden till skillnad mot Perl
11
Perl - Simple Example #!/usr/bin/perl $name=“Foo”;
$friends=1; #I only have one friend #$friends=2; #actually, I have 2 friends #$friends=“many;” #I have too many friends if ($friends == 1) { print “$name, you are my best friend.”; } The “shebang” construct (#!) indicates the path to the Perl interpreter on Unix systems. Välj ett scriptexempel För att testa programmet, skriv perl mitt_program.pl Perl tolkar koden och skriver ut den i operativsystemet Observera att det bara fungerar om du installerat Perl på datorn. Sparas med ändelserna ”.pl” eller ”.cgi” (#!) Magisk shebang… (magsik rad) The path will vary from system to system. På Windows är sökvägen utan betydelse. Där associerar man ändelsen med kommandotolken för Perl. Raden tas ändå med för enhetlighets skull. - ActiveState install configures the System Registry Kommentarer med # Perl is not a strongly typed language you don’t have to declare the type of variable when you declare it Variabler behöver inte deklareras, aktiveras vid första användandet. CGI/Perl Hello World Perl script that returns an HTML document with the text “Hello World” Remember to make the script executable, and end its name in “.cgi” #!/usr/local/bin/perl print “Content-type: text/html\n”; print “\n”; print “<html>\n”; print “<body>\n”; print “<h1>Hello World!</h1>\n”; print “</body>\n”; print “</html>\n”; Function print writes the string to the screen.
12
Data Types in Perl Ett tecken symboliserar vilken typ av variabel det är eller %) Ingen risk att blanda variabler och nyckelord Indexerade variabler börjar Hash Kallas Tabell på svenska …Hash consists of a series of pairs of items with each pair comprising of a key and an associated value. Scalar is a singular data type. Array is a plural data type Much of the power of Perl lies in hashes. Komplettera ev med example #2 (se Calgary) Ev more advanced exempel med variabler [mitt_program.pl] # Att jobba med variabler Print ”Använda en variabel i en sträng: $var”; $num = 5; $test =$num + 5; Print ”Innehållet i test-variabeln är 10: $test”; @array = (”Henrik”, ”Kalle”, ”Pelle”) OBS1 ej { som i Java # Skriver ut Pelle #Skriver ut hela array
13
Client-Server Interaction
HTTP is a request-response protocol. Client sends request, server responds. HTTP Request (Client is sending request message to Server ): When a client sends a request, it consists of three parts: Request line: (e.g. POST /im269/w7.html HTTP/1/1) HTTP method type (GET or POST) Resource name (URL) Protocol/version Header: contains browser information (optional) Message body: in POST method request information is stored here (optional) HTTP Response (Server is sending response message to Client): The response sent by the server also consists of three parts: Response line: (server protocol and status code) Header: specifies the type of output (content-type such as text/html, location such as or no response such as 204 No Response) Message body: (the actual data, such as sending back a Web page or a file to the user) It shouldn’t take a rocket scientist to realize that need to understand HTTP to be effective with CGI Basic HTTP Exchange 1.Connection established. 2.Client sends a request. 2. Server sends a response. 3.Connection closed. HTTP Request contains Request line (includes resource), Request header (Zero or more lines), Request body (ev. FORM data) HTTP is stateless The HTTP reply has 3 parts: Status-Line Zero or more header lines (Content-length and type) Tells browser what to do with the information Content-type (s.k. MIME-huvud) text/html for html text/plain for plain text Location Status Message body (HTML-page) HTTP/ OK < Status line Date: Fri, 11 Aug :17:44 GMT Server: Apach/1.3.9 (Unix) (Red Hat/Linux) Last-Modified: Fri, 11 Aug :17:27 GMT Etag: “2be71r90-2d ” Accept-Ranges: bytes Content-Length: 45 Connection: close Content-type: text/html < header line <html> Message body (HTML-page) <body> This is a test </body> </html>
14
HTTP Response from a CGI script
A CGI script that produces a HTTP response. CGI responds to the server via standard output Example CGI scripts: 1. Return content to user print (“Content-type: text/html”); print (““); print (“<HEAD>”); print (“<TITLE>CGI script output</TITLE>”); print (“</HEAD>”); print (“<BODY>”); print (“<H1>Output from a CGI script</H1>”); ... print (“</BODY>”); 2. Return a location to user Location: 3. Return no response Status: 204 No Response The web server process can automatically insert information into the header of the response. Unfortunaltly CGI-scripts cannot use this mechanism Reply Status Line Format: VERSION CODE REASON Status Code 3 digits 1xx (Informational) 2xx (Success) 3xx (Redirection) 4xx (Client Error) 5xx (Server Error) Reason: Human-readable phrase 404 (Not Found) No such page
15
GET and POST request methods
Most common ways to send data from client to server: GET request Retrieves appropriate resource from Web server Form contents are appended as a querystring to the URL Limits query to 1024 characters stored in request line Browsers cache (save on disk) HTML pages Allows for quick reloading Cache responses to get request Do not cache responses to post request POST request Updates contents of Web server (posting new messages to forum) The data is sent as part the message body of the request. Not part of URL and cannot be seen by user Has no limit for length of query Posts data to server-side form handler Note that the client don’t always need to send data to server to generate a response Also called HTTP Request types Other request methods: PUT - Take my message body and store it as the identified resource DELETE - Delete the resource Hur ser ett CGI-program ut? Ett program som är kopplat via CGI till en websida hanterar data som skickats via GET eller POST från den aktuella sidan Två sätt att skicka data: GET och POST GET Begränsat hur mycket som kan skickas (Problem med cache?) POST sends all the information from the form separately from the URL. Skickar formulärets data direkt in I webbapplikationen som en dataström med hjälp av <STDIN> GET vs. POST GET = slightly more limited, but easier to deal with. Data may get lost or truncated POST = substantial text entry fields POST is usually preffered because the amount of information that can be sent is not limited by the size of a URL. The most common method is POST … but what is the difference? The answer lies within the way information is passed... Vilken ska användas? GET ska användas för att fram data, till exempel söka efter ett specifikt namn i ett adressregister POST ska används för att modifiera data, till exempel lägga till en post i ett adressregister POST ska även användas när informationen bör döljas för användaren GET Requests can be stored as bookmarks
16
Ways to call Server-Side Scripts
The URL specifies a script called “program” to be executed Instead of an HTML file. Sending data directly to a script (using the GET-method) Invoking can also be done through a link. A hypertext reference can refer to: An exutable script <a href= An exutable script with arguments (using the GET-method) <a href= An Active Server Page <a href= It is much easier provide user input from an HTML form: <FORM ACTION=“ Input elements go here </FORM> LT 5-5 Flyttas ev till FORMS, GET o POST (se Calgary) All examples scripts could also be invoked with the POST-method Other Methods than using forms with GET or POST to access CGI Can be done through URL <A HREF=“ Can be done through link Invoking a CGI program in the cgi-bin directory The directory that the CGI scripts sit in cannot be specified by you alone - you need the help of whoever runs your HTTP server Most of Google is implemented in C or C++ for efficiency and can run in either Solaris or Linux Data of request is sent as name/value pairs Komplettera ev. med JSP och PHP ev. Phyton webserver extensions An exutable program that extends the server <a href= A hypertext reference can refer to (A local file <a href=file:///docs/system.html> A remote file <a href= Requesting documents Must know machine name on which Web server resides Through local Web servers or remote Web servers Through domain name or Internet Protocol (IP) address Local Web server Resides on users’ machines Requests documents in two ways Machine name localhost Host name that references local machine
17
Encoding User Input from Forms
HTML-forms are used to provide input to CGI scripts. The <FORM> tag requires two arguments: ACTION the URL representing the script which is to receive the form information METHOD either GET or POST represents the way in which the information will get passed to the script Using METHOD=“GET”. FORM elements’ names are paired with their contents ie. <input type=“text” size=“9” maxlength=“9” name=“zip”> User inputs 10003, then zip=10003 All such name/value pairs are joined together with an ‘&’ The entire input data string is URL encoded ie. name=Jane+Doe&address=35+W%27+4th+St%27&zip=10003 On the server end the data is placed in the environment variable QUERY_STRING Kommunikationen mellan webbbläsare och webbserver sker med hjälp av formulär som användaren fyller i och sedan skickar till en webbapplikation för bearbetning Forms are one of the most popular, interactive features on the web. They enable users to interact with the text and graphics that are displayed on your machine. when the user submits the form, the information is returned to a server-side script. A script is a short program that is written specifically for each form. Vad är Forms? Ett sätt att i HTML skapa sidor som använder inmatning av information från användaren och koppla hantering till program på en server Vi kan hantera knappar, textfält, listor, mm Information in the form is forwarded to a script that can process the data Varför Forms? HTML är ett språk för att beskriva innehåll på sidor och inte hur det skall hanteras FORMS är ett sätt att beskriva olika grafiska objekt och koppla hanteringen av användarens inmatning via CGI till program skrivna i konventionella programspråk GET Lägger formulärets data till slutet av URL:en i kodat format Parameter form: name = value, (Spaces replaced with +) Name/value pairs separated by & (ampersand) Space replaced by a ‘+’ sign Se Calgary eller Cal State Bild METHOD selects variations in the sending protocol. Tells the form how to send its information back to the script. <input type=“text”… type attribute determines input type: A single-line text field The browser specially encodes the form’s data before passing it to the server. The standard encoding format is “application/x-www-form-url-encoded” Spaces are converted to + sign, non-alphanumerics to %ASCII_hex_value, and line breaks into %0D%0A Using METHOD=“POST”; we have Basically the same as METHOD=“GET” Parameters are encoded as with GET for consistency. string -> STDIN length of string -> CONTENT_LENGTH
18
Three ways to pass data to CGI scripts
Environment variables (When the GET method is used in an HTML form) Data is encoded as part of the URL Portions of the URL are assigned to the environment variables QUERY_STRING, PATH_INFO, and SCRIPT_NAME: QUERY_STRING is assigned input_data PATH_INFO is assigned extrapath/afile SCRIPT_NAME is assigned cgi-bin/scriptname Standard input (When the POST method is used) The data is given in the message body of the HTTP request Web server forwards message body to the script via the standard input stream Command–line arguments For example, to pass arg1 and arg2 to a script: <a href= LT 5-14 AL-14 method = ”post” appends form data to the browser request, which contains the protocol (HTTP) and the requsted resource’s URL Retrieving parameter values. Determine whether parameters are in QUERY_STRING or on STDIN Use “split” to break parameter/value pairs. Use “split” to break parameters from value Replace “+” with a space. Replace “%##” with characters (use “pack”)
19
CGI Environment Variables
CGI environment variables are used to pass information about the context of execution. These variables are global, and accessible to all running programs Programs -> programs Variables are text strings (name and value pairs) Can be classified into two major categories Nonrequest specific Request specific Nonrequest-specific environment variables These variables are set for all requests SERVER_SOFTWARE The name and version of the information server software answering the request SERVER_NAME The server's hostname, DNS alias, or IP address GATEWAY_INTERFACE The revision of the CGI specification to which this server complies. LT , se även Calgary (komplettera med kolumn med exempel på värden) Knowing the client’s execution environment allows system administrators to provide client-specific information to generate clinet specific Web pages. Vidare kan programmet hantera andra omgivningsvariabler för att tex kontrollera om anropande websida "körs" från en bläddrare på en gilltig plattform (vi kan tex se till att endast bläddrare startade på någon av NADAs datorer kan köra CGI-programmet) Can be accessed by other running programs Function param is part of Perl CGI module and retrieves values from a form field’s value (Mastering boken delar upp variablerna I 3 grupper Server (Non request) Request Client)
20
Request-specific environment variables (1)
These variables are set depending on the request being fulfilled by the CGI script: SERVER_PROTOCOL The name and revision of the information protocol this request came in with. Format: protocol/revision SERVER_PORT The port number to which the request was sent. REQUEST_METHOD The method with which the request was made. For HTTP, this is "GET", "POST", etc. PATH_INFO The extra path information, as given by the client. E.g. PATH_TRANSLATED the PATH_INFO path translated into an absolute document path on the local system, which takes the path and does any virtual-to-physical mapping to it. SCRIPT_NAME A the path and the name of the script being executed, as referenced in the URL. QUERY_STRING The information which follows the ? that referenced this script. Important request variable: REQUEST_METHOD ’OBS! PATH_INFO Definitionen ovan stämmer ej med Bild 17 PATH_INFO The extra path information, as given by the client. In other words, scripts can be accessed by their virtual pathname, followed by extra information at the end of this path. The extra information is sent as PATH_INFO. This information should be decoded by the server if it comes from a URL before it is passed to the CGI script. PATH_TRANSLATED The server provides a translated version of PATH_INFO, which takes the path and does any virtual-to-physical mapping to it. QUERY_STRING has encoded parameters if using GET QUERY_STRING This is the query information. It should not be decoded in any fashion. This variable should always be set when there is query information, regardless of command line decoding.
21
Request-specific environment variables (2)
REMOTE_HOST The Internet domain name making the request. REMOTE_ADDR The IP address of the remote host making the request. AUTH_TYPE If the server supports user authentication, and the script is protects, this is the protocol-specific authentication method used to validate the user. REMOTE_USER the username that server and script have authenticated. REMOTE_IDENT the remote user name retrieved by the server using inetd identification (RFC 931), CONTENT_TYPE For queries which have attached information, such as POST-method, this is the MIME-content type of the data. CONTENT_LENGTH The length of the content as given by the client. Important request variable: CONTENT_LENGTH hint: Use the environment variable CONTENT_LENGTH to determine how much data to read REMOTE_HOST If the server does not have this information, it should set REMOTE_ADDR and leave this unset. AUTH_TYPE If the server supports user authentication, and the script is protects, this is the protocol-specific authentication method used to validate the user. REMOTE_USER If the server supports user authentication, and the script is protected, this is the username they have authenticated as. REMOTE_IDENT If the HTTP server supports RFC 931 identification, then this variable will be set to the remote user name retrieved from the server. Usage of this variable should be limited to logging only. Also, every item in an HTTP request header is stored in an environment variable for example: HTTP_USER_AGENT Se core servlets Accept Accept-Encoding Authorization Connection Referer Host If-modified-since Se NorthC headers
22
Perl script to display CGI environment variables
#!/usr/bin/perl 2 # Fig : fig27_11.pl 3 # Program to display CGI environment variables. 4 5 use CGI qw( :standard ); 6 7 $dtd = 8 "-//W3C//DTD XHTML 1.0 Transitional//EN\" \" 10 11 print( header() ); 12 13 print( start_html( { dtd => $dtd, title => "Environment Variables..." } ) ); 15 The use statement instructs Perl programs to include the contents (e.g., functions) of predefined packages called modules. The import tag :standard imports a predefined set of standard functions. Fig27_11.pl Calgary har ett enklare exempel (Dela upp ex på två sidor) el. Byt mot ex att ta emot data fr formulär ) qw places quotes around a list of words 3 # Program to display CGI environment variables. CGI.pm is a library of routines that simplify the creation and processing of Web forms. - handle the extraction of data - includes shortcuts which can be used to create common HTML tags - Attribute to tags have their standard HTML names and are preceded by a dash. If you want to create non-form pages these shortcuts are actually more complex than writing your own print statements. CGI.pm operate as classes and allow the programmer to access their routines through method calls Methods are accessed by using an arrow Module has a name (starting with uppercase) Examples: MyModule, CGI Stored in a file with same name with .pm ending Examples: MyModule.pm, CGI.pm DTD (or a schema) shows what HTML-version is used. Some parsers can read the DTD/schema and check that the document follows the structure that DTD/schema defines to The DTD shows the DTD in use by the document: XHTML Transitional 11 print( header() ); Instruct the Perl script to print a valid HTTP header, using function header from the CGI library. Prints Content-type::text.html The start_html function prints the document type definition for this document, as well as several opening XHTML tags (<html>, <head>, <title>, etc., up to the opening <body> tag).
23
Perl script to display CGI environment variables, cont.
16 print( "<table style = \"border: 0; padding: 2; font-weight: bold\">" ); 18 19 print( Tr( th( "Variable Name" ), th( "Value" ) ) ); 21 22 print( Tr( td( hr() ), td( hr() ) ) ); 23 24 foreach $variable ( sort( keys( %ENV ) ) ) { 25 print( Tr( td( { style => "background-color: #11bbff" }, $variable ), td( { style => "font-size: 12pt" }, $ENV{ $variable } ) ) ); 30 print( Tr( td( hr() ), td( hr() ) ) ); 32 } 33 34 print( "</table>" ); 35 print( end_html() ); The %ENV hash is a built-in table in Perl that contains the names and values of all the environment variables. Function keys returns an unordered array containing all the keys in the %ENV hash. sort orders the array of keys alphabetically. The foreach loop iterates sequentially through the array returned by sort, repeatedly assigning the current key’s value to scalar $variable. 16 Specifies the value for the attribute style. The name of the attribute is specified on the left, followed by its value on the right. 19 print( Tr( th( "Variable Name" ), th( "Value" ) ) ); Functions Tr and th place their arguments between table row and table header tags, respectively 24 foreach $variable ( sort( keys( %ENV ) ) ) foreach is used to set the value on each loop foreach. Foreach ger en kompaktare kod %ENV is a table with keys and value column (Rita hashtabell med key och value %ENV is a special variable containing the current environment Fr Henriks foreach $key (sort keys %ENV) { print "<strong>$key</strong>"; print "$ENV{$key}"; print "<br>" } print( Tr( td( { style => "background-color: #11bbff" }, $variable ), td( { style => "font-size: 12pt" }, $ENV{ $variable } ) ) ); Function Tr is called again with the hr and td functions, in order to print a row of horizontal rules within <td> tags. Hash values are accessed using the syntax $hashName{ keyName }. In this example, each key in hash %ENV is the name of an environment variable name (e.g., HTTP_HOST). Function end_html returns the closing tags for the page (</body> and </html>).
24
Program Output Prev notes
Specifies the value for the attribute style. The name of the attribute is specified on the left, followed by its value on the right.
25
Introduction to DBI Databases part of distributed applications Driver
Divides work across multiple computers Retrieves result set and displays results Driver Helps programs access databases Each database can have different syntax Each database requires its own driver Interface Provides uniform access to all database systems Database interface Programmatic library for accessing relational database Using the web to conduct business depends on storing and retrieving and manipulating data from customers. If you’re handling complex data a relational database is the best solution. Lägg ev in LT 6-13 o 6-14 showing a three tier model If the DBMS that you’re using changes (Oracle) then you simply tell the Perl DBI to use a different driver A Perl driver is available to talk to ODBC the consistent DBMS interface from Microsoft
26
Perl Database Interface
Perl DBI Enables users to access relational databases from Perl programs Database independent Most widely used interface in Perl Uses handles (Fig ) Object-oriented interfaces Driver handles, database handles, statement handles Each connection into the database is identified by a handle whose methods are called by Perl scripts Perl DBI is an API which provides a library of functions, variables and conventions. The functionality comes from a driver module which must be specifically developed for the database being used Till bild:
27
MySQL Pronounced “My Ess Que Ell” Robust and scalable RDBMS
Multiuser, multithreaded server Performs multiple commands concurrently Uses SQL to interact with data Supports various programming languages C, C++, Java, Python, Perl, PHP, etc Supports various operating systems Windows, Linux and Unix Access multiple databases with single query There are many types of relational database available – some of them even freely available on the Internet. Fig: Perl script using DBI -> MySQL Driver -> MySQL Engine MySQL Perl DBI lacks commit and drawback
28
The Perl DBI module and the MySQL driver, DBD::mysql are required.
Fig27_19.pl 1 #!/usr/bin/perl 2 # Fig : fig27_19.pl 3 # CGI program that generates a list of authors. 4 5 use CGI qw( :standard ); 6 use DBI; 7 use DBD::mysql; 8 9 $dtd = 10 "-//W3C//DTD XHTML 1.0 Transitional//EN\" \" 12 13 print( header() ); 14 15 print( start_html( { dtd => $dtd, title => "Authors" } ) ); 17 18 # connect to "books" database, no password needed 19 $databaseHandle = DBI->connect( "DBI:mysql:books", "root", "", { RaiseError => 1 } ); 21 22 # retrieve the names and IDs of all authors 23 $query = "SELECT FirstName, LastName, AuthorID FROM Authors ORDER BY LastName"; 25 26 # prepare the query for execution, then execute it 27 # a prepared query can be executed multiple times 28 $statementHandle = $databaseHandle->prepare( $query ); 29 $statementHandle->execute(); 30 31 print( h2( "Choose an author:" ) ); 32 33 print( start_form( { action => 'fig27_20.pl' } ) ); 34 35 print( "<select name = \"author\">\n" ); The Perl DBI module and the MySQL driver, DBD::mysql are required. Connect to the database by calling DBI method connect. If the connection succeeds, function connect returns a database handle that is assigned to $databaseHandle. # CGI program that generates a list of authors. Byt mot ex att ta emot data fr formulär se XML How to Program The databasehandle will be used for all database operations 19 $databaseHandle = DBI->connect( "DBI:mysql:books", "root", "", { RaiseError => 1 } ); Argument ({ RaiseError => 1 }) is used for error checking. If an error occurs when trying to connect to the database, function die is called and passed an error message.(Application can then use to fail gracefully) Connect ($datasource $username, $password) The datasource is a colon-separated set of values identifying the driver, database (and host) Driver is called through DBI::”driver-name: The handle is an instance of DBI Note that SQL-statements should not generally be terminated by a semicolon What is the contents of the table. The database handle is used to prepare the query (using the method prepare). This method prepares the database driver for a statement, which can be executed multiple times. Method execute executes the query.
29
Each value is printed as a list option.
Fig27_19.pl 36 37 # drop-down list contains the author and ID number 38 # fetchrow_array returns a single row from the result 39 while = $statementHandle->fetchrow_array() ) { print( "<option>" ); print( "$row[ 2 ]. $row[ 1 ], $row[ 0 ]" ); print( "</option>" ); 43 } 44 45 print( "</select>\n" ); 46 47 print( submit( { value => 'Get Info' } ) ); 48 print( end_form(), end_html() ); 49 50 # close the statement and database handles 51 $databaseHandle->disconnect(); 52 $statementHandle->finish(); Method fetchrow_array accesses the results of the query. Each call to this function returns the next set of data in the resulting table until there are no data sets left. Each row is returned as an array and assigned Each value is printed as a list option. 37 # drop-down list contains the author and ID number # method fetchrow_array returns a single row from the result fetchrow_array returns next row from the set of rows returned by the database. The row is returned as an array of values. Connection should be dropped by calling disconnect Finish is used to show that no more data will be returned from a statement handle. Detta går vi ej igenom: Formulär [send_form.pl] <form action=”get_form.pl” method=”post”> <input type=”text” name=”namn”> <input type=”submit” value=”skicka”> </form> Parsing form (query) data in traditional CGI Read the data one way for GET requests Chop pairs at & then separate parameter names (left of the ’=’) from parameter values (right of the ’=’) URL decode values (e.g. ”%7E becomes ”~”) Need special cases for omitted parameters [get_form.pl] # Ta emot formulärdata Use CGI qw/:standard/; My $name = param(namn); Print $name; Close the database connection (using method disconnect), and specify that the query is finished by calling method finish Program Output
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.