Based on material  2000 Deitel & Associates, Inc. 1 Chapter 27 – CGI (Common Gateway Interface) and Perl 5 Outline 27.1Common Gateway Interface (CGI)

Slides:



Advertisements
Similar presentations
Chapter 25 Perl and CGI (Common Gateway Interface)
Advertisements

PHP I.
WEB DESIGN TABLES, PAGE LAYOUT AND FORMS. Page Layout Page Layout is an important part of web design Why do you think your page layout is important?
Tutorial 6 Creating a Web Form
The Web Warrior Guide to Web Design Technologies
1 Configuring Internet- related services (April 22, 2015) © Abdou Illia, Spring 2015.
Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Introduction to Scripting.
1 Chapter 12 Working With Access 2000 on the Internet.
B.Sc. Multimedia ComputingMedia Technologies Database Technologies.
Creating Web Page Forms. Objectives Describe how Web forms can interact with a server-based program Insert a form into a Web page Create and format a.
Guide To UNIX Using Linux Third Edition
Chapter 11 ASP.NET JavaScript, Third Edition. 2 Objectives Learn about client/server architecture Study server-side scripting Create ASP.NET applications.
Computer Science 101 Web Access to Databases Overview of Web Access to Databases.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 25 – Perl and CGI (Common Gateway Interface) Outline 25.1 Introduction 25.2 Perl 25.3 String Processing.
Web Development & Design Foundations with XHTML Chapter 9 Key Concepts.
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
McGraw-Hill/Irwin © 2004 by The McGraw-Hill Companies, Inc. All rights reserved. Beginning Active Server Pages Barry Sosinsky Valda Hilley Programming.
Chapter 9 Collecting Data with Forms. A form on a web page consists of form objects such as text boxes or radio buttons into which users type information.
1 Web Developer & Design Foundations with XHTML Chapter 6 Key Concepts.
Chapter 9 Using Perl for CGI Programming. Computation is required to support sophisticated web applications Computation can be done by the server or the.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 24 – Web Servers (PWS, IIS, Apache, Jigsaw) Outline 24.1Introduction 24.2Microsoft Personal.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
 2001 Deitel & Associates, Inc. All rights reserved. 1 Chapter 29 – Perl 5 and CGI (Common Gateway Interface) Outline 29.1Introduction 29.2Perl 29.3String.
Advance web Programming Chapter 3: MySQL Date: 28 April 2014 Advance web Programming Chapter 3: MySQL Date: 28 April 2014 Dr. Mogeeb A. A. Mosleh .
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
XP Tutorial 6New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Creating Web Page Forms Designing a Product Registration Form Tutorial.
XP Tutorial 6New Perspectives on HTML and XHTML, Comprehensive 1 Creating Web Page Forms Designing a Product Registration Form Tutorial 6.
Comp2513 Forms and CGI Server Applications Daniel L. Silver, Ph.D.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Chapter 6: Forms JavaScript - Introductory. Previewing the Product Registration Form.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
4-1 INTERNET DATABASE CONNECTOR Colorado Technical University IT420 Tim Peterson.
Introduction to Shell Script Programming
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
Introduction to Programming the WWW I CMSC Summer 2004 Lecture 6.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 21 - Web Servers (IIS, PWS and Apache) Outline 21.1 Introduction 21.2 HTTP Request Types 21.3.
INE1020 Introduction to Internet Engineering Tutorial 9 Lab 6 and Assignment 2.
Chapter 8 Cookies And Security JavaScript, Third Edition.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
Active Server Pages  In this chapter, you will learn:  How browsers and servers interacted on the Internet when the Internet first became popular 
Chapter 8 Collecting Data with Forms. Chapter 8 Lessons Introduction 1.Plan and create a form 2.Edit and format a form 3.Work with form objects 4.Test.
Chapter 6 Server-side Programming: Java Servlets
ITCS373: Internet Technology Lecture 5: More HTML.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
7 Chapter Seven Client-side Scripts. 7 Chapter Objectives Create HTML forms Learn about client-side scripting languages Create a client-side script using.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
Introduction to Programming the WWW I CMSC Winter 2003.
5 1 Data Files CGI/Perl Programming By Diane Zak.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
 2000 Deitel & Associates, Inc. All rights reserved. Outline 8.1Introduction 8.2A Simple Program: Printing a Line of Text in a Web Page 8.3Another JavaScript.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
 2001 Prentice Hall, Inc. All rights reserved. Chapter 7 - Introduction to Common Gateway Interface (CGI) Outline 7.1Introduction 7.2A Simple HTTP Transaction.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 27 – CGI (Common Gateway Interface) and Perl 5 Outline 27.1Common Gateway Interface (CGI)
ASP-2-1 SERVER AND CLIENT SIDE SCRITPING Colorado Technical University IT420 Tim Peterson.
1) PHP – Personal Home Page Scripting Language 2) JavaScript.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Web Database Programming Using PHP.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
Linux Administration Working with the BASH Shell.
Chapter 7 - Introduction to Common Gateway Interface (CGI)
Chapter 19 PHP Part III Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
Chapter 19 PHP Part II Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
Chapter 27 WWW and HTTP.
Configuring Internet-related services
PHP.
Presentation transcript:

