15
1 Chapter 13 Intro to Server-Side Programming Presented by Thomas Powell Slides adopted from HTML & XHTML: The Complete Reference, 4th Edition ©2003 Thomas A. Powell Web Programming Toolbox Server-side scripting * Active Server Pages (ASP) * ColdFusion * PHP Scripting Languages * JavaScript * VBScript Java Servlets Java Applets ActiveX Controls Server API Programs * ISAPI * NSAPI * Apache Modules Netscape Plug-ins CGI scripts and programs Helper Applications Server Side Client Side Web Programming in Context

Chapter 13 Intro to Server-Side Programmingclasses.pint.com/xhtml2/chapter13/small.pdfChapter 13 Intro to Server-Side ... Client side or Server side? ... HTML style server-side scripting

Embed Size (px)

Citation preview

Page 1: Chapter 13 Intro to Server-Side Programmingclasses.pint.com/xhtml2/chapter13/small.pdfChapter 13 Intro to Server-Side ... Client side or Server side? ... HTML style server-side scripting

1

���������� ����������� �

Chapter 13Intro to Server-Side

ProgrammingPresented by Thomas Powell

Slides adopted from HTML & XHTML: The Complete Reference, 4th Edition

©2003 Thomas A. Powell

���������� �

Web Programming Toolbox

Server-side scripting* Active Server Pages (ASP)* ColdFusion* PHP

Scripting Languages* JavaScript* VBScript

Java ServletsJava Applets

ActiveX Controls

Server API Programs* ISAPI* NSAPI* Apache Modules

Netscape Plug-ins

CGI scripts and programsHelper Applications

Server SideClient Side

���������� �

Web Programming in Context

Page 2: Chapter 13 Intro to Server-Side Programmingclasses.pint.com/xhtml2/chapter13/small.pdfChapter 13 Intro to Server-Side ... Client side or Server side? ... HTML style server-side scripting

2

���������� �

Client-Server Overview

• Web is a client-server environment• Web browser is typically the client• Web server is obviously the server• In some ways Web server is a file server, but it

could be more of an application server when interactivity is added

• There is a question of where the computing in the Web should run. Client side or Server side?

���������� �

Client v.s. Server

• Client side programming can be problematic because you don’t have a great deal of control over what the user has– Screen size– Java/JavaScript support– Browser differences– Hardware

• Server side programming can be problematic because it puts all the responsibility on the server and can cause performance problems

• The best approach is a balance with nothing being to heavily relied on particularly client side wise. Everything should be done in a defensive manner.

���������� �

CGI Basics

• The most basic server-side way to add interactivity to a Web site is through a CGI (Common Gateway Interface) program.

• CGI = Common Gateway Interface• CGI is not the program it is the way things are interfaced• CGI specifies how data should passed in from a Web page and back

out• CGI Process

1) User submits form2) Form is sent to server and eventually CGI program3) CGI program processes data and responds back4) Web server passes CGI response to client

• The important part is step 2 and the end of step 3 where data goes back and forth.

Page 3: Chapter 13 Intro to Server-Side Programmingclasses.pint.com/xhtml2/chapter13/small.pdfChapter 13 Intro to Server-Side ... Client side or Server side? ... HTML style server-side scripting

3

���������� �

CGI Up Close

• 2.1 Server determines if request is a document or program• 2.2 Server locates the program and determines if the program can

be executed• 2.3 Server starts program (expensive) and sends it the data from

form and environment• 2.4 Program runs• 2.5 Server waits for program to finish and takes the result and

passes it back to client

• Understanding CGI requires an understanding of HTTP and forms

���������� �

How the Web Works

• Pretend to be a Web browser– Telnet www.yourfavoritesite.com 80– Eventually at the prompt type in

• GET / HTTP/1.0• Hit return twice

– Watch server respond back with headers and then HTML markup

• Key to interaction is the MIME type as indicated by the response header– Content-type: text/html– This header tells the browser what it is “reading”

• To “dynamically make HTML” from a server program just stamp the output with the appropriate MIME type.

���������� �

CGI Example

• Try http://www.htmlref.com/cgi-bin/firstcgi.pl

