0% found this document useful (0 votes)
32 views

Chapter 1 Scripting

Uploaded by

KUEK BOON KANG
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Chapter 1 Scripting

Uploaded by

KUEK BOON KANG
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 76

CHAPTER 1

SCRIPTING

1
ORIGINS OF SCRIPTING

• The creation of batch files containing a group of operating


systems commands to be carried out
• Not meant as general purpose languages, but to glue
together sequences of actions and automate tasks
• Over time, these scripting languages evolved to become as
capable as “real” programming languages
2
TYPES OF SCRIPTING LANGUAGES
•To glue
together a
Shell sequence of
scripting OS
commands to
•be
To carried
create out
Web
client-side
scripting web pages
and server-
Extensio •side scripts
To control
n and extend
applications
languag (e.g.
VBScript)
3

e
SCRIPTING LANGUAGES

4
COMMON SCRIPTING LANGUAGES ON WEB

• CLIENT-SIDE:
• JAVASCRIPT

• SERVER-SIDE:
• PHP
• JSP
• ASP
• COLDFUSION
• RUBY
5
SCRIPTING VS APPLICATION LANGUAGES
• Usually interpreted (not compiled)
• Trade-off performance for expressiveness 表现力与性能的权衡
• Encourage rapid prototyping and development
• Tend to be weakly typed [dynamic typing]
▪ Type-checking is done dynamically (at run time)

6
7
ADVANTAGES OF STRONG TYPING
Catch errors • Can catch errors at compile time
earlier

More • Can make large code bases more manageable


manageable code

Clearer code • Clarify how things are used

More efficient • Compiler can use type information to generate more e fficient code
code
8
ADVANTAGES OF WEAK TYPING

• No a-priori restrictions 先验限制


• Easier to “hook things together”
▪ E.g., In Unix shell commands, everything is just a string
• Encourages code re-use
• Don’t need different interfaces for di fferent types
• More succinct 简洁 code
9
2 TYPES OF WEB DEVELOPMENT SCRIPTING

•Scripts that run within your web browser –


Client-side scripting no interaction with a web server is required
for the scripts to run

Server-side scripting
•Scripts run on the web server, which then
sends results to your web browser
10
WEB PAGES
• A web page is just a text file that is marked up (surrounded) by
HTML code
• The HTML markup (called tags) provide guidelines to a browser
for displaying the content
• Files containing HTML tags must always be named with
the .HTML extension
11
SERVER-SIDE PAGES

• Example of files that contain HTML + programming


code: .php (PHP: hypertext preprocessor), .js
(node.js), .jsp (java server pages), .aspx (Microsoft active
server pages).
• The programming code in these files is executed on the server
side and all you would see on the client side is the HTML output

12
SCRIPTIN
G

13
A PHP FILE MAY CONTAIN

• HTML
• PHP tags
• PHP statements
• Whitespace
• Comments

14
COMBINING HTML AND PHP

• To use PHP, HTML and JavaScript in the same document:


❑Ensure all PHP statements are enclosed by PHP start and end tag
❑Save the file with a .php extension
• When the web server receives the request for a PHP page, it
scans the page looking PHP code and then runs any PHP code
it finds

15
PHP CODE BLOCKS

<?php Standard PHP script


delimiters
// statements
?>

PHP requires all statements to end with a semicolon (;)

16
ASSESSING & INTERPRETING PHP
PAGES

Extracted from http://www.hosting.vt.edu/tutorials/phpmysql


17
DISPLAYING OUTPUT

⚫ You can provide comma-separated strings for the echo()


function
⚫ The print() function requires that you provide one string
argument; therefore, to work with multiple strings, you must
use the string concatenation operator (.)
18
USING COMMENTS WITH PHP
SCRIPTS
<?php
// this is a comment
# this is also a comment
/* this is a
multiline comment */
?>
19
NAMING VARIABLES
• Must begin with a dollar sign ($)
• May contain uppercase and lowercase letters, numbers or
underscores (_)
• The first character after the dollar sign must be a letter
• Cannot contain spaces
• Are case sensitive
20
DISPLAYING VARIABLES
• Pass the variables to the echo statement as individual
arguments, separated by commas:
echo “<p>city is ”, $city, “.</p>”;
• Or, include the variable names inside a text string (must use
double quotes instead of single quotes in this case):
echo “<p>city is $city</p>”;