Based on material  2000 Deitel & Associates, Inc. 1 Chapter 27 – CGI (Common Gateway Interface) and Perl 5 Outline 27.1Common Gateway Interface (CGI) 27.2Introduction to Perl 27.3Configuring Personal Web Server (PWS) for Perl/CGI 27.4String Processing and Regular Expressions 27.5Viewing Client/Server Environment Variables 27.6Form Processing and Business Logic 27.7Server-Side Includes 27.8Verifying a Username and Password 27.9Sending from a Web Browser 27.10Using ODBC to Connect to a Database Cookies and Perl 27.12Case Study: Building a Search Engine

Based on material  2000 Deitel & Associates, Inc Common Gateway Interface (CGI) Server-side programming –Process data on the server to increase communication between clients and servers –Create interactive applications Client-side scripting –Not always sufficient when building truly interactive Web- based applications HyperText Transfer Protocol (HTTP) –Used for communication between Web browsers and servers Universal Resource Locator (URL) –Used by browsers (clients) to specify name of server from which to request data

Based on material  2000 Deitel & Associates, Inc Common Gateway Interface (CGI) (II) HTTP GET command –By issuing command, client directs server to send specific data to browser CGI –Lets HTTP clients interact with programs across a network through a Web server –A standard for interfacing applications with a Web server –CGI applications Can be written in many different programming languages Often reside in the directory /cgi-bin Within Web server –Permission granted by webmaster to allow specific programs to be executed on the server

Based on material  2000 Deitel & Associates, Inc Common Gateway Interface (CGI) (III) Interaction methods –Standard input (keyboard) –Standard output (screen) Web browser –Take info from user –Using HTTP, sends info to a Web server –Server-side CGI program executed –Standard output from server-side applications or scripts redirected or piped to CGI –Output sent from CGI over the Internet to client for rendering CGI is an interface –Cannot be directly programmed –Script or executable program must be used to interact with it

Based on material  2000 Deitel & Associates, Inc Common Gateway Interface (CGI) (IV) Data path of a typical CGI-based application

Based on material  2000 Deitel & Associates, Inc Introduction to Perl Perl (Practical Extraction and Report Language) –High-level programming language –Developed by Larry Wall in 1987 Trained as a linguist A systems admin at NASA –Rich, easy-to-use text-processing capabilities –Alternative to the tricky C programming language –Powerful alternative to Unix shell scripts Lots of built-in functionality TMTOWTDI

Based on material  2000 Deitel & Associates, Inc Introduction to Perl Current version: Perl –Programming Perl (1 st ed.) was about Perl 4 –Perl 5 is a complete rewrite –An entirely new language Good choice for programming server side WWW –Most popular language for doing so today –Is under continuous update by the online Perl community Stays competitive with newer server-side technologies Programmer driven Extensible by modular objects Can even search the online object-base to find newer versions

Based on material  2000 Deitel & Associates, Inc Introduction to Perl (II) Perl initially developed for Unix platform –Always intended to be a cross-platform computer language ActivePerl –Version of Perl for Windows –Free download at –Includes the core Perl package Predefined functionality expected to behave the same across all platforms Perl Interpreter — perl.exe — placed in bin directory Loaded into memory each time Perl program invoked –Extension of Perl programs is.pl Associated with Perl interpreter by default Perl program execution –Type perl –w followed by filename of Perl source code at command line (Unix or DOS prompt)

Based on material  2000 Deitel & Associates, Inc Introduction to Perl (III) Perl command line switches (case sensitive)

Based on material  2000 Deitel & Associates, Inc Introduction to Perl (IV) Comment character - # –Goes at beginning of every line with comment Function print –Outputs text indicated by quotation marks ( “…” ) Escape sequences –E.g. \n, \t, \a –Newline, tab, alert Statements terminated with semicolons ( ; ) –Exception: where braces ( {} ) used to denote block of code

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Print Statement 1# Fig. 27.4: first.pl 2# A first program in Perl. 3 4print "Welcome to Perl!\n"; Welcome to Perl!

Based on material  2000 Deitel & Associates, Inc Introduction to Perl (V) Perl contains set of data types –Represent different kinds of information –Each variable name has special character preceding it $ - variable contains scalar value –Strings, integer numbers and floating-point - indexed array –Uses an integer (called an index) to reference array elements % - hash (associative array) –Uses keys that are strings to reference individual array elements –Variables should be initialized before being used Variable names in strings –Serve as place-holders for values they represent –If have no declared value – set to undef (empty) value

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Demonstrate variable in string before initialization 1.2 Demonstrate addition involving variable using print statements 1.3 Add integer to string and print result Add integer to string and print result 1# Fig. 27.6: variable.pl 2# Program to illustrate the use of scalar variables. 3 4# using a variable in the context of a string 5print "Using a variable before initializing: $var\n"; 6 7# using a variable in a numeric context 8$test = $num + 5; 9print "Adding uninitialized variable num to 5 yields: $test.\n"; 10 11$a = 5; 12print "The value of variable a is: $a\n"; 13 14$a = $a + 5; 15print "Variable a after adding 5 is $a.\n"; 16 17$b = "A string value"; 18$a = $a + $b; 19 20print "Adding a string to an integer yields: $a\n"; 21 22$number = 7; 23$b = $b + $number; 24 25print "Adding an integer to a string yields: $b\n"; Using a variable before initializing: Adding uninitialized variable num to 5 yields: 5. The value of variable a is: 5 Variable a after adding 5 is 10. Adding a string to an integer yields: 10 Adding an integer to a string yields: 7