This file is a short Perl program like this

#!/usr/bin/perl

print "Content-type: text/html\n\n";

print"<HTML>\n<HEAD><TITLE>From CGI</TITLE></HEAD>\n";

print"<BODY BGCOLOR=red>\n<H1>Wow! I was created from a CGI program!!</H1>\n<HR>

<P>More Stuff</P>";

print"<HR>\n</BODY></HTML>";

• The key to making this “CGI” was literally the first print statement and the fact it was run on the Web

Page 4: Chapter 13 Intro to Server-Side Programmingclasses.pint.com/xhtml2/chapter13/small.pdfChapter 13 Intro to Server-Side ... Client side or Server side? ... HTML style server-side scripting

4

���������� �

Reading Data In

• The output half of CGI is just printing the appropriate HTML markup and headers, the input is slightly harder.

• There are two primary ways of getting data into a CGI program – Environment variables– Forms

• When a request takes place headers from the browser and server are combined to create the “environment”This is easily accessible from a programming language.

• Demo– http://www.htmlref.com/cgi-bin/printenv.cgi

���������� �

<html><head><title>CGI Form Example</title></head><body><h1 align="center">Registration Form</h1><hr><form action="http://www.pint.com/cgi-bin/formtest.pl" method= "get" ><table border="1"><tr><td align="left"><b>Name: </b></td><td><input type="text" name="username" size="30" maxlength="40"></td>

</tr><tr><td align="left"><b>E-mail: </b></td><td><input type="text" name="email" size="25" maxlength="30"></td>

</tr><tr><td align="center" ><input type="submit" value="Send"> <input type="reset" value="Reset">

</td></tr></table></form></body></html>

���������� �

CGI Form Example

#!/usr/bin/perl

require ("cgi-lib.pl");&ReadParse;

$name = $in{"username"};$email = $in{"email"};

print "Content-type: text/html\n\n";print "<H1>Hello $name. Nice to meet you!\n</H1><BR>";print "Email: $email";

On the server you have a program like this called formtest.pl

Notice the use of a library to do much of the parsing work

Page 5: Chapter 13 Intro to Server-Side Programmingclasses.pint.com/xhtml2/chapter13/small.pdfChapter 13 Intro to Server-Side ... Client side or Server side? ... HTML style server-side scripting

5

���������� �

Writing CGI

• What language do you write your CGI program in?– Whatever you want– C, Java, Pascal, Fortran, Cobol, PERL, Python, etc.– PERL is common because portable and good at text

handling– Take a look at the numerous libraries and example

CGI code online at sites like http://www.cgi-resources.com

���������� �

The Joy of Server Side Programming

• Your main problem with writing CGI programs will be– 1) Parsing data sent in via forms and environment

– Let the Library do it!

– 2) Dealing with state management• This is not unique to CGI as the bane of all server-side

development on the Web• Why? HTTP is stateless! It doesn’t know you from request to

request.• Three approaches to state problem1) HIDDEN form data2) Extended Path info3) Cookies!

– Again hopefully you’ll rely on libraries to deal with this pain

���������� �

CGI Speed Complaints

• CGI has speed issues– Launch– Language

• Solve some of this by simply writing in a compiled language or using a special CGI engine to speed up execution related to launch

• Real speed improvement comes with server modules

Page 6: Chapter 13 Intro to Server-Side Programmingclasses.pint.com/xhtml2/chapter13/small.pdfChapter 13 Intro to Server-Side ... Client side or Server side? ... HTML style server-side scripting

6

���������� �

Server Modules

• Server modules are special programs written to the API of a particular Web server that generally run within the task space of the server – ISAPI – Microsoft IIS API– NSAPI – Netscape Server API– Apache Module – Apache Server API– Java Servlets – Trying to be cross server module

format but you need an engine to deal with it• Server modules are of course much more

difficult to write than CGI programs and have server stability downsides if they crash

���������� �

Server Module Resources

• ISAPI– http://msdn.microsoft.com/library/psdk/iisref/isgu6j5f.h

tm

• NSAPI– http://docs.iplanet.com/docs/manuals/enterprise/41/ns

