UFCFV4-30-2 Data, Schemas & Applications

subduedjourneySoftware and s/w Development

Oct 28, 2013 (3 years and 10 months ago)

82 views

UFCFV4
-
30
-
2

Data, Schemas & Applications

Lecture
4

Server Side Scripting, PHP & XML

Last week:

o
encode data for communication


o
c
ard based

o
csv


o
tagged records

o
XML, xml vocabularies

o
xml processing vocabularies

o
xml namespaces

o
xml characteristics

o
rss

o
json

Processing
carried out on a web
server


o
SSI
-

Server
-
Side Include with some processing

o
Perl

o
PHP

o
Python

o
ASP (C#, VB, F# ..)

o
JSP

o
Ruby

o
XSLT

o
XQuery

o
Javascript

(with
jNode
)

Server
-
side languages

We
will be studying a number of different languages on this
module
because


o
Web development typically uses multiple languages

o
New languages are appearing all the time

o
Language design is evolutionary

o
Comparing the syntax and features of several languages
helps to understand computer languages in general


e.g
. How do different languages handle
Strings

Multiple languages

Processed by the web server

File suffix
-

shtml
..

Include a common file

<!
--
#include virtual="../quote.txt"
--
>

Execute a Unix command or
cgi

script and include the result

<!
--
#exec
cmd
="
ls

-
l"
--
>

<!
--
#exec
cgi
="/
cgi
-
bin/
foo.cgi
"
--
>

SSI (Server Side Includes)

PHP Origins

Originally created by
Rasmus

Lerdorf

(born Greenland,

educated
in Canada) around
1995


PHP originally abbreviated as ‘Personal Home Pages’, now
known
as
‘PHP Hypertext
Pre
-
processor



Other key developers:
Zeev

Surashi

and
Andi

Gutmans

(Israel)
responsible for PHP 3.0
-

a complete re
-
write of the original
PHP/F1 engine (1997)


PHP is Open Source software

First version PHP/FI released 1995

PHP 5.0 released July 2004

Current stable version is
5.5.5 (as of 16 October 2013)

PHP version
5.4.4
current at UWE

PHP Version 6 due for release since late 2010 but ??




PHP as a scripting language



o
A scripting language is:


often evolved not designed


cross
-
platform since interpreter is easy to port


designed to support a specific task


PHP Web support


un
-
typed variables (but values are typed)


implicit variable declaration


implicit type conversion


stored only as script files


compiled on demand


may run on the server (PHP, Perl) or the client (
Javascript
)


o
What are the potential differences in programming using an
interpreted scripting language like PHP in place of a compiled
language (e.g. Java in JSP, .NET)?


o
Free format
-

white space is ignored

o
Statements are terminated by semi
-
colon ;

o
Statements grouped by { … }

o
Comments begin with // or a set of comments /* */

o
Assignment is ‘=’: $a=6

o
Relational operators are ,< , > == ( not a single equal)

o
Control structures include if (
cond
) {..} else { }, while (
cond
) { .. } ,
for(
startcond
;
endcond
; i
ncrement)
{ }

o
Arrays are accessed with [ ]
-

$x[4] is the 5th element of the array $x


indexes start at 0

o
Associative Arrays (hash array in Perl, dictionary in Java) are accessed in
the same way: $y["
fred
"]

o
Functions are called with the name followed by arguments in a fixed order
enclosed in ( ) :
substr
("fred",0,2)

o
Case sensitive
-

$
fred

is a different variable to $FRED


C
-
like language

As of 31
st

January 2013,
Netcraft

reports PHP running on
well
over 200 million websites


PHP use statistics:

t
he http
request/response
cycle with
php



<!
DOCTYPE html>

<html>


<?
php


# declare a variable & assign it a value


$name =
"Popeye";

?>


<head>


<title>
PHP Simple Example
</title>

</head>


<body>


<p>
Welcome to PHP,
<?
php

echo
("$name");
?>
!
</p>

</body>


</html>

Simple PHP script example


s
ingle line comment, use # or //

v
ariable ($name) with value
assignment (‘Popeye’)

s
cripting delimiters

c
all to built
-
in ‘echo()’ function

v
iew script

run script

PHP is often used to generate HTML pages with dynamic
content. Here it is used like SSI. The
markup

<?
php

and ?> are
one way to delimit PHP code within HTML.

<html>


<head>


<title>Basic Page </title>


</head>


<body>


<h1>Basic Page</h1>


<p>Hello world</p>


<p>This page is different every time it is loaded </p>


<p>Current date/time is
<?
php

echo date("l, j M y H:i:s ")

?>

</p>


</body>

</html>

PHP ‘Hello World’

Run

Accessing URI parameters

<?
php




$
site = $_REQUEST["site"];



$
rawdatafile

= $site . "/clientraw.txt";



echo
$
rawdatafile
;

?>


o
PHP uses C conventions for assignment, statement separators, blocks etc.

o
PHP provides the parameters from the URI as an array of values.
$_REQUEST

o
arrays can be indexed by position or key value

o
Variables start with the character $

o
To join (concatenate ) strings use the . (dot) operator

Run

Form interface

A common approach would be to provide an HTML form to
allow the user to enter the parameters

<html>


<head>


<title>Form </title>


</head>


<body>


<h1>Form </h1>


<p>Current date <?
php

echo date("l, j M y H:i ") ?> </p>


<form method="get" action
=“
request_param.php
">


<label for="site">Enter the weather site URL</label>


<input type="text" name="site" />


<input type="submit" value="Get Weather"/>


</form>



</body>


</html>

Notice that when the
url

is entered into the form, the browser
url
-
encodes the
special characters.

Run

This
will be constructed along the
following workflow
lines, making use of user
-
defined functions (
udf’s
)


[
Get data
] >> [
Parse CSV
] >> [
Compute new data
] >> [
create RSS
]

Weather pipe RSS feed Replacement

Handling the proxy server

First we need to be able to fetch a data file. Because there is a proxy server at
UWE and because we don't want it to cache the data (why?), we need a bit of
magic.

<?
php


function
uwe_get_file
($
uri
) {


// get a file via UWE proxy and stop caching


$context =
stream_context_create
(


array('http'=>


array('proxy'=>'proxysg.uwe.ac.uk:8080',


'header'=>'Cache
-
Control: no
-
cache'



)


));


$contents =
file_get_contents
($
uri,false,$context
);


return $contents;

};

This defines a function which has one parameter, a
uri

and returns the file contents.
This is reusable for any file we want to get via HTTP running on a BIT server.

Arrays

The index values (keys) in PHP arrays are not restricted to
integers. They may also be strings and other kinds of values.
Similarly the value stored with a key can be any type of value
-

an integer
, string
or another array.

key
= "proxy" value = 'proxysg.uwe.ac.uk:80'

key = "header" value = 'Cache
-
Control: no
-
cache'

Arrays are like Dictionaries in Java , hash or associative
arrays in Perl.

Convert CSV string to an array of data

Now lets call the function to get the remote data file: The current
value of
$
rawdatafile

is passed to the function and becomes
the value of the parameter
$
uri

inside it.

$
csv

=
uwe_get_file
($
rawdatafile
);

Now split the string on the space character to get an array of strings which we can
access as an array.

$data = explode(" ", $
csv
);

Explode is a standard function in PHP
-

note the weird order of
parameters
-

the separator character first!

Mapping the array indexes

We could just refer to the array indexes as defined on the WDL
documentation
-

$data[4]
for temperature. A nicer way is
to define some names for these numerical indexes
(PHP
constants)

define ('WINDSPEED',1);

define
('WINDDIRECTION',3);
define('TEMPERATURE',4);

define
('STATION',32);

define
('TIMEHH',29);

define
('TIMEMM',30);

define
('SUMMARY',49);

Now we can use the more readable form $data[TEMPERATURE]
-

note there is no $ prefix with constants

Generate
the RSS

Now we can generate the RSS XML. Here we have lots of data to
interpolate into the RSS template and use a '
heredoc
' with
delimiter. Expressions are enclosed in { }

print <<<EOT

<?xml version="1.0"?>

<
rss

version="2.0">


<channel>


<title>{$data[STATION]}</title>


<link>{$site}</link>


<item>


<title>Weather at
{$data[TIMEHH]}:{$data[TIMEMM]}</title>


<description> {$data[SUMMARY]} . Wind
{$data[WINDSPEED"]} knots from {$data[WINDDIRECTION]}
degrees. Temperature {$data[TEMPERATURE]} &#0176;C.
</description>


</item>


</channel>


</
rss
>

EOT;

Mainline

Finally the main program defines the overall processing using
these functions. It is not a true pipeline because each step
executes fully and puts its output in a temporary variable.

Run

Source

Common code

The function to get a file via the proxy and will be used in any
application which needs to access a web resource from within UWE.
Similarly the code to define the structure of the
wdl

data will be used in
any script which access that data. We can put these in two separate files
(why two?) and then include them in the source of any program which
needs this code with the require() statement:

<?
php


require
("
commonlib.php
");
require("
wdllib.php
");



//main ...

Run

Source

o
interaction
between a client
-
side form and server
-
side
processing

o
variables and constants

o
functions transforming one or more inputs into an output

o
arrays with string keys as dictionaries or associative arrays

o
heredocs

o
setting a media
-
type

o
factoring out common code

Concepts