Based on material  2000 Deitel & Associates, Inc Introduction to Perl (VI) Perl can store arrays –Arrays divided into elements Each can contain an individual scalar variable Array = (“element1”, “element2”, …, “elementN”); First array element is [0] –Just like C, C++, etc. –Could be changed in Perl 4 but should not in Perl 5

Based on material  2000 Deitel & Associates, Inc Introduction to Perl (VII) Arrays –Elements are referenced as scalar values with element number in square brackets ( [] refers to array as a whole, $ refers to elements Example: $array[2] Refers to the third element Range Operator – “.. ” –Used to store all values between given arguments = (A..Z); –Creates containing all capital letters in alphabet (all letters between A and Z )

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Define 2.1 Print contents 2.2 Print third element 3.1 Define 3.2 Explain and print contents 1# Fig. 27.7: arrays.pl 2# Program to demonstrate arrays in Perl 3 = ("Bill", "Bobby", "Sue", "Michelle"); 5 6print "The array contains:\n\n"; 7print \n\n"; 8print "Third element: $array[2]\n\n"; 9 = (A..Z); 11 12print "The range operator is used to store all\n"; 13print "letters from capital A to Z:\n\n"; 14print \n"; The array contains: Bill Bobby Sue Michelle Third element: Sue The range operator is used to store all letters from capital A to Z: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Based on material  2000 Deitel & Associates, Inc Introduction to Perl (VIII) In addition to core Perl package –Add-ons called packages provide additional functionality Packages –Often provide platform specific features –Are available at

Based on material  2000 Deitel & Associates, Inc Configuring Personal Web Server (PWS) for Perl/CGI To run CGI with PWS –Several modifications must be made in the Windows Registry PWS must be enabled to execute Perl scripts – does not by default For detailed instructions on procedure to update Windows Registry to handle Perl scripts –See section 27.3 in Deitel, et al.

Based on material  2000 Deitel & Associates, Inc String Processing and Regular Expressions Processing textual data easily and efficiently –One of Perl’s most powerful capabilities –Usually done through use of regular expressions Patterns of characters used to search through text files and databases Allows large amounts of text to be searched using relatively simple expressions eq equality operator –Tests whether two strings are equivalent example: if ($hello eq “Good Morning”) … Keyword my –Designates variable only valid for block of code in which it is declared

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Declare variables using my 2.1 Test string variable-string equality 2.2 Print appropriate result 3.1 Test second variable 3.2 Print appropriate result 1# Fig : equals.pl 2# Program to demonstrate the eq operator 3 4my $stringa = "Test"; 5my $stringb = "Testing"; 6 7if ($stringa eq "Test") 8{8{ 9 print "$stringa matches Test.\n"; 10} 11else 12{ 13 print "$stringa does not match Test.\n"; 14} 15 16if ($stringb eq "Test") 17{ 18 print "$stringb matches Test.\n"; 19} 20else 21{ 22 print "$stringb does not match Test.\n"; 23} Test matches Test. Testing does not match Test.

Based on material  2000 Deitel & Associates, Inc my and local Keyword my –Designates variable only valid for block of code in which it is declared –In Perl 4 was done by local my creates local variables local creates local copy & then restores it on exit See program …

Based on material  2000 Deitel & Associates, Inc. 22 my and local (program) $lo = 'global'; $m = ‘global'; A(); sub A { local $lo = 'string'; my $m = 'string'; B(); } sub B { print "B can", ($lo eq 'string' ?'can' :'cannot'), " see the value of lo set by A.\n"; print "B can", ($m eq 'string' ?'can' :'cannot'), " see the value of m set by A.\n"; } B can see the value of lo set by A. B cannot see the value of m set by A.

Based on material  2000 Deitel & Associates, Inc String Processing and Regular Expressions (II) eq operator –Cannot be used to search through a series of words Matching ‘operator’ : =~ –Tests whether match for a string is found within a single string or series of words Format $search =~ /Test/ Searches for word test within indicate string

Based on material  2000 Deitel & Associates, Inc String Processing and Regular Expressions (III) Some meta/modifying characters –^ - indicates beginning of a line –$ - indicates end of a line –\b … \b – indicates word boundary –\w – matches any alphanumeric character Other modifying characters

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Test for word ‘Test’ in string, print result 2.1 Test for word ‘Test’ at beginning on string, print result 3.1 Test for word ‘Test’ at end of string, print result 4.1 Test for word in string ending with letters ‘es’, print result 1# Fig 27.17: expression1.pl 2# searches using the matching operator and regular expressions 3 4$search = "Testing pattern matches"; 5 6if ( $search =~ /Test/ ) 7{7{ 8 print "Test was found.\n"; 9}9} 10 11if ( $search =~ /^Test/ ) 12{ 13 print "Test was found at the beginning of the line.\n"; 14} 15 16if ( $search =~ /Test$/ ) 17{ 18 print "Test was found at the end of the line.\n"; 19} 20 21if ( $search =~ / \b ( \w+ es ) \b /x ) 22{ 23 print "Word ending in es: $1 \n"; 24} Test was found. Test was found at the beginning of the line. Word ending in es: matches

Based on material  2000 Deitel & Associates, Inc Viewing Client/Server Environment Variables Knowing info about client very useful to system administrators CGI environment variables –Contains info about client Web browser being used Version of CGI server running HTTP host, HTTP connection Much more use statement –Allows inclusion of predefined library packages in programs

Based on material  2000 Deitel & Associates, Inc Viewing Client/Server Environment Variables (II) CGI Library –Included to provide functionality that makes it easier to write HTML sent to Web browser –Contains keywords that represent HTML tags foreach loop –Iterates through keys in given hashtable, performs indicated actions foreach $key (sort keys %ENV) –Iterates through %ENV hashtable Built-in table in Perl that contains names and values of all CGI environment variables –sort function returns list in alphabetical order –Assigns current key to $key and performs indicated actions

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 use standard CGI library 2.1 Print top of HTML Table 3.1 Use foreach function to sort through keys in %ENV hashtable 3.2 Print current keys in table 4.1 Close table 1# Fig : environment.pl 2# Program to display CGI environment variables 3use CGI qw/:standard/; 4 5print header; 6print " "; 7print " "; 8print " Environment Variables... "; 9print " "; 10print " "; 11print " "; 12print " <TABLE BORDER = 0 CELLPADDING = 2 CELLSPACING = 0"; 13print " WIDTH = 100%>"; 14 15foreach $key (sort keys %ENV) 16{ 17 print " "; 18 print " $key "; 19 print " $ENV{$key}"; 20 print " "; 21 print " "; 22} 23 24print " "; 25print " "; 26print " ";

Based on material  2000 Deitel & Associates, Inc. 29 Script Output

Based on material  2000 Deitel & Associates, Inc Form Processing and Business Logic HTML FORM s 1. Allow users to enter data 2. Data sent to Web server for processing 3. Program processes data –Allows users to interact with server –Vital to electronic commerce FORM element –Indicates what action should occur when user submits form –Attribute: ACTION = “cgi-bin/form.pl” Directs server to execute form.pl Perl script

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Open FORM 1.2 Define FORM attributes 1.3 Insert and define form INPUT elements 1.4 Specify correct input format Sample FORM to take user input in HTML This is a sample registation form Please fill in all fields and click Register Please fill out the fields below Must be in the form (555)

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.5 Continue inserting and defining form INPUT element 1.6 Close FORM element Which book would you like information about? Internet and WWW How to Program 43 C++ How to Program 2e 44 Java How to Program 3e 45 Visual Basic How to Program 1e Which operating system are you 52 currently using? <INPUT TYPE = "RADIO" NAME = "OS" VALUE = "Windows NT" 56 CHECKED> 57 Windows NT Windows Windows Linux Other

Based on material  2000 Deitel & Associates, Inc. 33 Script Output

Based on material  2000 Deitel & Associates, Inc Form Processing and Business Logic (II) Retrieving data from form output –Assign to variables –Example: Assign data from form INPUT OS to variable $OS $os = param(OS); Testing for correct form input –Example: Make sure phone number in format (555) if ( $phone =~ / \( \d{3} \) \d{3} - \d{3} /x) { actions } –d{n} tests for n characters –\ is escape character Close-bracket (“ ) ”) character is used in Perl statements, needs escape character “ \ ” to appear as part of search test string

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 use standard CGI library 2.1 Assign form field values to variables 3.1 Test for correct phone number input form using if structure 3.2 Indicate actions to be performed if test returns TRUE result 1# Fig : form.pl 2# Program to read information sent to the server 3# from the FORM in the form.html document. 4 5use CGI qw/:standard/; 6 7$os = param(OS); 8$firstname = param(FNAME); 9$lastname = param(LNAME); 10$ = param( ); 11$phone = param(PHONE); 12$book = param(BOOK); 13 14print header; 15print " "; 16print " "; 17 18if ( $phone =~ / \( \d{3} \) \d{3} - \d{4} /x ) 19{ 20 print "Hi $firstname "; 21 print ". Thank you for completing the survey. "; 22 print "You have been added to the "; 23 print " $book "; 24 print "mailing list. "; 25 print " The following information has been saved "; 26 print "in our database: "; 27 print "<TABLE BORDER = 0 CELLPADDING = 0"; 28 print " CELLSPACING = 10>"; 29 print " Name "; 30 print " "; 31 print " Phone "; 32 print " OS ";

 2000 Deitel & Associates, Inc. All rights reserved. Outline 3.3 Finish inputting if structure actions and close structure 4.1 Set actions to be performed if if structure returns a FALSE value 33 print " $firstname $lastname $ "; 34 print " $phone $os "; 35 print " "; 36 print " "; 37 print " "; 38 print "This is only a sample form. "; 39 print "You have not been added to a mailing list."; 40 print " "; 41} 42else 43{ 44 print " "; 45 print "INVALID PHONE NUMBER "; 46 print " A valid phone number must be in the form"; 47 print " (555) "; 48 print " Click the Back button, "; 49 print "enter a valid phone number and resubmit. "; 50 print "Thank You."; 51}