api/contents.htm

• Apache Modules– http://www.apache.org

• Java Servlets– http://java.sun.com/products/servlet/index.html

���������� �

Server Side Scripting Intro

• Server-side scripting often dubbed “parsed HTML” solutions offer a third solution to server-side programming

• Consider the idea of writing a special BozoScriptserver module that looks to see if a file is being requested with an extension .bozo If it sees this it parses the page, if not it passes it on. If you get this idea you understand how all parsed HTML style server-side scripting languages work as shown in the next slide

Page 7: Chapter 13 Intro to Server-Side Programmingclasses.pint.com/xhtml2/chapter13/small.pdfChapter 13 Intro to Server-Side ... Client side or Server side? ... HTML style server-side scripting

7

���������� �

���������� �

Parsed Script Intro

• Basic parsed HTML is Server Side Includes (SSI)• .shtml files• In the form of a comment

– <!--#include file=“footer.html”-->

• Some basic ones are common to all servers, but some others are unique to a particular Web platform

• Common Server Side Script languages– ColdFusion (www.allaire.com) [.cfm]– Active Server Pages from Microsoft [.asp]– PHP [.php]– JSP [.jsp]– On and on.

���������� �

ColdFusion Markup Overview

• ColdFusion (www.macromedia.com) is a simple server-parsed tag based scripting language that is very focused on connecting databases to Web pages– ColdFusion requires a special Application Server and it runs on NT,

Linux, and Solaris– Like other server parsed scripting solutions the app server is

engaged when a file of a particular extension (.cfm) is requested• Cold Fusion markup looks like basic HTML tags and thus is

popular with people who are new to programming

• Main purpose of CF is to connect to a database– Either using ODBC or native database drivers

Page 8: Chapter 13 Intro to Server-Side Programmingclasses.pint.com/xhtml2/chapter13/small.pdfChapter 13 Intro to Server-Side ... Client side or Server side? ... HTML style server-side scripting

8

���������� �

ColdFusion Markup Overview• You need to specify basic SQL (Structured Query

Language) statements to use CF• Given a DB table called Positions with the fields Position-

Num, JobTitle, Location, Description, Hiring Manager, and PostDate. It is easy to query the table using statements like

– SELECT * FROM Positions

– SELECT * FROM Positions WHERE Location="Austin"

