Chapter 1 Scripting
Chapter 1 Scripting
SCRIPTING
1
ORIGINS OF SCRIPTING
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 efficient • Compiler can use type information to generate more e fficient code
code
8
ADVANTAGES OF WEAK TYPING
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
12
SCRIPTIN
G
13
A PHP FILE MAY CONTAIN
• HTML
• PHP tags
• PHP statements
• Whitespace
• Comments
14
COMBINING HTML AND PHP
15
PHP CODE BLOCKS
16
ASSESSING & INTERPRETING PHP
PAGES
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
• Example:
$states = array(“Penang”, “Perak”, “Johor”);
25
ALTERNATIVE WAY TO CREATE ARRAYS
<?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
31
MAKING DECISIONS
• Similar to Java:
• if statement
• if..else statement
• switch 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
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
45
STEPS TO HANDLE SUBMITTED FORM 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
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
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;
58
MUTATOR METHODS
class Circle {
private $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()
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
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)
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