Based on material  2000 Deitel & Associates, Inc. 37 Script Output 1

Based on material  2000 Deitel & Associates, Inc. 38 Script Output 2

Based on material  2000 Deitel & Associates, Inc Server-Side Includes Web offers ability to track –Where client coming from –What client views on your site –Where client goes after your site Tracking Web data important, allows Web masters to –Know which sites visited most frequently –Know how effective advertisements and products are Server-side includes (SSIs) –Commands embedded in HTML documents –Provide for content creation –Allow inclusion of current time, date or even contents of different html document

Based on material  2000 Deitel & Associates, Inc Server-Side Includes (II) SSI commands –Execute CGI scripts on a server –Are capable of connecting to an ODBC data source Use to create customized Web pages depending for certain conditions –Document containing SSI commands has.shtml file extension EXEC CGI command –Issued to execute a Perl script before document sent to client Example: –Executes the Perl script counter.pl, located in the cgi- bin directory

Based on material  2000 Deitel & Associates, Inc Server-Side Includes (III) ECHO command –Used to display variable information –Is followed by the keyword VAR and variable’s constant name Example: –Returns the current local time Other variables –DATE_GMT Contains current Greenwich Mean Time –DOCUMENT_NAME Contains name of current document –Many more

Based on material  2000 Deitel & Associates, Inc Server-Side Includes (IV) Perl scripts can access and modify other files –open() function Form: open(fileHandle, “>fileName”); –> discards any data in file, creates new file if does not exist –>> append mode –While file open, referenced using fileHandle –Close file using the close() statement Format: close(fileHandle); –print statement can redirect output to a file print COUNTWRITE $data; Assigns $data to file pointed to by COUNTWRITE If the file is open for writing already