– SELECT *FROM PositionsWHERE ((Location="Austin" OR

(Location="Los Angeles") AND(Position="Game Tester"))

���������� �

<CFQUERY>

<CFQUERY NAME="ListJobs"DATASOURCE="CompanyDataBase">

SELECT * FROM Positions</CFQUERY>

Note: The DATASOURCE attribute is set equal to CompanyDataBase, which is the ODBC data source that contains a database called Company, which contains the Positions table from which data is pulled.

<CFQUERY> supports attributes like NAME, DATASOURCE, MAXROWS, USERNAME, PASSWORD, TIMEOUT, and DEBUG

���������� �

<CFOUTPUT>• Once you have data for example from variables,

calculations or a from a database query you can output it with <CFOUTPUT>

<CFOUPUT QUERY="ListJobs"><hr noshade><br>Position Number: <b>#PositionNum#</b><br><br>Title: #JobTitle#<br><br>Location: #Location#<br><br>Description: #Description#

</CFOUPUT>

• Notice the use of # symbols to relate the fields of the database with output “slots” Also notice how HTML and database fields are intermixed.

Page 9: Chapter 13 Intro to Server-Side Programmingclasses.pint.com/xhtml2/chapter13/small.pdfChapter 13 Intro to Server-Side ... Client side or Server side? ... HTML style server-side scripting

9

���������� �

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><CFQUERY NAME="ListJobs" DATASOURCE="CompanyDataBase">SELECT * from Positions</CFQUERY><html><head><title>Demo Company Job Listings</title></head><body bgcolor="#FFFFFF"><h2 align="center">Job Listings</h2><hr><CFOUTPUT QUERY="ListJobs"><hr noshade><br> Position Number: #PositionNum#<br><br>Title: #JobTitle#<br><br>Location: #Location#<br><br>Description: #Description#</CFOUTPUT><hr><address>Demo Company, Inc.</address></body></html>

���������� �

Common CFML Elements

• <CFABORT>• <CFAPPLICATION>• <CFCOL>• <CFCONTENT>• <CFCOOKIE>• <CFERROR>• <CFFILE>• <CFHEADER>• <CFIF>• <CFINCLUDE>

• <CFINSERT>• <CFLOCATION>• <CFLOOP>• <CFMAIL>• <CFOUTPUT>• <CFPARAM>• <CFQUERY>• <CFREPORT>• <CFSET>• <CFTABLE>• <CFUPDATE>

���������� �

CFM Summary

• Database specific• Very high level (like a 4GL)• Tag like so integrates well with HTML• Some programmers find clumsy because

not script like• However, functionally equivalent to any

other script language• Still NT oriented despite appearing cross

server

Page 10: Chapter 13 Intro to Server-Side Programmingclasses.pint.com/xhtml2/chapter13/small.pdfChapter 13 Intro to Server-Side ... Client side or Server side? ... HTML style server-side scripting

10

���������� �

ASP Intro• Microsoft’s Active Server Pages (ASP) is probably

the most popular server parsed scripting technology used today and is indicated by files ending in .asp– Likely because it is free and Microsoft oriented– VB or JavaScript oriented– Reality is script neutral

• You can use any script language in an ASP page but most people do not

– Tends to be bulkier to do similar tasks than CF but offers a more “programmer” friendly syntax

• NT specific though there are UNIX ports without COM object support.

���������� �

ASP ExampleNote <script> tag showing location of execution and language and

script is delimited by <% %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><script language="VBScript" runat="Server"></script><html><head><title>ASP Example</title></head><body><h1>Breaking News</h1>

<% = date() %>

<p>Today the stock of a major software company <br>reached an all time high, making the Demo Company CEO<br>the world's first and only trillionaire.</p></body></html>

���������� �

ASP Summary

• ASP syntax can get more involved than CFM, for example consider a similar database example

• <%Set Conn = Server.CreateObject("ADODB.Connection")

Conn.Open ODBCPositionsSQL = "SELECT JobTitle, Location, Description, HiringManager,

PostDate FROM Positions"Set RS = Conn.Execute(SQL)Do While Not RS.EOF

%>

• Yet is it correct to want to get more complicated with script? Instead should we do simple tasks with scripts and do heavy lifting with objects?

• Script + objects makes sense and in this respect you would find that CFM and ASP are more similar than they are dissimilar

• See www.asphole.com, www.15seconds.com for ASP info

Page 11: Chapter 13 Intro to Server-Side Programmingclasses.pint.com/xhtml2/chapter13/small.pdfChapter 13 Intro to Server-Side ... Client side or Server side? ... HTML style server-side scripting

11

���������� �

PHP Intro

• PHP is a free server parsed scripting environment gaining popularity

• See www.php.net for the best PHP info• Mostly Linux oriented though ports exist• Does have some limitations that have only be recently

addressed– Performance– Session management– Database integration

• On the upside it provides numerous useful features and is somewhat between CFM and ASP in complexity

���������� �

First PHP

• PHP files end generally in .php• Within the file scripts are denoted in PHP in numerous

ways.• Most common <?php ?>

– Always suggested like this– A shorter form is just <? ?>

• Also use <script>– <script language="php">

echo ("some editors (like FrontPage) don't like processing instructions");</script>

• Also use ASP style syntax– <% echo ("You may optionally use ASP-style tags"); %>

���������� �

PHP Hello World

<html><head><title>Hello PHP world</title></head><body>

<?php

print("Hello world from PHP!");

?>

</body>

</html>

Page 12: Chapter 13 Intro to Server-Side Programmingclasses.pint.com/xhtml2/chapter13/small.pdfChapter 13 Intro to Server-Side ... Client side or Server side? ... HTML style server-side scripting

12

���������� �

PHP Intro

• PHP syntax is similar to C• PHP doesn’t care about white space so• $result = 2 =+ 2; is the same as • $result = 2 • Statements are ended by semi-colons ;• PHP is somewhat case sensitive

– Variable names are case sensitive– Function names both defined and built-in are not– In short you should make sure to pretend the language is case

sensitive

���������� �

PHP Comments

• Comments in PHP should be indicated in the standard C fashion. /* This is a comment */

Also // Single line comment

As well as a UNIX shell style comment– # Hi I’m a comment

���������� �

Types in PHP

• Simple Types– Integers Doubles– Strings Arrays– Objects Booleans (somewhat)

• Variables are declared with a leading $– Contain a mixture of letters, digits, and the underscore after the $,

but don’t start with a number so $x5 is a legal variable while $5x is not.

– Variables do not have to be declared before use– Variables have no intrinsic type beyond the type of their current

value (read PHP is loosely typed)– PHP puts some default value in a variable if it is not set before it is

used

Page 13: Chapter 13 Intro to Server-Side Programmingclasses.pint.com/xhtml2/chapter13/small.pdfChapter 13 Intro to Server-Side ... Client side or Server side? ... HTML style server-side scripting

13

���������� �

PHP Variable Demo<php

$align = center;$footer = "&copy; 2000, Demo Company, Inc.";

?><html><head><title>Simple Variables Example</title></head><body><h1 align="<?php print("$align");?>">HTML and PHP</h1><hr><?php

print("<i>Hello world from PHP!</i>");?><hr> <?php

print("$footer");?></body></html>

���������� �

PHP Type Issues

• PHP provides a function called IsSet that tests a variable to see if it has been defined already

• Be careful with type conversion in PHP• It is even looser than JavaScript and variables

tend to take on the type of whatever context they are being used within

• Always assume that PHP will try to forgive you.– Actually this is what makes it difficult at times to

debug.

���������� �

PHP Variables

• Easy to define variables– $today = “Thursday”;

$num = 5;• All the environment variables for a page

request should be made available in PHP, for example

$���� ��� ������������ ����������

� �����

Page 14: Chapter 13 Intro to Server-Side Programmingclasses.pint.com/xhtml2/chapter13/small.pdfChapter 13 Intro to Server-Side ... Client side or Server side? ... HTML style server-side scripting

14

���������� �

PHP Variables

• You can also pass data from page to page and have it available as a variable.

• For example if you had<form action=“page2.php” method=“post”><input type=“text” name=“username”><input type=“submit” value=“send”>

</form>

On the next page called page2.php a variable called $username would have the value the user entered.

���������� �

Common Operators

������������ �!��"� �# �"� �$��"� �%��"� �&��"

� ������������� �''��"

�()��*+�� �*���,) -�����"�� �'''��"�./0�1�*� -2