21
SINGLE-QUOTED & DOUBLE-QUOTED STRINGS

• Single-quoted strings
• Preserves its content as it is
• Does not interpret escape sequences
• Double-quoted strings
• Performs variable substitution (or variable evaluation)
• Interprets all escape sequences (e.g. \n)

22
PHP NUMERIC OPERATORS
• Similar to Java

23
DEFINING CONSTANTS
• Constant names do not begin with a dollar sign ($)
• Use the define() function. Syntax:
define(“constant_name”, value);
• Examples:
define(“DEFAULT_LANGUAGE”, “English”);
define(“PI”, 3.14159);

24
DECLARING ARRAYS WITH NUMERICAL INDEX

• Syntax for array() construct:


$array_name = array(values);

• Example:
$states = array(“Penang”, “Perak”, “Johor”);

25
ALTERNATIVE WAY TO CREATE ARRAYS

• Use the array name and brackets


• Example:
$states[] = “Penang”;
$states[] = “Perak”;
$states[] = “Johor”;
▪ Each value is assigned to the $states array as a new element using
the next consecutive index number.
26
DEFINING FUNCTIONS
• Syntax:
<?php
function function_name(parameters) {
statement(s);
}
?>
• The function may contain a return statement
27
FUNCTIONS: EXAMPLE
<?php
function calcAvg($a, $b, $c) {
$sum = $a + $b + $c;
$average = $sum / 3;
return $average;
}
?>
• Function call example:
$result = calcAvg(1, 2, 3);
28
PASSING PARAMETERS BY REFERENCE

<?php
function increment(&$count) {
++$count;
}
?>

29
DECLARING GLOBAL VARIABLES
• Global variables must be declared with the global keyword inside a
function definition to make the variable available within the scope of the
function
<?php
$globalVariable = “global variable”;
function scopeExample() {
global $globalvariable;
echo “<p>$globalvariable</p>”;
}
?>
30
PHP’S BUILT-IN FUNCTIONS

• PHP has an extensive library of built-in functions to


manipulating strings, numbers, arrays, dates, etc.
• For more details, refer to
o http://php.net/manual/en/indexes.functions.php

31
MAKING DECISIONS
• Similar to Java:
• if statement
• if..else statement
• switch statement

Plus the if..elseif statement

32
REPEATING CODE
• PHP’s loop statements are similar to Java’s:
• while statement
• do..while statement
• for statement

33
foreach STATEMENT
• Used to iterate through the elements in an array
• Syntax:
foreach ($array_name as $variable_name) {
statement(s);
}
$weekdays = array(“MON”,“TUE”,“WED”,“THU”,“FRI”);
foreach ($weekdays as $day) {
echo “<p>$day</p>”;
}
34
ASSOCIATIVE ARRAYS 关联数组
• Use any alphanumeric keys for the array elements
• Specify an element’s key by using the array operator => in the
array construct
• Syntax:
$array_name = array(key => value, …);

35
DECLARING ASSOCIATIVE ARRAYS
$capitals = array(
“MALAYSIA” => “KUALA LUMPUR”,
“FRANCE” => “PARIS”,
“SOUTH KOREA” => “SEOUL”
);
or
$capitals[“MALAYSIA”] = “KUALA LUMPUR”,
$capitals[“FRANCE”] = “PARIS”,
$capitals[“SOUTH KOREA”] = “SEOUL”;
36
Chapter1Example1 NetBeans Project

demoarray.php
• Run this file (Shift-F6)
• Review and discuss the code with a friend

37
THE list() CONSTRUCT

• The list() construct may be used for retrieving values from


an array as follows:
<?php
$colors = array("red","blue","green");
list($red,$blue,$green) = $colors;
// $red="red", $blue="blue", $green="green"
?>

38
RETURNING MULTIPLE VALUES USING list()

<?php
function retrieve_user_profile() {
$user[] = “Zoe";
$user[] = “[email protected]";
$user[] = “English";
return $user;
}
list($name, $email, $language) = retrieve_user_profile();
echo "name: $name, email: $email, preferred language:
$language";
?>
39
MULTIDIMENSIONAL ARRAYS
Example for creating a 2D array:

$products = array(
array("tir", "tires", 100),
array("oil", "oil", 10),
array("spk", "spark plugs", 4)
);

40
ARRAYS & STRINGS
• explode() - converts a string to array
• implode() – converts an array to string
Example:
$s1 = "Mon-Tue-Wed-Thu-Fri";
$dayArray = explode ('-', $s1);
$s2 = implode (', ', $dayArray);
// $s2 = “Mon, Tue, Wed, Thu, Fri”
echo '<p>$s1: ', $s1;
echo '<br />$dayArray: ', print_r($dayArray);
echo '<br />$s2: ', $s2;
echo '</p>';

41
SORTING ARRAYS
• sort(array_name)
o sorts the elements in the array into alphabetical order
o is case sensitive - capital letters before lowercase letters
o example:
sort($products);
• rsort(array_name)
o sorts the array elements in reverse order

42
SUPERGLOBALS
• PHP includes various predefined global arrays, called
autoglobals[duplicate] or superglobals
• These arrays contain client, server, and environment
information that you can use in your scripts
• Superglobals are associative arrays

43
PHP AUTOGLOBALS
Array Description
$_COOKIE An array of values passed to the current script as HTTP cookies
$_ENV An array of environment information
$_FILES An array of information about uploaded files
$_GET An array of values from a form submitted with the GET method
$_POST An array of values from a form submitted with the POST method
$_REQUEST An array of all the elements found in the $_COOKIE, $_GET, and
$_POST arrays
$_SERVER An array of information about the Web server that served the current
script
$_SESSION An array of session variables that are available to the current script
$GLOBALS An array of references to all variables that are defined with global
scope 44
ASSESSING FORM DATA

• Form data are assessed via the superglobal variables


$_POST, $_GET or $_REQUEST
• E.g.,
$studentName = $_POST[‘studentName’];

45
STEPS TO HANDLE SUBMITTED FORM DATA

1. Verify that the entered information is complete, valid


and safe
2. Prepare the submitted data for use
3. Use the submitted data

46
DETERMINING IF FORM VARIABLES EXISTS

• When form data is posted using the post or get method, all
controls except unchecked radio buttons and check boxes get
sent to the server, whether they contain data or not
• The isset() function takes a variable name as an argument
and returns true if it exists and false otherwise

47
The empty() function

• The empty() function returns


• TRUE if the variable does not exist
• FALSE if the variable does exists and has a non-empty, non-zero
value
• The values considered empty are “”(empty string), 0, 0.0,
“0”, NULL, FALSE and array() (an empty array)

48
VALIDATING NUMERIC DATA
• All data entered in a form is actually string data. PHP
automatically converts string data to numeric data if the
string is in numeric format
• The is_*() family of functions can be used to ensure
that the user enters numeric values when necessary
• Comparison functions ensure that values are within a
required range
49
VALIDATING STRING DATA
• String functions can be used to produce strings with consistent
formatting
• Regular expression functions are some of the best tools for
verifying that string data meets the strict formatting required for
email addresses, web page urls, or date values

50
BASIC STRING FUNCTIONS
strcmp() Compares two strings (case-sensitive)
strlen() Returns the length of a string
strpos() Returns the position of the first occurrence of a string inside
another string (case-sensitive)
strtolower() Converts a string to lowercase letters
strtoupper() Converts a string to uppercase letters
substr() Returns part of a string
trim() Removes whitespace or other characters from both sides of a
string
ucwords() Converts the first character of each word in a string to uppercase
Chapter1Example1 NetBeans Project
• Run this project (Click )
• Draw a page map to show the links and relationships
index.php footer.php
header.php company.html
about.html vieworders.php
contact.php
orderform.php
processorder.php

• Review and discuss the code with a friend


52
OBJECT-ORIENTED PHP

• Object-oriented (OO) techniques will help you build more


extensible code that is easier to reuse, modify and enhance

53
CREATING A CLASS DEFINITION
class ClassName {
// data member definitions
// method member definitions
}

54
DEFINING DATA MEMBERS

class ClassName {
access_specifier data_member_name;
}
• Access specifiers include: public, private and
protected