Based on material  2000 Deitel & Associates, Inc Server-Side Includes (V) length() function –Returns length of string substr( expr, len, offset ) function –Similar to JavaScript’s substr function –First argument ( expr ) Specifies string from which to take a substring –Second argument ( offset ) Specifies offset in characters from beginning of the string –Third argument ( len ) Specifies length of substring to return

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Execute Perl script counter.pl using EXEC CGI statement 2.1 Use ECHO VAR statements to display environmental variables Using Server Side Includes Using Server Side Includes The Greenwich Mean Date is The name of this document is The local date is This document was last modified on 31 32

 2000 Deitel & Associates, Inc. All rights reserved. Outline 2.2 Continue printing environmental variables using ECHO VAR statements Your current IP Address is My server name is And I am using the Web Server. 50 You are using This server is using This document was last modified on

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Open counter.dat, assign to filehandle COUNTREAD 1.2 Increment data in COUNTREAD 1.3 Close COUNTREAD 2.1 Assign data contained in file counter.dat to variable $data 3.1 Use for structure to output number of page hits using number images 1# Counter.pl 2# Program to track the number of times a web page 3# has been accessed. 4 5open(COUNTREAD, "counter.dat"); 6 my $data = ; 7 $data++; 8close(COUNTREAD); 9 10open(COUNTWRITE, ">counter.dat"); 11 print COUNTWRITE $data; 12close(COUNTWRITE); 13 14print " "; 15print " You are visitor number "; 16 17for ($count = 0; $count < length($data);$count++) 18{ 19 $number = substr( $data, $count, 1 ); 20 print " "; 21} 22 23print " ";

Based on material  2000 Deitel & Associates, Inc. 47 Script Output

Based on material  2000 Deitel & Associates, Inc Verifying a Username and Password Often desirable to have private Web site –Developers often employ username and password authentication to implement privacy Upcoming files –verify.html – HTML document client browser displays –password.pl – Perl script that verifies username and password inputted by client and performs appropriate actions –data.txt – Text file containing username and password combinations (unencrypted for simplicity)

Based on material  2000 Deitel & Associates, Inc Verifying a Username and Password (II) If file cannot be opened –Use function die to exit program and print message while –Executes structure while still information in fileHandle split function –Read contents of a file into an = split(/\n/) –Creates array arrayName, creates new array entry after every \n character Access array elements and split into two parts foreach $entry {…} –Performs indicated action on every entry in –Subsequently assigns entry information to $entry

Based on material  2000 Deitel & Associates, Inc Verifying a Username and Password (III) Split array into two parts ($name, $pass) = split(/,/, $entry) –Assigns username string of current entry to $name –Assigns password string of current entry to $pass

Based on material  2000 Deitel & Associates, Inc Verifying a Username and Password (III) Perl has logical and ( && ) and or ( || ) operators –Same format as other languages Example: if ($userverified && $passwordverified) {…} –Evaluates to true if both variable values are true –Short-circuit evaluation String context: true is any non-empty string Numeric context: true is any non-zero number String "0" is false!

