Ch4 - PHP

Download as pdf or txt
Download as pdf or txt
You are on page 1of 151

CT219H – Web Programming Fundamentals

Chapter 4
PHP (Hypertext Preprocessor)
2019

Tran Cong An
([email protected])
Content

1. Introduction
2. PHP language basics
3. PHP functions
4. OOP in PHP
5. PHP and forms
6. PHP and MySQL
7. Cookies and sessions
8. Advanced PHP techniques (file upload, pagination, AJAX, etc.)
9. Appendix

2
Introduction to PHP

3
Introduction to PHP

What is PHP?

- PHP is a server-side scripting language:


• Scripts are embedded in HTML documents
• They are processed before returned to browser

- Basic characteristics:
• Widely used and open source scripting language
• Executed on the server
• Dynamically typed and purely interpreted
• Supported by most of popular web servers (IIS, Apache, etc.) and
OS (Windows, Linux, MacOS, etc.)

4
Introduction to PHP

What is PHP?

5
Introduction to PHP

PHP vs. JavaScript

6
Introduction to PHP

PHP vs. JavaScript

7
Introduction to PHP

What Can PHP Do?

- PHP can generate dynamic page content


- PHP can create, open, read, write, delete, and close files on
the server
- PHP can collect form data
- PHP can send and receive cookies
- PHP can add, delete, modify data in your database
- PHP can be used to control user-access
- PHP can encrypt data
- Etc.

8
Introduction to PHP

Why PHP?

- PHP runs on various platforms (Windows, Linux, Unix, MacOS, etc.)


- PHP is compatible with almost all servers used today (Apache,
IIS, etc.)
- PHP supports a wide range of databases
- PHP is free.
- PHP is easy to learn and runs efficiently on the server side

9
Introduction to PHP

PHP Development Environment

- Suggested development tools:


• Web server: Apache (http://httpd.apache.org/download.cgi)
• PHP interpreter (http://www.php.net/downloads.php)
• DBMS: MySQL/MariaDB (http://www.mysql.com/downloads/)

- Setting-up development environment:


• Option 1: download and install the above tools separately and
configure them to let them to be able to “talk” to each other
• Option 2 (recommended): install a software that packages all
above software (e.g. XAMPP, AMPPS, etc.)

10
PHP Language Basics

11
PHP Language Basics

Basic Syntax

- A PHP file normally contains HTML tags, and some PHP


scripting code (default PHP file extension: .php)
- PHP script can be placed anywhere in the document
- A PHP script starts with <?php and ends with ?>

- PHP statements end with a semicolon ;


- Variable names are case sensitive, others are case insensitive

The PHP processor has two modes: copy (HTML) and interpret (PHP)
12
PHP Language Basics

Basic Syntax
Copy &
Interpret

copy (HTML)

interpret (PHP)

copy (HTML)

Web server response


PHP
interpreter

13
PHP Language Basics

Variables

- Variable can be used without declaration (dynamically typed)


- Naming rules:
• A variable start with a $, followed by the variable name
• A variable name starts with a letter or the underscore
• A variable name can contain only alpha-numeric characters and
underscore

14
PHP Language Basics

Variables

- Scope (the parts of script where the variable can be used):


• Local:
o Created within a function
o Can be accessed within that functions
• Global:
o Created outside any functions
o Can only be accessed outside a function
o The global keyword is used to access global variable within a
function
o All global variables can also be accessed by the associative array
$GLOBALS

15
PHP Language Basics

Variables

Result: 15

16
PHP Language Basics

Variables

- Static variables:
• Created inside a function
• Not deallocated/deleted when the function completed (i.e. their
values are retained for further usage in the latter runs)
- Variable datatype:
• Automatically assigned depending on its value (loosely typed)
• To get the datatype od a variable: gettype(var_name)
• Functions to check variable type: is_bool(),
is_int(),is_float(), is_double(), is_string(),
is_object(),is_array(), is_numeric(), is_resource(),
is_null(),isset(), empty()

17
PHP Language Basics

Variables

18
PHP Language Basics

PHP Outputs

- echo and print statement are used to output data to screen


- echo: echo(str); or echo str [,str...];
• Can take multiple parameters
• Has no return value (i.e. cannot be used in expressions)

• Marginally faster than print()


- print: print(str); or print str;
• Can take only one parameter
• Has return value of 1 (i.e. can be used in expressions)

19
PHP Language Basics

Datatypes

- Common datatypes supported by PHP:


• String (string values are enclosed in single or double quotes)
• Integer (32-bit number, from -2,147,483,648 and 2,147,483,647)
• Float (platform-dependent but typically: 64-bit, with precision of 14
decimal digits)
• Boolean (TRUE or FALSE values)
• Array (can store multiple values with different datatypes)
• Object (the class of the object must be declared first)

20
PHP Language Basics

Operators

- Arithmetic: +, –, *, /, %, ++, --, ** (exponentiation)


- Assignment: =, +=, -=, *=, /=
- Comparison: == (equal), === (identical), !=, <>, !==, >, <, >=, <=
- Logical: and, or, xor, &&, ||, !
- String: . (concatenation), .=
- Array: + (union), ==, ===, !=, !==, <>

21
PHP Language Basics

Strings

- String values are enclosed in single quotes, double quotes, or


heredoc (starts with <<< followed by an identifier, ends with the identifier)
- Example:

- A string value can be expanded in multiple lines


- Variables and escape sequences will not be expanded when
using single quote
- Some string functions: strlen(), strpos(), strrev(),...

22
PHP Language Basics

Constants

- A constant is an identifier (name) for a simple value


- A valid constant name starts with a letter or underscore (no $
sign before the constant name)
- Automatically global across the entire script
- To create a constant, use the define() function
define(name, value [, case-insensitive = FALSE])

23
PHP Language Basics

Control Statements

- Condition statements:
• if ... else
• switch ... case
• ?
- Loops:
• while
• do … while
• for
• foreach

24
PHP Language Basics

Control Statements – if ...else

25
PHP Language Basics

Control Statements – switch ... case

26
PHP Language Basics

Control Statements – while

27
PHP Language Basics

Control Statements – do ... while

28
PHP Language Basics

Control Statements – for/foreach

29
Functions

30
Functions

Declarations

- A user-defined function is declared using the word function


- Syntax:
function function_name() {
//function body (statements)
}
- Note:
• A function name can start with a letter or underscore
• Function name should reflect what the function does
• Function names are NOT case-sensitive

31
Functions

Example

32
Functions

Function Arguments

- Declared inside the parentheses, separated by commas

33
Functions

Function Arguments

- May have default values (should be declared at the end)

34
Functions

Function Arguments

- Functions arguments are pass-by-value by default


- Pass-by-reference: prepend an & to the argument name
- Example:

35
Functions

Function Arguments

- Related built-in functions:


• int func_num_args(void): get the number of arguments
• mixed func_get_arg(int $arg_num): get the argument value

36
Functions

Argument Type Declarations

- Type declaration allows functions to require that parameters


are of a certain type at call time (int, float, string, array, boolean,…)
- To enable strict requirement: declare(strict_types=1);

37
Functions

Return Values

- A function always return one and only one value


- To return a value for a function call: return <value>;
• Any types may be returned
• If no return statement in a function, NULL will be returned

38
Functions

Return Type Declarations

- Add a colon “:” and the type right before the “{” in the
function declaration to specify the function return type
- To enable strict requirement: declare(strict_types=1);

39
Arrays

40
Arrays

Arrays

- An array stores multiple values in one single variable


- Elements of an array may have difference data types
- Types of array:
• Indexed arrays: arrays with a numeric index
• Associative arrays: arrays with named keys
• Multidimensional arrays: arrays containing one or more arrays

41
Arrays

Indexed Arrays

- Declaration:
• Empty array: $arr_name = array()
• Array with initial values: $arr_name = array(val1, val2,…);
- Access (set/get) array elements: $arr_name[index]
- Get array length: count($arr_name)
- Loop through an array:
• for loop (usually combined with the count() function)
• foreach ($arr_name as $var) loop

 Array index may not be contiguous


 Index may be omitted, $a[]: a new available index will be used
42
Arrays

Indexed Arrays

43
Arrays

Associative Arrays

- Two ways to create an associative array:


• $arr_name = array(key => value [, key => value …] );
• $arr_name['key1'] = value1;
$arr_name['key2'] = value2;
- Access array elements: $arr_name['key']
- Get array key set: array_keys($arr_name)
- Loop through an associative array:
• foreach ($arr_name as $key => $value) { ... }
• for loop using the key set
- Remove a key/value pair: using unset($arr[key]) function

44
Arrays

Associative Array Example

//another method to loop through an associative array

45
Arrays

Multi-dimensional Arrays

- A multi-dimensional array is an array of arrays


• Two dimensional: an array of arrays
• Three dimensional: an array of arrays of arrays
- Syntax: $arr_name = array(
array(…),
array(…)
[,…]);
- Arrays of an array may be different dimensions

46
Arrays

Multi-dimensional Arrays

47
Arrays

Multi-dimensional Arrays

orange banana
apple

48
OOP in PHP

50
OOP in PHP

Class Definition

- Syntax:

- Access modifiers: public, protected, private


- $this: reference to the calling object

51
OOP in PHP

Creating Objects

- Use the new keyword: $var = new Classname([arg]);


- If there is no argument for the constructor, parentheses may
be omitted

52
OOP in PHP

Object Assignment

- $obj2 = $obj1: $obj2


references to the same
object as $obj1 (shadow copy)
- $obj2 = &$obj1: $obj2 is a
reference of $obj1 (reference
is an alias)
- $obj2 = clone $obj1: A
new object is cloned from
$obj1 and it is referenced by
$obj2 (deep copy)

53
OOP in PHP

Static Members

- Declared using static keyword


- Accesses though class, not the objects of the class
• Outside the class:
o classname::$property
o classname::method()
• Inside class:
o self::$property
o self::method()

- Note: $this cannot be used


inside static methods

54
OOP in PHP

Constructors and Destructors

- Constructors: called automatically when an object is created

- Destructors: called automatically when an object is destroyed

55
OOP in PHP

Constructors and Destructors

56
OOP in PHP

Inheritance

- Syntax: use the extends keyword

- Child class inherits all members of the parent class (but it can
access public and protected members)
- Child class can override methods of the parent class
- Access parent members from the child class:
• parent::property
• parent::method()

57
OOP in PHP

Inheritance

58
OOP in PHP

Further Reading

- Abstract class (class contains some abstract methods – methods


without implementation)
- Final methods (methods that cannot be overridden)
- Interfaces (“pure” abstract classes)
- __toString() method (object to string auto conversion )
- Using code from other .php files (include statement)

59
PHP and Forms

60
PHP and Forms

HTML Forms

- Forms are used to get user inputs


- Form data is usually sent to server (PHP) to process

• action: PHP page that will receive and process form data
• method: HTTP method that is used to send data to server
o GET: form data is sent via the URL parameters
o POST: form data is sent inside the request package body)
• Form data is sent to server in the form of an array (key => value)
where key is the name of the control and value is the input data

61
PHP and Forms

Getting Form Data

- The PHP global variables $_GET and $_POST are used to collect
form data (corresponding to the GET and POST method)

62
Checking Data Existence

- Use the isset() function:

63
PHP and MySQL

64
PHP and MySQL

MySQL Server Access from PHP

- Two methods in accessing MySQL DB from PHP:


• MySQLi (object-oriented or procedural, only work with MySQL)
• PDO (PHP Data Objects, can work with 12 DBMS)
- Steps in accessing MySQL databases from PHP:
1. Create connection to MySQL server
2. Select the database
3. Execute SQL statement (query, insert, update, delete)
4. Get and process the returned data
5. Produce the output
6. Close the connection

65
PHP and MySQL

Related MySQLi Classes

- mysqli: represents a connection between PHP and MySQL


• ::__construct(): creates connections
• ::$connect_error: contains connection error description
• ::select_db(): select the default DB
• ::query(): perform a query
• ::$error: contains last error description
• ::prepare(): create a prepared statement (mysqli_stmt class)
• ::close(): close a connection

66
PHP and MySQL

Related MySQLi Classes

- mysqli_stmt: represents a prepared statement


• ::bind_param(): binds variables to a prepared statement as
parameters
• ::bind_result(): binds variables to a prepared statement for
result storage
• ::execute(): executes a prepared statement
• ::get_result(): returns the result set from the statement
• ::fetch(): fetch results from a prepared statement
• ::$num_rows: number of rows in the statement result set
• ::close(): closes a prepared statement

67
PHP and MySQL

Related MySQLi Classes

- mysqli_result: represents the result set obtained from a


query
• ::fetch_all(): fetch all rows as an associative or numeric
array or both
• ::fetch_array(): fetch a row as an associative or numeric
array or both
• ::fetch_assoc(): fetch a row as an associative array
• ::fetch_row(): fetch a row as an numeric array
• ::$field_count: get the number of fields in a result
• ::$num_rows: get the number of rows in a result

68
PHP and MySQL

Creating Connections

- Use the constructor of class mysqli:


mysqli($servername, $username [, $password, $dbname]);
• servername: can be either hostname or an IP
• username: MySQL user name
• password: MySQL user password (not provided/NULL: no password)
• returns an object representing the connection to MySQL server
- The connection information:
• usually declared in a separated file
• included into the PHP file using the require_once() statement
- mysqli::$connect_error contains error description

69
PHP and MySQL

Creating Connections

- mysqli::$connect_error – contains description of the last error,


or NULL of no error occurred
70
PHP and MySQL

Selecting DB

- Select DB when create the connection:


mysqli($servername, $username, $password, $dbname);
- Select DB after the connection created:
• mysqli::select_db($dbname): returns TRUE on success,
FALSES on failure

71
PHP and MySQL

Executing SQL Statements

- Use the mysqli::query() method:


• Failure: returns FALSE
• Success: mysqli_result object for SELECT, SHOW, DESCRIBE,
EXPLAIN queries; TRUE for other queries

72
PHP and MySQL

Executing SQL Statements

- Prepared statements:
• mysqli::prepare($query): create prepared statement
o Returns a mysqli_stmt object or FALSE if an error occurred
• mysqli_stmt::bind_param($type, $var [, $var…]): binds
variables to a prepared statement as parameters
o Returns TRUE on success; FALSE on failure
o Parameter types: i (integer), d (double), s (string), b (blob)
• mysqli_stmt::execute(): execute a prepared query
o Returns TRUE on success; FALSE on failure

Prepared statement is recommended due to its better


performance, less bandwidth and useful against SQL injection
73
PHP and MySQL

Executing SQL Statements

74
PHP and MySQL

Accessing Returned Data

- Access data in a mysqli_result object with fetch_assoc():

75
PHP and MySQL

Accessing Returned Data

- Access data in a mysqli_result object with fetch_row():

76
PHP and MySQL

Accessing Returned Data

- Access data in a mysqli_result object with fetch_array():

77
PHP and MySQL

Accessing Returned Data

- Access data in a mysqli_stmt object with bind_result()


and fetch():

78
PHP and MySQL

Template for PHP-MySQL Data Access

$hostname, $username, $password, $dbname

79
PHP and MySQL

Example – Book Search

80
PHP and MySQL

Example 1 – Book Search

- Webpage and form:

81
PHP and MySQL

Example 1 – Book Search

- Search function:

SELECT * FROM classics WHERE title LIKE '%$new_kw%'

<p><i>$row[title]</i>. $row[author] ($row[year]).</p>\n

82
PHP and MySQL

Example 2 – Title Management

- Application interface:

83
PHP and MySQL

Example 2 – Title Management

- Main page:

84
PHP and MySQL

Example 2 – Title Management

- Add title form:

85
PHP and MySQL

Example 2 – Title Management

- List and delete title form:

Confirm before deleting:

86
PHP and MySQL

Example 2 – Title Management

- Process the delete title function:

To show an alert box about the deletion:

87
PHP and MySQL

Example 2 – Title Management

- Process the add title function:

88
PHP and MySQL

Exercise – Edit Book Details

- Add the “Edit Book Detail” for the Book Manager Application
as follow:
• Add an Edit button next to the Delete button
• When the user click the Edit button, open a new page that
allows user to edit the details of the selected book (update page)
• In the update page, user can
o Edit and Save the change
o Go back to the home page

89
Cookies and Sessions

90
Cookies and Sessions

What is Cookie?

- A cookie is a small file that the server stores on the browser


(user computer)
- This small file stores a set of name => value items (called cookie)
- Usually used to identify the user
- Each time the browser making a request, it will include the
cookies in the request message
- To create a cookie (name => value) in PHP:
• setcookie(name [, value, expire …])
• Expiration unit is second
• The calls to this function must appear before the <html> tag

91
Cookies and Sessions

Getting and Deleting Cookies

- Cookies sent to server is stored in the array variable $_COOKIE


- To get a cookie value, provide cookie name $_COOKIE[name]
- A cookie is automatically deleted when:
• Time is expire
• The browser closes, if no expire is set
- To delete a cookie, set expire time of the cookie with an
expiration date in the past

92
Cookies and Sessions

Cookie Example

93
Cookies and Sessions

Sessions

- Used to store information (in variables) across multiple pages of


an application (website)
- Sessions are stored on the server
- By default, session variables last until the browser closes
- To start a session: call session_start() (before the <html> tag)
- Session variables are stored in the global variable $_SESSION
• Access a session: $_SESSION[name]
- Destroy all sessions: session_unset() or session_destroy()
- Destroy a session: unset($_SESSION[name])

94
Cookies and Sessions

Session Example – Login

95
Cookies and Sessions

Session Example – Login

- The code to check login session is usually stored in a separated


file and included into the webpages which need the
authorization
96
Advanced PHP Technique

File upload, image saving in DB, pagination, AJAX

97
File Upload

98
File Upload

Setting Up

- Turn on file upload option:


• Set the file_uploads directive to On in file “php.ini”

- Steps to upload files by PHP:


1. Create a form for file upload with appropriate encryption
method (browser)
2. Validate data received at server (error, format, size, etc.)
3. Save files received to storage devices

99
File Upload

Upload Form (Client)

- Form attributes:
• Method: POST
• Encryption method: enctype=multipart/form-data
• File select control: <input type=file ...>

100
File Upload

File Information (Server)

- After uploading, the file will be stored temporarily on the


server (configured with the upload_tmp_dir directive in php.ini)
- The global associative array $_FILES contain all the uploaded
file information:
• $_FILES["filename"]["name"]: the original name of the file
• $_FILES["filename"]["type"]: the MIME type of the file
• $_FILES["filename"]["size"]: the file size (in bytes)
• $_FILES["filename"]["tmp_name"]: the temporary name of
the file (stored temporarily in the server after uploading)
• $_FILES["filename"]["error"]: error code of the upload

101
File Upload

Validation (Server)

102
File Upload

File Storage

- Related functions:
• move_uploaded_file(tmp_file, persistent_file): moves
an uploaded file to a new location (returns TRUE on success)
• file_exists(filename): check whether a file or directory
exists (returns TRUE on success)

103
File Upload

Complete Image Upload Example

1. Check for upload error and file type (jpeg)


2. Save image file to “uploads” folder
3. Display uploaded image on upload page

104
File Upload

Complete Image Upload Example

upload-form.html

upload.php

105
File Upload

Saving Images to a Database

- Datatype to store image: blob


- Steps to save image to database:
1. Validate file uploaded: upload status, type, size, etc. (using the
global variable $_FILES and function getimagesize())
2. Get the image file content which is saved temporarily on the
server to a variable
3. Add backslashes ( \ ) before predefined character, using the
addslashes() function
4. Save image into the table, using the image variable create in
step 2

106
File Upload

Saving Images to a Database

- Given a table with the following structure:

- Upload form:

107
File Upload

Saving Images to a Database

108
File Upload

Displaying Images Saved in a Database

- To display an image in DB: <img src=get_img?id=img_id>


(get_img.php is script that read the image with the id is img_id from the DB )

109
File Upload

Displaying Images Saved in a Database

110
Pagination

112
Pagination

Steps in Creating Pagination

1. Calculate the total number of records: $total_records


2. Identify the number of records displayed per page:
$records_per_page
3. Store the current page number (use hidden variable or send
directly to server by GET method)
4. Query data for the requested page
5. Create Next page and Previous page links

113
File Upload

Case Study

- Build a book search page with pagination (2 result per page)

114
File Upload

Structure of the Application

- Main page:
• Show the form to get search keywords + Search button
• Call search() function to search for books and get the
pagination information
• Call page_nav_link() function to create links to Prev/Next page
- PHP functions:
• compute_paging(search_kw): computer pagination parameters
• search(kw): search and return search result and pagination info
• page_nav_links(paging_info, search_kw): create links to
Prev/Next page

115
File Upload

Main page

116
File Upload

Function compute_paging()

p_total: total no of pages;


p_no: current page;
p_start: index of the first
record in the page;
total: total number of records

117
File Upload

Function search()

118
File Upload

Function search()

119
AJAX
Asynchronous JavaScript And XML

120
AJAX

What is AJAX?

- A technology that allow asynchronous communication


between web browsers and web servers
- Not a programming language, just a combination of:
• A browser built-in XMLHttpRequest object (to send request to server)
• JavaScript and HTML DOM (to display or use response data)
- With AJAX, we can:
• Read data from a web server, after the page has loaded
• Update a (part of) web page without reloading the page
• Send data to a web server in the background (i.e. update parts of a
web page, without reloading the whole page)

121
AJAX

Synchronous Communication

- User have to wait while browser communicates with the web


server

122
AJAX

Asynchronous Communication

- Users can interact with the web page while the browser is
communicating with web server

123
AJAX

How AJAX Works?


Browser Server Browser
An event occur... • Process • Process the
• Create an

Internet

Internet
HttpRequest returned data
XMLHttpRequest • Create a response using JS
object and send data back • Update page
• Sent HttpRequest to the browser content

124
AJAX

XMLHttpRequest Object

- Used to exchange data with web server behind the scenes


- Send request to server:
• open(method, url, async): specify the type of the request
o method: GET/POST
o url: server/file location
o async: true (asynchronous) or false (synchronous)
• send(): send the request to the server (used for GET)
• send(string): send the request to the server (used for POST)
• setRequestHeader(header, value): add HTTP header to the
request

125
AJAX

XMLHttpRequest Object

- Request examples:
• GET request:

• To avoid cached result:

• POST request:

Content-type application/x-www-form-urlencoded

126
AJAX

XMLHttpRequest Object

- Request examples:
• POST with JSON data:

127
AJAX

XMLHttpRequest Object

- Server response:
• readyState: the status of the XMLHttpRequest object
(0: request not initialized, 1: server connection established, 2: request
received, 3: processing request, 4: response is ready)
• onreadystatechange: a function to be execute when the
readyState changes

128
AJAX

XMLHttpRequest Object

- Server response:
• status, statusText: status of the XMLHttpRequest object
(200: "OK", 403: "Forbidden", 404: "Page not found")
• responseText: contains the response data as a string
• responseXML: contains the response data as XML data
• getResponseHeader(header): returns specific header
information from the server
• getAllResponseHeaders(): Returns all the header information
from the server

129
AJAX

loadDoc() Function

- If there are more than one AJAX tasks, we should create:


• A loadDoc() function for executing the XMLHttpRequest with
two parameters: the requested URL and the callback function
• A callback function for each AJAX task with

130
AJAX

AJAX Simple Example

131
AJAX

AJAX Simple Example

132
AJAX

AJAX Example – Dropdown List

133
AJAX

AJAX Example – Dropdown List

̣ ̉

❶ ❷
̣ ệ

134
AJAX

AJAX Example – Dropdown List

135
AJAX

AJAX Example – Dropdown List

136
AJAX

AJAX Example – Dropdown List

137
AJAX

AJAX Example – Dropdown List

138
Question?

Chapter 3 – JavaScript

139
Appendix

A simple CRUD “Employee Manager Application”

140
Appendix – Simple CRUD Application

Application GUI

141
Appendix – Simple CRUD Application

Application GUI

142
Appendix – Simple CRUD Application

Application GUI

143
Appendix – Simple CRUD Application

Application GUI

144
Appendix – Simple CRUD Application

Application and DB Structure

145
Appendix – Simple CRUD Application

Connect to MySQL

146
Appendix – Simple CRUD Application

Header and Footer

147
Appendix – Simple CRUD Application

Index Page

148
Appendix – Simple CRUD Application

Adding New Employees (Sample)

149
Update Form Generation (update.php)

150
Update Employee Information

151
Login, Logout and Permission Checking

152
The End!

153

You might also like