55
THE $this REFERENCE
⚫ Within a class method, use $this-> to access class
members in the same way you would use an instantiated
object to refer to a data member
⚫ If you do not use the $this reference to refer to a data
member from within a member function, PHP treats the
data member as a local variable of the function

56
DEFINING CLASS CONSTRUCTOR
⚫ Each class can contain its own constructor named
__construct() (with 2 leading underscore characters), e.g.

class circle {
private $radius;

function __construct() {
$this->radius = 1;
}
. . . 57
}
ACCESSOR METHODS
class Circle {
private $radius;

public function getRadius() {


return $this->radius;
}
. . .
}

58
MUTATOR METHODS
class Circle {
private $radius;

public function setRadius($radius) {


$this->radius = $radius;
}
. . .
}

59
STORING CLASSES IN EXTERNAL FILES
• For ease of maintenance and reusability, define a class
within a single external file
• This external file is then called from each script that
needs the class using one of the following functions:
• include()
• include_once()
• require()
• require_once()
60
include() vs require()

• include() and include_once() will only produce a


warning and the script will continue
• require() and require_once() will produce a fatal
error and stop the script
• require_once() and include_once() ensures that the
file is inserted only once in a single execution lifetime
61
USING THE DEFINED CLASS
The following script section should be added to the start of the
document, before the <!doctype> tag:
<?php
require_once(“Circle.php”);
?>

62
USING OBJECTS IN PHP SCRIPTS
• To instantiate an object:
$objectName = new ClassName();
• To access the methods and properties contained in an object,
use the member selection notation (->), i.e:
$objectName->propertyName;
$objectName->methodName();
Note: do not put the dollar sign ($) before the property name when
using the -> operator
63
Chapter1Example2a NetBeans Project
a. Run this project (Click )
b. Draw a class diagram to show the relationships
index.php Circle.php
Displayable.php Rectangle.php
Shape.php

c. Review and discuss the code with a friend


• Explain how the magic functions work
• Compare & contrast the implementation of OOP in Java vs PHP

64
Chapter1Example2b NetBeans Project
a. Run this project (Click )
b. Draw a class diagram to show the relationship
index.php
Page.php
ServicesPage.php

c. Explain
• The use of OO concepts & principles in this example
• How does it contribute towards code reusability &
maintainability
65
WORKING WITH DATABASE OBJECTS
• There are 3 main API options for connecting to a
MySQL database server:
• MySQL - procedural
• MySQLi – procedural & OO
• PHP Data Objects (PDO) – Generic OO
• OO techniques is the preferred method as PHP
continues to evolve
66
PDO vs MySQLi

67
MORE INFORMATION ON PDO
• https://phpdelusions.net/pdo

68
Chapter1Example3 NetBeans Project
a. Run this project (Click )
b. Explain how information hiding/encapsulation and
abstraction are achieved by using the PDO class

69
SERIALIZING OBJECTS
• Serialization is the process of converting an object into a
string that you can store for reuse
• Serialization stores both data members and member functions into
strings, which can be stored in text files and databases or passed to
another script
• To serialize an object, pass the object name to the
serialize() function, e.g.
$saveditem = serialize($item);

70
DESERIALIZING OBJECTS
• To convert serialized data back into an object, use the
unserialize() function, e.g.
$item = unserialize($savedItem);

71
MAINTAINING STATE USING SESSIONS
(1)
• To share objects within the same session, serialize the
object between script calls within the same session
• To use serialized objects between scripts, assign a
serialized object to a session variable, e.g.:
session_start();
$_session(‘savedItem’) = serialize($item);

72
MAINTAINING STATE USING SESSIONS (2)

• Converting a serialized value in a session variable is similar


to converting a serialized value in a regular variable
• The following statement converts the serialized data in the
saveditem session variable back into the $item object:
$item = unserialize($_session(‘savedItem’));

73
Chapter1Example3 NetBeans Project

page1.php
page2.php
page3.php
• Run the page1.php file (Shift-F6), and then click the links
• Review and discuss the code with a friend

74
APPENDICES
• APPENDIX1.1 Advanced Form Handling
• APPENDIX1.2 Error and Exception Handling

75
Credits for Audio Clips
• BENSOUND.COM
• SOUNDBIBLE.COM
• BRAINYBETTY.COM

76

You might also like