Based on material  2000 Deitel & Associates, Inc Verifying a Username and Password (III) sub functionName {…} –Sets actions of user-defined function functionName –User-defined functions accessed: &functionName

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Print instructions 2.1 Open FORM and define ACTION attribute 3.1 Open HTML TABLE Verifying a username and a password Type in your username and password below Note that password will be sent as plain text <TABLE BORDER = "0" CELLSPACING = "0" STYLE = "HEIGHT: 90px; 25 WIDTH: 123px" CELLPADING = "0"> Username:

 2000 Deitel & Associates, Inc. All rights reserved. Outline 3.2 Insert and define INPUT elements for username and password 3.3 Insert INPUT submit button 3.4 Close TABLE and FORM elements <INPUT SIZE = "40" NAME = "USERNAME" 36 STYLE = "HEIGHT: 22px; WIDTH: 115px"> Password: <INPUT SIZE = "40" NAME = "PASSWORD" 48 STYLE = "HEIGHT: 22px; WIDTH: 115px" 49 TYPE = PASSWORD> <INPUT TYPE = "submit" VALUE = "Enter" 55 STYLE = "HEIGHT: 23px; WIDTH: 47px">

Based on material  2000 Deitel & Associates, Inc. 55 Script Output

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Open data.txt and assign to FILE 1.2 Enter text to be printed if the file cannot be accessed using die function 2.1 Open while structure 3.1 array using FILE 3.2 Split each entry into NAME and PASS entries 3.3 Use if structure to verify username and password and perform appropriate actions 1# Fig : password.pl 2# Program to search a database for usernames and passwords. 3use CGI qw/:standard/; 4 5my $username = param(USERNAME); 6my $password = param(PASSWORD); 7 8open(FILE, "data.txt") || 9 die "The database could not be opened"; while( ) 12 { = split(/\n/); foreach $entry 16 { 17 ($name, $pass) = split(/,/, $entry); if($name eq "$username") 20 { 21 $userverified = 1; 22 if ($pass eq "$password") 23 { 24 $passwordverified = 1; 25 } 26 } 27 } 28 } 29

 2000 Deitel & Associates, Inc. All rights reserved. Outline 3.4 Close while structure 4.1 Use if structures to call user-defined programs depending on outcome of password verification 5.1 Define accessgranted function 5.2 Print ‘permission granted’ message 33 { 34 &accessgranted; 35 } 36 elsif ($userverified && !$passwordverified) 37 { 38 &wrongpassword; 39 } 40 else 41 { 42 &accessdenied; 43 } 44 45sub accessgranted 46{ 47 print header; 48 print " Thank You "; 49 print " "; 50 print " Permission has been granted $username."; 51 print " Enjoy the site. "; 52} close(FILE); if ($userverified && $passwordverified)

 2000 Deitel & Associates, Inc. All rights reserved. Outline 6.1 Define wrongpassword function 6.2 Print ‘invalid password’ message 7.1 Define accessdenied function 7.2 Print ‘access denied’ message 65sub accessdenied 66{ 67 print header; 68 print " Access Denied "; 69 print " "; 70 print "You were denied access to this server."; 71 print " "; 72 exit; 73} 54sub wrongpassword 55{ 56 print header; 57 print " Access Denied "; 58 print " "; 59 print "You entered an invalid password. "; 60 print "Access has been denied. "; 61 exit; 62 63} 64

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1account1,password1 2account2,password2 3account3,password3 4account4,password4 5account5,password5 6account6,password6 7account7,password7 8account8,password8 9account9,password9 10account10,password10 Data.txt 1.1 Input username and password combinations using format: username,password/n

Based on material  2000 Deitel & Associates, Inc. 60 Script Output

Based on material  2000 Deitel & Associates, Inc Sending From a Web Browser –One of most frequently used capabilities of the Internet –Can be sent directly from browser using Perl script Net package’s Simple Mail Transfer Protocol (SMTP) –Use this SMTP functionality to send code: use Net::SMTP; cannot be sent without a valid smtp server –Server name client uses is usually text after ” in your client’s address

Based on material  2000 Deitel & Associates, Inc Sending From a Web Browser Create a new instance of a mail server object smtp = Net::SMTP->new($mailserver); -> is Perl’s scope operator –Equivalent to “. ” in JavaScript datasend function –Tells mail server that a command is being issued smtp->quit; –Closes connection to smtp server

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Open FORM and define ACTION attribute 2.1 Inset and define INPUT submit image 2.2 Insert text INPUT s for other field categories Web-based interface To: From: 32

 2000 Deitel & Associates, Inc. All rights reserved. Outline 2.3 Insert and define remaining INPUT elements for fields 2.4 Insert and define TEXTAREA for body of message Subject: Mail 51 Server: Message: <TEXTAREA COLS = 50 NAME = "MESSAGE" ROWS = 6 64 STYLE = "HEIGHT: 170px; WIDTH: 538px">

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Close TABLE and FORM tags Script Output

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 use SMTP 1.2 use CGI standard library 2.1 Set local variable values to user form inputs 3.1 print ‘request processed’ message 4.1 Connect to SMTP server 4.2 Form message using data(), datasend() and dataend() functions 4.3 quit smtp server 1# Fig : mail.pl 2# Program to send from a Web-based form. 3 4use Net::SMTP; 5use CGI qw/:standard/; 6 7my $to = param("TO"); 8my $from = param("FROM"); 9my $subject = param("SUBJECT"); 10my $message = param("MESSAGE"); 11my $mailserver = param("MAILSERVER"); 12 13print header; 14print " The request has been Processed. "; 15print "Thank You $from "; 16 17$smtp = Net::SMTP->new($mailserver); 18 19$smtp->mail($ENV{USER}); 20$smtp->to("$to"); 21$smtp->data(); 22$smtp->datasend("To: $to \n"); 23$smtp->datasend("From: $from \n"); 24$smtp->datasend("Subject: $subject \n"); 25$smtp->datasend("\n"); 26$smtp->datasend("$message \n"); 27$smtp->dataend(); 28 29$smtp->quit;