�()��*+�� �*���,) -�����"3� 10� (���+�� ����45��

� �6'��"� �6''��"���.����*0�1�*� -2

�()��*+�� �*��1����,) -�����"3��(�1����+�� ����45��

� �7��"� �8��"� �7'��"� �8'��"

���������������(expr1) ? (expr2) : (expr3);

���������� �

Include Example

<html><head><title>Hello PHP world</title></head><body><?php

include ("templates/header.inc");?>

<hr><p>Fill in document contents here</p>

<hr><?phpinclude("templates\footer.inc");

?>

</body></html>

Page 15: Chapter 13 Intro to Server-Side Programmingclasses.pint.com/xhtml2/chapter13/small.pdfChapter 13 Intro to Server-Side ... Client side or Server side? ... HTML style server-side scripting

15

���������� �

Common Operators

���� ���������� ���!!� �(�#*1�(���1�� !! ����#*1�(���1�##� �(�#0��(���1�� ## ����#0��(���1�

�������������� � 10��" �10� ��(��" �(� �9�(�" �9�-)�*:���(6�� ���� �����" �10� �;;��" �(

String Operators$a = "Hello "; $b = $a . "World!"; // now $b contains "Hello World!“$a = "Hello ";$a .= "World!"; // now $a contains "Hello World!"

���������� �

Statements

������������������������

�������������������

�������������������������

Control statements in PHP are similar to nearly any procedural language like C, JavaScript, etc.