We typically use onload with the body element or window object.
Other Events
Event
Description
Attribute
focus
Occurs when a form field receives input.
onFocus
change
Occurs when an input is modified.
onChange
blur
Occurs when an HTML element loses focus.
onBlur
click
Occurs when an object is clicked.
onClick
keydown
Occurs when a users presses a key.
onkeydown
mouseOver
Occurs once each time the mouse pointer moves over an HTML element.
onMouseOver
select
Occurs when a users selects some of the text within an object.
onSelect
submit
Occurs when a user submits a form.
onSubmit
Creating Custom Events
When an event occurs, an event object, with methods and attributes, is created. We can make our own event objects which will be passed to event handler functions (not in IE).
In Internet Explorer we can access only the most recent event with window.event.
<html><bodyonKeyDown="processKey(event)"><script>functionprocessKey(e){e=e||window.event// this accommodates for IEdocument.getElementById("key").innerHTML=String.fromCharCode(e.keyCode)+'has been pressed '}</script><!-- key code will appear in the paragraph below --><pid="key"></p></body></html>
Inner function have access to the variables of outer functions.
By default, inner function can not be invoked from outside the function they are defined in.
functionbubble_sort(array){functionswap(i,j){vartmp=array[i];array[i]=array[j];array[j]=tmp;}if(!(array&&array.constructor==Array))throw("Argument not an array")for(vari=0;i<array.length;i++){for(varj=0;j<array.length-i;j++){if(array[j+1]<array[j])swap(j,j+1)}}returnarray}
JavaScript Libraries
JavaScript libraries can be imported to HTML using the following syntax:
<script src="url"></script>
Objects
Object Literals
Instead of having classes, JavaScript has object literals. They have the following syntax:
Member values can be accessed using dot notation or bracket notation:
person1.ageperson1['gender']
Object Constructors
We can use functions to act as object constructors like so:
functionSomeObj(){this.prop1='A'// public propertyvarprop2='B'// private propertythis.method1=function(){// public methodreturn'm1[prop1 = '+this.prop1+' prop2 2 = '+prop2+']'}varmethod2=function(){...}// private method}obj1=newSomeObj()obj2=newSomeObj()
Prototype Property
All functions have a prototype property that can hold shared object properties and methods:
Objects do not store their own copes of these properties and methods, but only store references to a single copy.
functionSomeObj(){this.prop1='A'// public propertyvarprop2='B'// private propertySomeObj.prototype.method1=function(){...}// public prototypevarmethod2=function(){...}// private method
These can be edited during runtime to change the behaviour of a set of objects.
Class Variables & Methods
Function properties can be used to emulate Java’s class variables & methods (static variables shared among instances).
functionCircle(radius{this.r=radius}// class variable - property of the Circle constructor functionCircle.PI=3.14159// instance methodCircle.prototype.area=function(){returnCircle.PI*this.r*this.r;}// class method - property of the Circle constructor functionCircle.max=function(cx,cy){if(cx.r>cy.r){returncx}else{returncy}}c1=newCircle(1.0)// create an instance of the Circle classc1.r=2.2// set the r instance variablec1_area=c1.area()// invoke the area() instance methodx=Math.exp(Circle.pi)// use the PI class variable in a computationc2=newCircle(1.2)// create another Circle instancebigger=Circle.max(c1,c2)// the the max class method
Private Static Variables
In order to create private static variables shared between objects we can us a self-executing anonymous function:
varPerson=(function(){varpopulation=0// private static class variablereturnfunction(value){// constructorpopulation++varname=value// private propertythis.setName=function(value){returnname}this.getName=function(){returnname}this.getPop=function(){returnpopulation}}}())person1=newPerson('Peter')person2=newPerson('James')
Pre-Defined Objects
String
A String object encapsulates the values of the primitive datatype string.
Properties of String include:
length - The number of characters in the string.
Methods of String include:
Method
Description
charAt(index)
Returns the character at position index, starting at 0.
substring(start, end)
Returns the part of a string between positions start and end inclusive.
toUpperCase()
Returns a copy of a string with all the letters in uppercase.
toLowerCase()
Returns a copy of a string with all letters in lowercase.
RegExp
JavaScript supports perl-like regular expressions. String object have methods that use regular expressions:
Method
Description
search(regexp)
Matches regexp witha string and retursn the start position of the first match, or -1 if there is no match.
match(regexp)
Without g, returns the matching groups for the first match. With g, returns an array containing all the matches for the whole expression. Returns null if no match is found.
replace(regexp, replacement)
Replaces matches for regexp with replacement and returns the resulting string.
Date
The Date object can be used to access the local date and time.
It supports the following constructors:
newDate()// current date and timenewDate(milliseconds)// set date to unix millisnewDate(dateString)// set date according to dateStringnewDate(year,month,day,hours,min,sec,msec)
Date also provides the following methods:
Method
Description
toString()
Returns a string representation of the Date object.
getFullYear()
Returns a four digit string representation of the current year.
parse()
Parses a date string and returns it in unix millis.
JavaScript is a language for client-side programming.
Hello, world!
<!DOCTYPE html><htmllang="en-GB"><head><title>Hello, world!</title></head><body><script>document.writeln("<p><b>Hello, world!</b></p>");</script><noscript><p><b>Please enable JavaScript to see the super secret message!</b></p></noscript></body></html>
Script is enclosed in script tags.
Alternative HTML is enclosed in noscript tags.
Types
JavaScript is a dynamically and loosely typed language. It has five different types:
boolean
number
This is both integers and floating point numbers are treated the same.
We can use the Math object (Math.log()) to do mathematical functions.
string
function
object
We can find the type of an object like so:
document.writeln("Type of 23.0: "+typeof(23.0));
Typecasting
We can cast types by wrapping them in an appropriate object from:
Number()
String()
Boolean()
We can also process specifically as an int or float:
parseInt()
parseFloat()
Strings
We can write strings like so:
document.writeln("Your name is "+name+"and\
you are studying "+degree+"\
at "+university);
Variables
Variables can be declared like so:
varvariable1=value,variable2=value2,...
If you don’t initialise a variable before using it you will get a reference error.
The PHP Data Objects (PDO) extension defines an interface for accessing databases in PHP.
Connections
We create a connection to the database server by creating an instance of the PDO class. We can use the following constructor to this:
$pdo=newPDO(dsn,username,password,options);
The connection remains open for the lifetime of the object. Therefore, we can close the connection by running the following:
$pdo=NULL
A full example would look like so:
# Connection information for the Departmental MySQL Server$host="studdb.csc.liv.ac.uk";$user="sgfsurn";# your University username$passwd="-------";# your MySQL server account password$db="sgfsurn";# your University username$charset="utf8mb4";$dsn="mysql:host = $host; dbname = $db; charset = $charset ";# Useful options$opt=array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC,PDO::ATTR_EMULATE_PREPARES=>false);try{$pdo=newPDO($dsn,$user,$passwd,$opt);}catch(PDOException$e){echo'Connection failed: ',$e->getMessage();}
Queries
The query() method of PDO object can be used to execute an SQL query:
$result=$pdo->query("SELECT * FROM meetings");
The exec() method of PDO objects executes an SQL statement, returning the number of roes affected by the statement:
$rowNum=$pdo->exec("DELETE * FROM meetings");
Processing Result Sets
Getting results in this way can leave the server open to SQL injection attacks. You should use prepared statements instead.
fetch()
To get a single row as an array from a result set stored in a PDOStatement object, we can use the fetch() method.
By default, PDO returns each row as an array indexed by the column name and a 0-indexed column position in the row:
fetch() uses a cursor that moves through the rows in a result set and does not reset at the end. You should store the result set in an array first, then iterate over the array as often as you like.
bindColumn()
We can bind a variable to a particular column in the result set of a query:
Columns can be specified with a number (indexed at 1).
By default PDO runs in auto-commit mode. To execute a sequenc of SQL statements atomically then you must use the following commands to construct a transaction:
beginTransaction()
Turns off auto-commit mode. Changes to the database are not commited until commit() is called.
Returns TRUE on success or FALSE on failure.
Throws an exception if another transaction is already active.
commit()
Changes to the database are made permanent and auto-commit mode it turned back on.
Returns TRUE on success or FALSE on failure.
Throws an exception if no transaction is active.
rollBack()
Discards the changes to the database and re-enables auto-commit mode.
Returns TRUE on success or FALSE on failure.
Throws an exception if no transaction is active.
Here is an example for transferring money from one account to another:
$balance=array();// this function stores a key-value pair to a global array called balancefunctionstoreBalance($id,$b){global$balance;$balance[$id]=$b;}$pdo=newPDO('mysql:host=...; dbname=...','...','...',array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_EMULATE_PREPARES=>false));try{// Details of the transaction: payer, payee, amount$payerId=1;$payeeId=2;$paymentAmount=10.50;$pdo->beginTransaction();// Obtain payee's and payer's account balances and lock access to both records$sql1="select id, balace from accounts where id=? or id=? for update";$stmt=$pdo->prepare($spq1);$stmt->execute(array($payerId,$payeeId));// store the data retrieved from the database in the $balance array$smt->fetchAll(PDO::FETCH_FUNC,'storeBalance');// Check whether there is enough money in the payer's accountif($balance[$payerId]<$paymentAmount){echo"Insufficient funds in payer's account";}else{$sql="UPDATE account SET balance = balance + ? WHERE id = ?";$stmt=$pdo->prepare($sql);// Increase balance of payee's account by payment ammount$stmt->execute(array($paymentAmmount,$payeeId));// Decrease balance of payer's account by payment ammount$stmt->execute(array(-$paymentAmount,$payerId));}// Commit the transaction (whether money was transferred or not)$pdo->commit();}catch(PDOException$e){echo"Error: ",$e->getMessage(),"<br>\n";// roll back the transaction$pdo->rollBack();}
Properties and methods can have the following visibilities:
public - Accessible everywhere.
private - Accessible only within the same class.
protected - Accessible only within the class itself, by inheriting and parent classes.
Properties require a visibility declaration whereas, by default, methods are public.
Constants
Classes can have their own constants. By default they are declared public:
Class constants are allocated once per class and not for each class instance.
Class constants are accessed using the scope resolution operator:::
classMyClass{constSIZE=10;}echoMyClass::SIZE;# prints 10$o=newMyClass();echo$o::SIZE;# prints 10
Destructors
A class can have a destructor method that is called as soon as there are no references to a particular object:
classEmployee{static$totalNumber=0;public$name;function__construct($name){$this->name=$name;Employee::$totalNumber++}function__destruct(){Employee::$totalNumber--;}}$e1=newEmployee("Ada");$e2=newEmployee("Ben");echoEmployee:$totalNumber# prints 2$e1=null;echoEmployee::$totalNumber# prints 1
Inheritance
Inheritance can be implemented like so:
classRectangle{protected$height;protected$width;function__construct($height,$width){$this->height=$height;$this->width=$width;}functionarea(){return$this->width*$this->height;}}classSquareextendsRectangle{function__construct($size){parent::__construct($size,$size);}}$rt=newRectangle(3,4);echo"\$rt1 area = ",$rt1->area(),"\n";$sq1=newSquare(5);echo"\$sq1 area = ",$sq1->area(),"\n";
$rt1 area = 12
$sq1 area = 25
The constructor of the parent class is not automatically called. It must be called explicitly from the child class.
Inherited constants, properties and methods can be overridden by re-declaring them with the same name defined in the parent class.
The declaration final can be used to prevent a method from being overridden.
Using parent:: it is possible to access overridden methods or static properties of the parent class.
Using self:: it is possible to access static properties and methods of the current class.
Interfaces
Interfaces specify which methods a class must implement, without providing an implementation:
As no data about a client is remembered by default we can’t track a series of requests from coming from the same user. This can be problematic if we want to send several forms, such as on a shopping site.
Hidden Inputs
One way of solving this is by sending the data from the last form along with the next using a hidden input:
As we use $_REQUEST['item'] we can manipulate this value using process.php.
The user is able to modify these hidden fields if they want to act maliciously.
Sessions
This is a way of keeping track of a user’s session by using a session identifier which is:
Generated by the server, when the session starts.
Remembered by the browser.
Sent by the browser with every further HTTP request to that server.
Forgotten by the browser when the session ends, or the browser is closed.
In addition, the server can use session variables for storing information that relate to a session.
Session variables only store data temporarily. to preserve data between visits then you need to use a persistent cookie or a database.
Sessions vs. Cookies
Sessions:
ID and session data are stored on the web server.
Access and changes to session data are done in PHP via the $_SESSION array.
Expiration cannot be set; it always expires when the user’s close the browser or the session is ended by a script.
The client can’t manipulate the data.
Cookies:
ID and cookies data are stored by the web client on the user’s device.
Acess to cookie data is done in PHP via the $_COOKIE array.
Changes to cookie data are done in PHP via setcookie.
Expiration can be set via setcookie too.
Web client can be manipulated.
This can be used as an attack vector.
Session Method
Creating and using sessions uses the following method:
Start the session:
session_start()
session_id([id])
session_regenerate_id([delete_old])
Maintain session data:
session_start()
The $_SESSION array.
isset($_SESSION[key])
End a PHP session:
session_destroy()
$_SESSION = array();
session_unset()
setcookie(name, value, expires, path)
Starting a Session
session_start()
session_start()
Creates a session identifier when a session is created:
Sets up the $_SESSION array that stores session variables and session data.
The function must be executed before any other header calls or output is procured.
session_id()
session_id([id])
Get or set the session id for the current session:
The constant SID can also be used to retrieve the current name and session id as a string suitable for adding to URLs.
session_name()
session_name([name])
Returns the name of the current session:
If a name is given, the current session name will be replaces with the given one and the old name returned.
session_regenerate_id()
session_regenerate_id([delete_old])
Replaces the current session id with a new one:
By default keeps the current session information stored in $_SESSION.
If the optional boolean argument is true, then the current session information is deleted.
Regular use of this function alleviates the risk of a session being hijacked.
Maintaining Session Data
We can use the following methods:
session_start()
The $_SESSION array.
isset($_SESSION[key])
like so:
<?php// counting the number of page requests in a session// each web page contains the following PHP codesession_start();if(!isset($_SESSION['requests']))$_SESSION['requests']=1;else$_SESSION['requests']++;echo"#Requests in this session so far: ",$_SESSION['requests'],"<br>\n";?>
Ending a Session
We can end a session like so:
<?session_start();session_unset();if(session_id()!=""||isset($_COOKIE[session_name()]))// force the cookie to expiresetcookie(session_name(),session_id(),time()-2592000,'/');session_destroy();?>
You should only end the session if the operation is successful. This saves losing all existing.
Close on Inactivity
The following code tracks whether a session is active and end the session if there has been no activity for more than 30 mins:
We can also use this same construct to make the session identifier change every 30 mins1:
if(!isset($_SESSION['CREATED'])){$_SESSION['CREATED']=time();}elseif(time()-$_SESSION['CREATED']>1800){// session started more than 30 minutes agosession_regenerate_id();$_SESSION['CREATED']=time();}
Session Examples
There is an improved example of the “hidden inputs” example from above using session variables [starting at slide 16]https://liverpool.instructure.com/courses/46944/files/6811254?module_item_id=1325181).
There is also a PRG (POST, redirect; GET) example with sessions starting at slide 19.
date('H:i l, j F Y')// 12:20 Thursday, 8 March 2022time()// Unix time in seconds
PHP Environment
phpinfo([part])
Displays information abou the PHP installation and EGPCS data (environment, GET, POST, cookie and server data).
The optional part argument can take the following options to only display certain information:
INFO_GENERAL - The configuration, php.ini location, build date and web-server.
INFO_CONFIGURATION - Local and master vales for PHP directives.
INFO_MODULES - Loaded modules.
INFO_VARIABLES - All EGPCS data.
Manipulating the PHP Configuration
The following function can be used to access and change the configuration of PHP from within the PHP script:
Function
Description
ini_get_all()
Returns all the registerd configuration options.
ini_get(option)
Returns the value of the configuration option option.
ini_set(option, value)
Sets the value of the given configuration value. The configuration option will keep this new value during the script’s execution and will be restored after.
ini_restore(option)
Restores a given configuration option to its original value.
We can use this to show errors in the HTML output:
<htmllang='en-GB'><head></head><body><? php
ini_set('display_errors', 1);
error_reporting(E_ALL | E_STRICT); // choose one
echo '<p>The value of 1 divided by 0 is ' , 1/0 , '</p >';
?></body></html>
Server Variables
The superglobal $_SERVER array stores information about the web-server and the client request.
The form data is passes to a PHP script via three superglobal arrays:
Variable
Description
$_POST
Data from the POST client requests.
$_GET
Data from the GET client requests.
$_REQUEST
Combined data from POST and GAT client requests. Equivalent to cgi.FieldStorage() in Python CGI.
We can access data by the name:
$_REQUEST['username']
String Functions
The following functions could be useful when processing form data:
Function
Description
strtolower(str)
Returns a string will all alphabetic characters in str converted to lower-case.
substr(str, start [,length])
Returns the portion of the string str starting at position start and consisting of at most length characters. If start is negitive, the returned string will start at the start‘th character from the end of the string.
date(format, [,timestamp)
Returns a string formatted according to the given format string format using the given timestamp or the current time if no timestamp is given.
HTML Form Example
There is a full example for generating and processing a HTML form using PHP starting at slide 14
The following form is used:
POST, Redirect, GET (PRG)
As we used a POST request, if a person refreshes the page, this can resend the request giving unwanted side effects.
This design pattern requires that we:
Redirect to a results page after a POST request.
There is an example of extending the original form with this functionality starting at slide 21
PHP uses PCRE (Perl-compatible regular expressions). You can try out your expressions in a live environment at regex101 (ensure that PCRE2 is checked).
PHP RE Syntax
We can use the following syntax to define regular expressions in PHP:
'/a*bc/'
The expression is enclosed in two /.
Quantifiers
We can request a certain number of characters:
Quantifier
Description
*
Match 0 or more times.
+
Match 1 or more times.
?
Match 1 or 0 times.
{n}
Match exactly $n$ times.
{n,}
Match at least $n$ times.
{n,m}
Match between $n$ and $m$ times.
These quantifiers are greedy:
Match the longest leftmost sequence of characters possible.
We can match lazily by following a quantifier with a ? character:
'=/\*.*?\*/='
Any non-whitespace, non-backslash character can be a regex delimiter. = is used here for convenience.
this would match:
x = /* one */ y*z; /* three */
as opposed to the following using a greedy expression:
x = /* one */ y*z; /* three */
Capture Groups & Back-references
We can capture groups and use them with backreferences like so:
"=<(?<c1>\w+)>/*?</\g{c1}>="
This captures a group of w+ called c1 and uses it later using \g{c1}.
This would match the whole string:
"<li><b>item</b></li>"
Available syntax includes:
Expression
Description
(regex)
Creates a capturing sub-pattern and automatically names starting from 1.
(?<name>regex)
Creates a named capturing sub-pattern.
(?:regex)
Creates a non-capturing sub-pattern.
\N, \gN, \g{N}
Back-reference to a capturing pattern called $N$, where $N$ is a natural number.
\g{name}
Back-reference to a named capture group.
(?:regex) is used to enclose alternations without making another capture group:
"/(?:regex1|regex2)/"
Modifiers
Usually we might enclose our regular expression in //. We can use the following modifiers to match in different ways like so:
"/hello/i"
This performs a case-insensitive match.
Modifier
Description
i
Perform case-insensitive match.
s
Treat multiline string as a single line.
m
Treat string as a set of multiple lines (multi-line mode).
You can combine these modifiers one after the other.
Arrays are not sorted so the values are returned in insertion order.
In order to change the values of an array using a for each loop you need to use a reference (&):
foreach($arr6as$key=>&$value){// note the &$value.=" - modified";}
This is required, otherwise a copy will be modified.
Unsetting the pointier is required to remove the structure from memory.
You can’t change the key, only the value.
Array Assignments
PHP uses copy-on-write for array assignments. This means that if you create a copy of an array:
$arr2=$arr1;
they are treated as a reference to eachother (this saves the memory of writing it twice).
When one is changed:
$arr2[1]+=1000;
then the other copy is written to memory.
This means that $arr2 is no longer a pointer to $arr1 and is now its own array.
If you explicitly want a reference then you can do the following:
$arr2=&$arr1;
This will create an alias for the same array.
Array Operators
PHP has no stack or queue datastructures. We can use the following functions with arrays to emulate these features:
Function
Description
array_push(&$array, value1, value2, ...)
Appends one, or more, elements at the end of an array. Returns the number of elements in the resulting array.
array_pop(&$array)
Extracts the last element from an array and returns it.
array_shift(&$array)
Extract the first element of an array and returns it.
array_unshift(&$array, value1, value2, ...)
Inserts one or more elements at the start of an array variable. Returns the number of elements in the resulting array.
Printing
In PHP the default command for generating output is echo:
echo(arg1);echoarg1,arg2,...
No brackets are allowed if there is more than one argument.
This method is more efficient that printf so should be used when possible.
Additionally there are also the functions print and printf:
Function
Description
print(arg)
Takes one argument only and returns value 1. Brackets can be omitted.
printf(format, arg1, arg2, ...)
Produces output according to format. Returns the length of the output string.
sprintf(format, arg1, arg2, ...)
Returns a string produced according to the format.
vprintf(format array)
Same as printf by accepts an array instead of comma separated values.
vsprintf(format, array)
Same as sprintf and vprintf.
NULL
A variable can have the value and type of NULL in the following situations:
The variable has not yet been assigned a value.
The variable has been assigned the value NULL.
The variable has been unset.
You can use the following function to sets whether a variable is NULL:
Function
Description
isset($variable)
True if $variable exists and does not have value NULL.
is_null(expr)
True if expr is identical to NULL.
Empty arrays are only loosely (==) equal to NULL but not identical (===).
Resources
A resource is a reference to an external file. We can use the following functions:
Function
Description
fopen(filename, mode)
Returns a file pointer for filename on success, false on error.
fclose(resource)
Closes the resource. Returns true on success.
fgets(resource [, length])
Returns a line read from resource and returns false if there is no more data to read. length can be used to read the first $n$ characters, or until the end of the line.
fread(resource, length)
Returns length charactesr read from resource.
fwrite(resource, string [, length])
Writes a string to a resource. If length is given, writing stops after length bytes, or the end of the string.
fprintf(resource, format, arg1, arg2, ...)
Same as printf with output to resource.
vfprintf(resource, format, array)
Same as vprintf with output to resource.
We can use the following modes:
Mode
Operation
Create
Truncate
r
Read File
r+
Read/Write File
w
Write File
Y
Y
w+
Read/Write File
Y
Y
a
Append File
Y
a+
Read/Append File
Y
x
Write File
Y
x+
Read/Write File
Y
Here are some common file operations:
$handle=fopen('somefile.txt','r');while($line=fgets($handle)){// processing each line}fclose($handle);
The input element represents a field that allows the user to enter data of a certain type.
The input element is a void element.
The type attribute of an input element determines what type of data can be entered and in what form.
Value of Type
Data Type
Form Control
text
Text with no line breaks
Text field.
number
Floating-point number.
Text field or spinner.
password
Password
Text field with obscured input.
button
Button
submit
Initiates form submission.
Button
reset
Resets the form.
Button
You can use them like so:
<inputtype="text"><inputtype="reset">
Common attributes of input elements include the following:
Attribute
Description
id
A unique id used to identify the element within the document.
name
A unique name used by the form processor to access input.
autofocus
Automatically focus on this form control when the page is loaded.
disabled
Whether the form control is disabled.
required
Whether the form control is required to have a non-empty value for form submission.
Labels
In order for a form to be readable, each form control should be accompanied by an indication of what it is. A label element is a caption the can be associated with a specific form control.
We can then use the following python to make the form:
defprintForm():print('''\
<form action='generate.py' method='post'>
<label>
Enter your full name:
<input type='text' name='fullname'>
</label>
<label>
Select your year of registration:
<select name='year' required>
<option value=''>
----
</option>''')now=datetime.datetime.now()foryearinrange(now.year-9,now.year+1):print('<option>',year,'</option>')print('''\
</select>
</label>
<input type='submit' name='submit' value='Generate'>
</form>''')
Generating Username
We can use the following function to generate a username:
defgenUsername(name,year):# first letter of given name/names
return("sg"+name.split()[0][0].lower()# first three letter of surname
+name.split()[-1][:3].lower()# last two digits of year
+str(year)[2:4])
Wrapper Script
#!/usr/bin/python3
# generate.py
importos,sys,codecs,datetime,localefromhtmlUHimportstart_html,end_htmlstart_html("Generate Username")if(os.environ["REMOTE_ADDR"][0:7]!="138.253"):print('<div><b>Sorry, please come back when you are on a uni computer</b></div>')else:inputs=cgi.FeildStorage()ifinputs.getvalue('submit'j):# form has been completed and submitted
name=inputs['fullname'].valueyear=inputs['year'].valueusername=genUsername(name,year)print('<div>The username for '+name+' registerd in '+year+' is '+username+'</div>')else:# show user the form
printForm()end_html()
Common gateway interface illustration - https://www.oreilly.com/library/view/cgi-programming-on/9781565921689/04_chapter-01.html ↩
Scripts are user-readable and user-modifiable programs that perform simpler operations and control the operation of other programs.
They have the following properties:
Program code is present at run time and the starting point of execution:
Compilation is not needed.
Compilation to intermediary languages may be performed behind the scenes as an optimisation.
Presences of a suitable runtime environment is required for thee execution so scripts:
Includes one of:
Interpreter
Just-In-Time Compiler
Byte-code Compiler
and a virtual machine.
Execution of scripts is typically slower than the execution of code that has been fully pre-compiled.
Rich and easy to use interface to the underlying operating system in order to run other programs and communicate with them.
Rich I/O including:
Pipes
Network Sockets
File I/O
Easy integration with larger systems:
Often used to glue other systems together.
Can be embedded into other applications.
Language Constructs
Variables, functions, and methods typically do not require type declarations. Automatic conversion between types:
Strings and numbers.
Lots of pre-defined functions and libraries.
Lots of pre-defined functions for the specific purpose the language was designed for.
Ability to generate, load, and interpret source code at run time through an eval function.
This can lead to self modifying and running code like the following:
varx=2;vary=6;varstr=" if ( x > 0) { z = y / x } else { z = -1 }";console.log(' z is ',eval(str));// Output : z is 3x=0;console.log(' z is ',eval(str));// Output : z is -1
Language Evolution
The evolution of a scripting language typically starts with a limited set of languages constructs for a specific purpose:
PHP started as a set of functions for tracking web visits.
The language then accumulates more and more language constructs as it is used for a wider range of purposes:
These additional language constructs may or may not fit well together with the original core and may duplicate existing language constructs.
During this evolution of the language, backward compatibility may or may not be preserved.
Language design of scripting languages is often sub-optimal.