Based on material  2000 Deitel & Associates, Inc. 67 Script Output

Based on material  2000 Deitel & Associates, Inc Using ODBC to Connect to a Database Databases allow companies to –Enter world of e-commerce –Maintain crucial data Perl package Win32-ODBC –Enables Perl programs to connect to ODBC data sources –Data source must first be defined using Data Source Administrator in MS Windows (see Section 25.5) From Web browser 1. Client enters SQL query string 2. String sent to Web server 3. Perl script executed Database queried 4. Record set in HTML form sent back to client

Based on material  2000 Deitel & Associates, Inc Using ODBC to Connect to a Database (II) Script connects to ODBC Data source –By passing the Data Source Name, $DSN, to the constructor for the Win32::ODBC object. $Data = new Win32::ODBC($DSN) new specifies that a new instance of the object is to be created –Win32::ODBC::Error Returns error that occurred Query string sent to database $Data->Sql($querystring) –If fails, error message is returned

Based on material  2000 Deitel & Associates, Inc Using ODBC to Connect to a Database (III) Method DataHash –Retrieves the fields in a row from the record set Coding HTML in Perl –Open HTML area with print header; –Close HTML area with print end_html; Use tables to output fields in a database –Organizes information neatly

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Open and define FORM 1.2 Insert and define text INPUT for entering SQL query 1.3 Insert INPUT button Sample Database Query Querying an ODBC database <INPUT TYPE = "TEXT" NAME = "QUERY" SIZE = VALUE = "SELECT * FROM AUTHORS">

Based on material  2000 Deitel & Associates, Inc. 72 Script Output

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 use Win32::ODBC; 1.2 use CGI standard library 1.3 print header (open HTML coding) 2.1 Query database and assign to $Data and set actions if query failed 3.1 Assign record set generated by SQL statement to $Data and set error actions 4.1 Initialize counter variable 1# Fig : data.pl 2# Program to query a database and send 3# results to the client. 4 5use Win32::ODBC; 6use CGI qw/:standard/; 7 8my $querystring = param(QUERY); 9$DSN = "Products"; 10 11print header; 12 13if (!($Data = new Win32::ODBC($DSN))) 14{ 15 print "Error connecting to $DSN\n"; 16 print "Error: ". Win32::ODBC::Error(). "\n"; 17 exit; 18} 19 20if ($Data->Sql($querystring)) 21{ 22 print "SQL failed.\n"; 23 print "Error: ". $Data->Error(). "\n"; 24 $Data->Close(); 25 exit; 26} 27 28print " "; 29print " "; 30print " Search Results "; 31 32$counter = 0;

 2000 Deitel & Associates, Inc. All rights reserved. Outline 5.1 Insert records into array and execute DataHash 5.2 Use foreach statement to output results 5.3 Print number of results and closing comments 6.1 print end_html; (close HTML coding area) 6.2 Close data source 33 34print " "; 35 36while($Data->FetchRow()) 37{ %Data = $Data->DataHash(); print " "; foreach $key( keys( %Data ) ) 45 { 46 print " $Data{$key} "; 47 } 48 print " "; 49 $counter++; 50} 51print " "; 52print " Your search yielded $counter results."; 53print " "; 54print " "; 55print "Please comments to "; 56print " Deitel "; 57print "and Associates, Inc.."; 58print end_html; 59 60$Data->Close();

Based on material  2000 Deitel & Associates, Inc. 75 Script Output

Based on material  2000 Deitel & Associates, Inc Cookies and Perl Cookies –Used to maintain state information for a particular client –May contain Username Password Specific information that will be helpful when user return to same site –Are small text files saved on client’s machine –Sent back to Web server whenever user requests a Web page –Can be written to client machines using Perl scripts

Based on material  2000 Deitel & Associates, Inc Cookies and Perl (II) To set a cookie using Perl –Set variable values to user input strings –Set cookie setup info $expires – expiration date of cookie $path – location on clients computer to store cookie $server_domain – IP address of your server –print “set-cookie: “; … set information to be stored in cookie using print statement –Repeat as needed to store all information in cookie After cookie written –Text file added to Temporary Internet Files directory Filename:

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 Enter text instructions 2.1 Open FORM and define ACTION attribute 2.2 Insert and define INPUT fields 2.3 Insert INPUT submit button 2.4 Close FORM area Writing a cookie to the client computer Click Write Cookie to save your cookie data Name: Height: Favorite Color

