PHP
Document Sample


Other Web Application
Development Technologies
PHP
PHP
• Personal Home Pages originally; now
– PHP: Hypertext Preprocessor
• PHP is a server-side scripting language, like ASP
– PHP scripts are executed on the server
• language for creating HTML content
– normally runs as a server-side scripting language
– command line scripting possible from PHP4.2
– client-side GUI applications using PHP-GTK
• Also generates other formats
– PDF, GIF, JPEG, PNG, Flash
PHP
• free, open source technology
– free to download and use
• extensive libraries of PHP code modules
• runs on all major operating systems
– develop in Windows and serve on a Unix platform
• runs with all major web servers (Apache, IIS,
iPlanet)
• good database integration
– MySQL, Oracle, ODBC databases, PostgreSQL,
Sybase
• combined with MySQL offers a cross-platform,
open source, efficient solution
What is a PHP File?
• PHP files can contain
– text,
– HTML tags
– and scripts
• PHP files are returned to the browser as
plain HTML
• PHP files have a file extension of ".php",
".php3", or ".phtml"
PHP example
<HTML>
…
<BODY>
<H1>PHP Hello World Example</H1>
<?php echo „Hello world!‟ ?>
</BODY>
</HTML>
PHP architecture
PHP/Web Server Architecture
• web server layer
– handles http requests
– passes data to PHP via SAPI
• TSRM Thread-Safe Resource Management
• PHP language core
– many of the non-optional core features of PHP
• PHP API (available to core and PHP extensions)
• PHP extensions
– PHP comes with a skeleton extension framework
• Zend parsing engine
– runtime compiler
– executer
PHP/Web Server Architecture
web sever (Apache, IIS, etc..)
Server Abstraction API (SAPI)
PHP API
PHP Core
TSRM
PHP extensions
TSRM
Zend Engine
PHP and http
http request
data PHP
input PHP
web Zend
client page
server parsing
engine
http response output
HTML
HTML
page
form processing example
<html><head><title>Ice Cream Parlour
</title></head><body>
<h1>Ice Cream Parlour</h1>
<form action = “ices.php” method = “POST”>
Flavour : <select name=“flavour”>
<option>vanilla</option>
<option>chocolate</option>
</select>
Scoops :<input type = “text” name = “scoops” />
</form>
</body></html>
form processing example
<html>
<head><title>Ice Cream Response</title></head>
<body>
<h1>Thank you for your order</h1>
<?php
$flavour = $_POST [„flavour‟];
$scoops = $_POST [„scoops‟];
echo “$scoops scoops of $flavour coming right
up!”;
?>
</body></html>
<HTML><head>
<title>self processing PHP page</title>
</head><BODY>
<?php if(!empty($_POST[„name‟])) {
echo “Greetings, {$_POST[„name‟]}”;
} else {?>
<FORM ACTION=“<?php $PHP_SELF; ?>”
METHOD=“POST”>
Enter your Name:
<INPUT TYPE=TEXT NAME=“name”>
<INPUT TYPE=SUBMIT>
</FORM>
<?php } ?> </BODY></HTML>
control of http response
• PHP sets standard headers by default
– response status line
– date, document length
– other headers added by web server
• header () function allows other headers to
be set
– header („content-type: text/plain‟);
• header must be used before any html
generated (including leading <html> tag)
cookies
• $_COOKIE associative array used for input
• setcookie () function sets cookie headers in the http
response
– setcookie(name, value, expiration);
– $var_name = $_COOKIE[„name']; //retrieves cookie
<?php
$accesses = $_COOKIE [„accesses‟];
setcookie („accesses‟, ++$accesses);
?>
• must be used before html content
sessions
• PHP provides automatic session handling
• sessions set up using start_session() command
– start_session() must appear at the start of the PHP document
• registers the user's session with the server
• user data stored in the $_SESSION associative
array
– set: $_SESSION[„name‟] = “value” ;
– retrieve: $var_name= $_SESSION[„name‟]
– free up specific variable: unset($_SESSION['views']);
– destroy: session_destroy();
simple hit counter
<?php
session_start(); // start up your PHP
session!
if(isset($_SESSION['views'])) {
$_SESSION['views'] = $_SESSION['views']+ 1; //retrieve session
variable
}else { $_SESSION['views'] = 1; } //set session variable
echo "views = ". $_SESSION['views'];
?>
OOP in PHP
• Limited support in PHP <5
• Much better support in PHP >=5
• Simpler than Java OOP
class SomeClass {
function func() {
….
}
}
SomeClass s = new someClass();
s->func();
PHP and XML
PHP and XML
• PHP has strong text processing
functionality
– comprehensive string manipulation
– strong regular expressions
• inherited or imported from Perl
• full set of filehandling functions for file I/O
• XML data files can be created/manipulated
programmatically using text processing
approaches
PHP and XML
• DOM
– DOM processing from PHP 4.3
– DOM extension part of PHP 5 core
• XSLT
– libxslt extension in PHP 5
– A separate XSLT extension available from
Sablotron C library (different API)
• SAX
– based on libxml2 library in PHP 5
PHP and XSLT
libxslt extension in PHP 5
<?php
// Load XML
$xml = new DomDocument;
$xml->load(“cdcatalog.xml”);
// Load the XSL
$xsl = new DomDocument;
$xsl->load (“cdcatalog.xsl” );
// configure xslt processor
$xslt = new Xsltprocessor;
$xslt->importStylesheet($xsl);
// Transform
echo $xslt->transformToXML($xml);
?>
PHP and XSLT
<!-- sablotron version -->
<?php
$processor = xslt_create ();
$result =
xslt_process($processor,„source.xml‟,„transform.xml‟);
if(!$result) echo xslt_error ($processor);
xslt_free ($processor);
echo “<pre>$result</pre>”;
?>
events-based XML
programming
• PHP has an event-based XML parser
• based on libxml2 library
– SAX parser
– replaces old non-SAX Expat library
• parser calls handler functions as events
occur
• you write the event handler functions
PHP strengths and
weaknesses
PHP strengths
• free, open-source product
– flexible
– extensible
• easy to implement
– builds onto most browsers on most platforms
– familiar, flexible and powerful syntax
• with occasional weirdness thrown in
• good database connectivity
– technology of choice for low-end web-DB
system
PHP weaknesses
• XML support
– some non-standard features still in PHP5
• slow because of runtime compilation then execution
– derives from CGI script origins
– PHP accelerator reduces this
• limited separation of coding from HTML
– no equivalent of JSP custom tags
– some open source versions emerging
• see http://trac.php-tools.net/
• extensibility limited by cumbersome C-based
architecture
– this is improving with later versions
PHP web application frameworks
• Frameworks are now emerging for PHP
• Cake
– Started in 2005 - Latest release 22 October2007
– Modelled on ruby for rails. Implements MVC
– growing developer community, growing functionality
– http://www.cakephp.org/
• Symfony
– Very recent but stems from older projects. Implements MVC
– Symfony 1.4 planned for Nov. 09
– established development community.
– http://www.symfony-project.com/
• Zend Framework (June 2006, currently v.1.0.3)
– growing community of developers
– provide components for the MVC
– http://framework.zend.com/
PHP web application frameworks
• software framework that support the
development of dynamic websites
• Typical functionality
– CRUD (database interaction)
• make database interfacing easier for the user
– M-V-C architecture
• Implement the MVC design pattern
– Access control lists
• come with authentication and authorization frameworks
– View helpers - AJAX, JavaScript, etc…
– Session & cookie management
– Standard application components/templates
• Promote code reuse
• Provide object-oriented design environment
Active Server Pages
(ASP)
Active Server Pages (ASP)
Microsoft-based server-side processing technology
• ASP provides a server-side scripting
environment.
• This includes:
Read information from an HTTP request.
Customize an HTTP response.
Interact with Databases.
Support complex middleware.
Active Server Pages (ASP)
• are processed in response to a client request
------ server-side scripting
• are processed by an ActiveX component
------ a scripting engine
• have the file extension .asp
• contain HTML tags and scripting code
• VBScript is the most widely used language
(although you can use JavaScript, other .NET
languages)
The ASP Architecture
ASP.DLL
• A user makes an http request for an ASP page.
• The .asp extension tells the Web server that the
page contains server script (executable code)
that it should process before returning the page
to the browser.
• The server passes the ASP to the scripting
engine
• The scripting engine executes ASP commands
as it encounters them
• After execution of the server scripts, all code is
stripped out of the page.
• The pure HTML page is sent in the http
reponse.
A Simple ASP Example
<% @LANGUAGE = VBScript %>
<% Option Explicit %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">
<% ' File : clock.asp %>
<HTML>
<HEAD>
<TITLE>A Simple ASP Example</TITLE>
<META HTTP-EQUIV = "REFRESH" CONTENT = "60;
URL=CLOCK.ASP">
</HEAD>
A Simple ASP Example
<BODY>
<H1>Simple ASP Example</H1>
<TABLE BORDER = "6">
<TR>
<TD><% =Time() %></TD>
</TR>
</TABLE>
</BODY>
</HTML>
ASP Built-in Objects
• Request
• Response
• Session
• Application
• Server
• ObjectContext
ASP Built-in Objects
• Request
– Retrieves the values that the browser
passes to the server during an HTTP
request.
• Response
– Controls what information is sent to a
browser in the HTTP response
message.
ASP Built-in Objects
• Session
– Used to manage and store
information about a particular user
session.
• Application
– Used to manage and store
information about the Web
application.
ASP Built-in Objects
• Server
– Provides access to resources that
reside on a server.
• ObjectContext
– Used to commit or abort a
transaction managed by Microsoft
Transaction Server (MTS) for ASP
pages that run in a transaction.
ASP Built-in Objects
Retrieve information passed from the browser
to the server using the Request object.
Send output to the browser using the
Response object.
Store information for a specific user using the
Session object.
Share information among all users of your
application using the Application object.
Work with the properties and methods of
components on the server using the Server
object.
Request Object Collections
• ClientCertificate
• Cookies
• Form
• QueryString
• ServerVariables
Form Collection
• The Form collection contains the values of each
standard HTML control that has a NAME attribute. When
a user submits a form with the POST method, you can
read the values of the controls by using the Form
collection.
• The Form collection of the Request object can
be used to extract information from the body of
an HTTP request message.
Form Collection
<FORM ACTION=“icecream.asp"
METHOD=POST>
Name: <INPUT TYPE=TEXT
NAME="name"><P>
Favourite Flavour:
<SELECT MULTIPLE NAME=“flavour">
<OPTION>Mint
<OPTION>Vanilla
<OPTION>Coffee
</SELECT><P>
<INPUT TYPE=SUBMIT NAME=“iceSubmit"
VALUE="Submit">
</FORM>
Form Collection
icecream.asp
Request.Form("name")
Request.Form(“flavour")
or
<% For Each Item in Request.Form
'code to display Item here
Next %>
ASP on Alternative Platforms
• Chili!ASP by Chili!Soft (Expensive to buy!)
• Windows
– IIS, Apache, Netscape Enterprise & FastTrack, O‟Reilly WebSite
Pro
• Solaris
– Apache, Netscape Enterprise & FastTrack
• Linux: Apache
• IBM AIX: Apache, Netscape Enterprise & FastTrack, IBM
HTTP Server, Lotus Domino Go
• HP UX
– Apache, Netscape Enterprise
ASP on Alternative Platforms
• Instant ASP (iASP) by Halcyon Software
• cheaper
• written in Java as a Servelet, so runs with
Apache/Tomcat and many other servers
• allows mix of ASP and JSP
– better range of functionality
– may run slow for high volume applications
ASP Strengths
• implements M-V-C
• code embedded in the HTML
– separation of concerns
• no compiling - stays resident in memory
• no complex interfacing - method calls
• suitable for high-end web applications
• standard components
– re-use
– eases programming effort
ASP weaknesses
• difficult to port between platforms
• steep learning curve for full functionality
– less suitable for low-end web apps
• multiplicity of .NET languages
– diffuse coding options
– can leave legacy problems
ColdFusion
ColdFusion
• Technology for building dynamic web
applications
• provides powerful markup reducing need
for programming skills
• designed for RAD: abstracts many low-
level tasks e.g. connection to a database
ColdFusion
• runs on all major platforms
• compatible with all major browsers
• runs in CGI mode or as an embedded
process
• runs on Apache, IIS, iPlanet
• ColdFusion applications are portable
across platforms with very minor
differences
History of ColdFusion
• developed by Allaire software
– first version 1995 - only 30 language
elements
– strongly tag-based, supplemented by
functions
• Allaire merged with Macromedia in 2001
– MacroMedia ColdFusion
– ColdFusion MX
• ColdFusion MX 6.1 (2004)
use and availability
• Widely used for medium to large scale
web apps
• Large developer community
• Not free, not open source
– ColdFusion MX Standard £929
• Windows, Linux
– ColdFusion MX Enterprise £4289
• Windows, Linux, Solaris, HP-UX, AIX
– 30-day free trial version (limited
functionality)
ColdFusion Basics
ColdFusion Markup Language
• tag-based language (CFML)
• mixed with HTML, JavaScript/VBScript in
a template
• CFML used to dynamically construct
content
• CFML processed by ColdFusion
Application Server on the server side
CFML
template
input
entity
http request
data
ColdFusion
web entity
client Application
server
Server
http response output entity
HTML
HTML
page
ColdFusion templates
• CFML tags embedded in HTML
– Can produce pure CFML pages
• Tag Syntax
– <CFTagname ... attributes ...> content
</CTTagName>
– or <CFTagname ... attributes .../>
• trailing / optional
– Attributes are literals or expressions
– Tags controlled by attributes and/or
content
Example 1
<!--- simple output of variable values --->
<h2>Writing output</h2>
<CFSET xy = x * y />
<CFOUTPUT>
x = #x#<br/>
y = #y#<br/>
x * y = #xy#<br/>
</CFOUTPUT>
Example 2
<HTML><head><title></title></head>
<BODY>
CFML tag
<CFOUTPUT>
<H2>Today‟s date is
#DateFormat (Now (),‟dd/mm/yy‟)#
</H2>
</CFOUTPUT>
</BODY>
</HTML>
closing CFML tag
Example 3
<CFMAIL
FROM = "jm@comp.rgu.ac.uk"
TO = "honsISD@comp.rgu.ac.uk"
SUBJECT = "Assessed Lab"
SERVER = "mailhost@comp.rgu.ac.uk"
>
Have a Merry Christmas.
</CFMAIL>
ColdFusion Web Application
Framework
web application
• a group of templates forming a cohesive
application
– maintain state
– utilise constants
– multi-threading
– error and exception handling
– security
• controlled through application
template
Application.cfm template
• reserved template name
• template placed in root directory of the
web application
– executed before every request
• may be supplemented by
OnRequestEnd.cfm template
– executed after every web request
processing Application
templates
• ColdFusion template requested
• ColdFusion searches template directory
for an Application.cfm template
– ColdFusion processes Application.cfm
template then requested template
– OnRequestEnd.cfm template processed if it
exists
template request process
Server
application
client template
request
myTemplate
response
onREquestEnd
function of Application.cfm
• maintains state
– create Application, Client and Session variables
• set application constants
– data-source names, source directories, style
elements
• handle errors
• provide security services
– user authentication
– entitlements
ColdFusion
strengths and weaknesses
strengths
• tag-oriented programming for web
developers
– good support for custom tags and
extensions
• full functionality to support medium to
high end web systems
• supports MVC
• strong support for thread-safe
transactions
• excellent database connectivity
weaknesses
• expensive compared with other
technologies
• not open source
• highly redundant syntax
– leads to inconsistent development
• idiosyncratic language structure
– limited code re-use on or from other
platforms
• non-standard and limited XML support
Get documents about "