Based on material  2000 Deitel & Associates, Inc. 79 Script Output

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1# Fig : cookies.pl 2# Program to write a cookie to a client’s machine 3 4use CGI qw/:standard/; 5 6my $name = param(NAME); 7my $height = param(HEIGHT); 8my $color = param(COLOR); 9 10$expires = "Monday, 20-Dec-99 16:00:00 GMT"; 11$path = ""; 12$server_domain = " "; 13 14print "Set-Cookie: "; 15print "Name", "=", $name, "; expires=", $expires, 16 "; path=", $path, "; domain=", $server_domain, "\n"; 17 18print "Set-Cookie: "; 19print "Height", "=", $height, "; expires=", $expires, 20 "; path=", $path, "; domain=", $server_domain, "\n"; 21 22print "Set-Cookie: "; 23print "Color", "=", $color, "; expires=", $expires, 24 "; path=", $path, "; domain=", $server_domain, "\n"; 25 26print header; 27print " "; 28print " "; 29print "The cookie has been set with the folowing data:"; 30print " "; 31print " Name: $name "; 32print " Height: $height "; 33print " Favorite Color: "; 34print " $color ";

Based on material  2000 Deitel & Associates, Inc. 81 Script Output

Based on material  2000 Deitel & Associates, Inc Cookies and Perl (III) Cookies are read from client machine using Perl –Function &readCookies returns the information stored in cookies sent to client from server ip address Information read with statement $ENV{‘HTTP_COOKIE’} –Cookie information can be read by Storing information in hash array Splitting fields Displaying information Display cookie output in table for organization

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 use CGI standard library 1.2 print header 2.1 Call function readCookies to and store info in %cookie 3.1 Use foreach structure to output cookie info 4.1 Define function readCookies 4.2 Put cookie information into an array 1# Fig : read_cookies.pl 2# Program to read cookies from the client’s computer 3 4use CGI qw/:standard/; 5 6print header; 7print " "; 8print " "; 9print " The following data is saved in a cookie on your "; 10print "computer. "; 11 12my %cookie = &readCookies; 13 14print ("<TABLE ", 15 "BORDER = \"5\" ", 16 "CELLSPACING = \"0\" ", 17 "CELLPADDING = \"10\">"); 18 19foreach $cookie_name (keys %cookie) 20{ 21 print " "; 22 print " $cookie_name "; 23 print " $cookie{$cookie_name} "; 24 print " "; 25} 26print " "; 27 28sub readCookies 29{ 30 = split (/; /,$ENV{’HTTP_COOKIE’}); foreach

 2000 Deitel & Associates, Inc. All rights reserved. Outline 4.3 Split cookie entry names and values 4.4 Return information for output 33 { 34 my ($cookie_name, $cookie_value) = split ( /=/, $_ ); 35 $cookies{$cookie_name} = $cookie_value; 36 } return %cookies; 39}

Based on material  2000 Deitel & Associates, Inc. 85 Script Output

Based on material  2000 Deitel & Associates, Inc Case Study: Building a Search Engine Search engines –Allow clients to search through catalogs of info for data Typical search process 1. Usually, search string entered by client using Web browser 2. Program executed on Web server that searches through database 3. Database typically contains URL’s to specific Web sites and descriptions of site contents Info sometimes entered by administrators Info also gathered by programs running on Web server

 2000 Deitel & Associates, Inc. All rights reserved. Outline 1.1 use Cgi standard library 2.1 Open database file 3.1 Use while structure to search through file 3.2 split array into hash, search for matches to search string 3.3 Test to see if first result, if yes, enter output header 3.4 Output results as they are found 1# Fig : search.pl 2# Program to search for Web pages 3 4use CGI qw/:standard/; 5 6my $search = param(SEARCH); 7my $counter = 0; 8 9print header; 10print " "; 11 12open(FILE, "urls.txt") || 13 die "The URL database could not be opened"; 14 15while( ) 16{ 17 = split(/\n/); foreach $entry 20 { 21 my ($data, $url) = split(/;/, $entry); if ($data =~ /$search/i) 24 { 25 if ($counter == 0) 26 { 27 print " Search Results: "; 28 } print " "; 31 print " 32 print " ";

 2000 Deitel & Associates, Inc. All rights reserved. Outline 3.5 Increment counter 3.6 Close FILE 4.1 Test to see if no matches found fro search string 4.2 Set final actions 5.1 Write database file: urls.txt 33 print " $data "; 34 $counter++; 35 } 36 } 37} 38close FILE; 39 40if ($counter == 0) 41{ 42 print " Sorry, no results were found matching "; 43 print " $search. "; 44} 45else 46{ 47 print " $counter matches found for "; 48 print " $search "; 49} 50This site contains information about Perl and CGI; 51The Deitel and Deitel Web Site; 52Purchase books on this web site; 53Perl for the Win32 platform; 54The Perl Mongers Web page; 55Monthly online Perl periodical;

Based on material  2000 Deitel & Associates, Inc. 89 Script Output

Based on material  2000 Deitel & Associates, Inc. 90 Script Output