0% found this document useful (0 votes)
20 views114 pages

Chapter Five - PHP

Uploaded by

semagn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views114 pages

Chapter Five - PHP

Uploaded by

semagn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Woldia University

Institute of Technology (IoT )


Department of Computer Science
Programming Chair

Chapter Five: Hypertext Preprocessor (PHP)


By
Instructor: Nega A.(MSc in CS)
July 30, 2024
Outline

 Introduction to PHP
 Basic PHP Syntax
 PHP Comments
 Predefined and User Variables in PHP
 PHP Output Statements
 Data Types in PHP
 Arithmetic and Logical Operators
 Conditional and looping Statements
 Arrays and functions in PHP
 Working with MySQL
 Form Processing using PHP

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 2
Introduction

 PHP stands for Hypertext Preprocessor

 PHP is server-side scripting language widely used for web development.

 PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid,


PostgreSQL, Generic ODBC, etc.)

 PHP is an open source software (OSS)(free to download and use).

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 3
Basic Features of PHP
 Extensive Library Support: Rich set of libraries and frameworks (e.g., Laravel,
Symfony) for various functionalities.
 Database Integration: Strong support for interacting with databases, especially
MySQL.
 Simple Learning Curve: Easy for beginners to pick up due to its C-like syntax.

 Community Support: Large and active community contributing to continuous


improvement.
 Embedded in HTML: PHP code is embedded within HTML, allowing seamless
integration with web pages.
 Cross-Platform Compatibility: Works on various operating systems (Windows,
Linux, macOS) and supports major web servers.
@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 4
Advantages of PHP

 Open Source: PHP is free to use, and its source code is


available for modification.

 Easy Integration: Easily integrates with HTML code and


other web technologies.

 Database Support: Excellent support for multiple


databases, with MySQL being a popular choice.

 Rapid Development: Allows quick development of dynamic web


applications.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 5
Disadvantages of PHP

 Inconsistency: Historically, PHP has had inconsistencies


in function names and parameter orders.

 Security Concerns: If not handled properly, PHP


applications can be vulnerable to security issues like SQL
injection.

 Not Suited for Large Applications: While it's excellent


for small to medium-sized projects, PHP might face
scalability challenges in massive applications.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 6
Disadvantages of PHP

 Performance: Compared to some other languages, PHP may not


be as performant in certain scenarios.

 Lack of Modern Features: Before PHP 7, the language lacked


some modern features found in other languages.

 Less Object-Oriented Focus: Though PHP supports OOP, its


early versions were not as object-oriented as some other
languages.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 7
Basic PHP Syntax

 There are four ways the PHP parser engine can


differentiate PHP code in a webpage:
1. Canonical PHP Tags: This is the most popular and effective
PHP tag style and looks like this: <?php ...?>

2. Short-open Tags: These are the shortest option, but they


might need a bit of configuration, and you might either
choose the --enable-short tags configuration option when
building PHP, or set the short_open_tag setting in your
php.ini file to on. <? ...?>

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 8
Basic PHP Syntax

3. ASP-like Tags: In order to use ASP-like tags, you’ll need


to set the configuration option in the php.ini file:
<% ... %>

4. HTML script Tags: You can define a new script with an


attribute language like so:
<script language=“PHP”> ... </script>
• This syntax is removed in PHP 7.0.0. So its no more
used.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 9
Basic PHP Syntax

 The default file extension for PHP files is “.php”.

 Everything outside of a pair of opening and closing tags


is ignored by the PHP parser.

 The open and closing tags are called delimiters.

 Every PHP command ends with a semi-colon (;).

 In PHP, keywords (e.g. if, else, while, echo, etc.),


classes, functions, and user-defined functions are not
case-sensitive.
• However, all variable names are case-sensitive!
@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 10
Basic PHP Syntax
 Example:
<?php // PHP code starts here

// Define a variable for the user's name


$stringVariable = “students”;

// Output a greeting message


echo “<h1>Hello, $ stringVariable!</h1>”;

?> // PHP code ends here

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 11
Comments in PHP
 Single-line comments begin with //. Anything following //
on the same line is treated as a comment.

 Multi-line comments are enclosed between /* and */. Everything


between these symbols is treated as a comment, spanning
multiple lines if needed.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 12
Predefined and User Variables in PHP
 PHP provides several predefined variables that hold
information about the server, user input, and more

 Predefined variables
1. $_GET
• Contains data sent to the script via URL parameters using the
HTTP GET method. Commonly used for retrieving form data from the
URL. Example: assume the URL is example.php?name=John&age=30

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 13
Predefined and User Variables in PHP
 Predefined variables
2. $_POST
• Holds data submitted to the script via the HTTP POST method.

• Commonly used for handling form submissions where sensitive data


is sent.

• Example: Assume a form is submitted with <form method="post"


action="example.php"> containing input fields with names
username and password.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 14
Predefined and User Variables in PHP
 Predefined variables
3. $_REQUEST
• Combines data from $_GET, $_POST, and $_COOKIE.

• Provides a merged view of user input.

• Example: Assume the script can accept data from both GET
and POST methods.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 15
Predefined and User Variables in PHP
 Predefined variables
4. $_SESSION
• Manages session variables that can be used across
multiple pages during a user's visit.
• Useful for storing user-specific information.

• Example: Assume a session is started on one page, and


user information is stored.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 16
Predefined and User Variables in PHP

 Predefined variables
5. $_SERVER
• Provides information about the server and the execution
environment.
• Example: Assume you want to get the server's IP address
and the user's browser.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 17
Predefined and User Variables in PHP

 Predefined variables - $_GET, $_POST, $_REQUEST

 Advantages
• Ease of Use: These variables simplify the process of
collecting data from forms submitted via GET or POST
methods.
• Common Usage: Widely used in web development for
handling form data and user input.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 18
Predefined and User Variables in PHP

 Predefined variables - $_GET, $_POST, $_REQUEST

 Disadvantages/Limitations:
• Security Concerns: Data from $_GET and $_POST may need
to be validated and sanitized to prevent security
vulnerabilities like SQL injection or cross-site
scripting.
• Data Visibility: Data sent via $_GET is visible in the
URL, which may pose a security risk if sensitive
information is passed.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 19
Predefined and User Variables in PHP
 Predefined variables - $_SESSION
 Advantages:

• User State Management: Enables the storage of user-specific


information across multiple pages during a session.

• Security: Session data is stored on the server, reducing the


risk of exposing sensitive information to users.

 Disadvantages/Limitations:

• Server Resources: Sessions consume server resources, and


improperly managed sessions may lead to memory issues.

• Complexity: Managing sessions across pages requires proper


initialization and handling, which might be complex for
beginners.
@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 20
Predefined and User Variables in PHP

 Predefined variables - $_SERVER


 Advantages:

• Server Information: Provides useful information about the server


environment.

• Customization: Can be used for server-related tasks, such as


retrieving the server's IP address or handling user agents.

 Disadvantages/Limitations:

• Dependence on Server Configuration: Some information may depend on


the server's configuration and may not be available in all
environments.

• Potential for Spoofing: Some values, like user agent, can be easily
manipulated, posing a risk for security-sensitive operations.
@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 21
Predefined and User Variables in PHP

 Predefined variables - $_COOKIE


 Advantages:

• Persistent Data: Allows storing data on the user's browser for


extended periods.

• Customization: Useful for implementing features like remembering


user preferences.

 Disadvantages/Limitations:

• Security Risks: Cookies may be susceptible to security risks


like session hijacking or cookie theft.

• Limited Storage: Browsers impose limits on the number and size


of cookies that can be stored.
@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 22
Predefined and User Variables in PHP

 User variables
 User variables are created by the programmer to store and
manipulate data:

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 23
Predefined and User Variables in PHP

 User variables
 Variable Naming Rules:

• Variables must start with a letter or underscore.

• Subsequent characters can be letters, numbers, or underscores.

• Variable names are case-sensitive ($name and $Name are different).

 Clear and Meaningful Names:

 Choose names that reflect the purpose or content of the variable.

 Use camelCase or underscores for multi-word variable names (e.g.,


$userName or $user_name).

 Avoid using PHP reserved keywords (e.g., $if, $echo) as variable


names.
@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 24
Predefined and User Variables in PHP

 User variables
 Scope:

 Understand variable scope: variables declared inside a function


are local, while those declared outside functions are global.

 Initialization:

• Initialize variables before using them to avoid undefined


variable warnings.

• $name = “”; or $name = null; for strings; $count = 0; for


integers.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 25
Predefined and User Variables in PHP

 User variables
• Type Consistency:

• PHP is loosely typed, but maintaining type consistency is good


practice.

• If a variable is initially assigned as an integer, try to keep


it as an integer.

• Avoid Magic Numbers:

• Avoid hardcoding numbers directly in your code; use named


constants or variables instead.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 26
Predefined and User Variables in PHP

 User variables
• Memory Management:

• Be mindful of memory usage, especially in large-scale


applications.

• Unnecessary variables should be unset to free up memory.

• Security Considerations:

• Validate and sanitize user input before assigning it to


variables to prevent security vulnerabilities.

• Be cautious about using user input directly in queries or


displaying it on the page.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 27
Predefined and User Variables in PHP

 User variables

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 28
PHP Output Statements

 PHP provides several output statements that allow you to


display content to the user or send data to a browser. The
most common output statements in PHP are echo, print, and
printf.
1. echo Statement: is used to output one or more strings. It can take
multiple parameters, and you can use it with or without
parentheses.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 29
PHP Output Statements
2. print Statement: is similar to echo and is used to output text. It
can also be used with or without parentheses.

3. printf Statement: The printf (formatted print) statement allows


you to format and output text with placeholders for variables. It
is similar to the printf function in C.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 30
PHP Output Statements

4. sprintf Function: works similarly to printf but returns the


formatted string instead of printing it directly. This can be
useful if you want to store the formatted string in a variable.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 31
Data Types in PHP

 Integer: Represents whole numbers without decimal points.

• Example: $num = 42;

 Float (Floating-point numbers or Doubles):

• Represents numbers with decimal points. Example: $floatNum


= 3.14;

 String: Represents a sequence of characters enclosed in single


or double quotes.
• Example: $name = "John";

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 32
Data Types in PHP
 Boolean: Represents a binary value, typically used for logical
conditions. Example: $isTrue = true;

 Array: Represents an ordered map of values where each value is


assigned a key.
• Example: $colors = array("red", "green", "blue");

 Object: Represents instances of user-defined classes.

 Example:

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 33
Data Types in PHP

 Null: Represents the absence of a value or a variable with no


value assigned. Example: $variable = null;

 Resource: Represents a special variable holding a reference to


an external resource (like a file handle). Example:

 Callable: Represents a variable that can be called as a


function. Example:

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 34
Operators in PHP

 PHP supports a variety of operators that allow you to


perform operations on variables and values.
1. Arithmetic Operators: +, -, *, /, and %

2. Assignment Operators: =, =+, =-, =*, =/, and =%

3. Comparison Operators: Equal (==), Identical (===, Not


Equal (!= or <>), Not Identical (!==), Greater Than (>),
and Less Than (<)

4. Logical Operators: AND (&&), OR(||), and NOT(!)

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 35
Operators in PHP
5. Increment/Decrement Operators: ++ and -- (with prefix and
postfix)

6. Concatenation Operator (.): $fullName = $firstName .’’.$lastName;

7. Ternary Operator (? :):

8. Null Coalescing Operator (??): is a shorthand syntax in


PHP that provides a concise way to handle situations where
you want to check if a variable is set and not null, and
if it is null, provide a default value. It's especially
useful for simplifying code that involves checking and
assigning default values.
@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 36
Reading Assignment

 Conditional Statements

 Looping Statements
• For loop

• While loop

• Do … while loop

• forEach loop

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 37
Arrays in PHP

 Arrays are used to store multiple values in a single variable.

 There are three types of arrays in PHP


1. Indexed Arrays: We can create these kind of arrays in two ways
shown below:

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 38
Arrays in PHP

 There are three types of arrays in PHP


2. Associative arrays: are arrays which use named keys that you
assign. Again, there are two ways we can create them:

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 39
Arrays in PHP

 There are three types of arrays in PHP


3. Multidimensional Arrays: is an arrays the elements of which are
other arrays. For example, a three-dimensional array is an array
of arrays of arrays.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 40
PHP Functions

 Functions are a type of procedure or routine that gets executed


whenever some other code block calls it.

 PHP has over 1000 built-in functions.

 The basic syntax of a function that we create is:

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 41
PHP Functions

 Every function needs a name, optionally has one or more


parameters and most importantly, defines some kind of procedure
to be followed within the body, that is, code to be executed.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 42
Overview on MySQL database

 MySQL is a popular open-source relational database management


system (RDBMS). It is widely used for web development and is
compatible with various programming languages, including PHP.

 Basic MySQL Concepts:


 Database: A collection of related data tables.

 Table: Organized data in rows and columns.

 Column: Represents a specific data type in a table.

 Row: A record in a table.

 Primary Key: Unique identifier for each record in a table.


@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 43
Connecting to a Database

 There are four ways you can generally consider when you want to
connect to a previously created database.
1. Connecting to MySQL Databases: The syntax for connecting to a
MySQL database would be:

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 44
Connecting to a Database

 The four ways to connect to a previously created database.


2. Connecting to MySQLi Databases (Procedurial): The MySQLi stands
for MySQL improved.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 45
Connecting to a Database

3. Connecting to MySQLi databases (Object-Oriented):

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 46
Connecting to a Database

4. Connecting to PDO Databases: PDO stands for PHP Data Objects and
is a consistent way to access databases, which promises much
easier portable code.
• PDO is more like a data access layer which uses a unified API
rather than an abstraction layer
• PDO is widely used today for a bunch of advantages it offers.
 PDO allows for prepared statements and it throws catchable exceptions
which means better error handling and uses blind parameters in statements
which increases security.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 47
Connecting to a Database
PDO - It represents a connection between PHP and the database.
Connecting to PDO Databases:

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 48
CRUD Operations in PHP

1. Create (Insert) Operation: Procedural MySQLi

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 49
CRUD Operations in PHP

1. Create (Insert) Operation: Object-Oriented MySQLi

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 50
CRUD Operations in PHP

1. Create (Insert) Operation: PDO:

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 51
CRUD Operations in PHP

2. Read Operation: Procedural MySQLi

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 52
CRUD Operations in PHP

2. Read Operation: Object Oriented MySQLi

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 53
CRUD Operations in PHP

2. Read Operation: PDO

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 54
CRUD Operations in PHP

3. Update Operation: Procedural MySQLi

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 55
CRUD Operations in PHP

3. Update Operation: Object Oriented MySQLi

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 56
CRUD Operations in PHP

3. Update Operation: PDO

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 57
CRUD Operations in PHP

4. Delete Operation: Procedural MySQLi

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 58
CRUD Operations in PHP

4. Delete Operation: Object Oriented MySQLi

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 59
CRUD Operations in PHP

4. Delete Operation: PDO

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 60
Security Considerations
 Prevent SQL Injection:
• Use prepared statements or parameterized queries.

 Data Validation: Validate and sanitize user input.

 Error Handling: Properly handle errors to avoid exposing


sensitive information.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 61
PHP Form Handling

 In HTML, forms are used to collect user input/information

 we check each input to make sure the user has written/


chosen something, and the input is not empty. We do this
using two well-known functions in PHP, the isset() and
empty()
@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 62
PHP Form Handling

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 63
PHP Include & Require Statements

 Include and require statements are two almost identical


statements that help in an important aspect of coding, the
organization of code, and making it more readable and flexible.

 The include/require statement copies all text, code or any other


markup from one existing file to the file using the statement.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 64
PHP Include & Require Statements

 The include and require statements are the same, except upon
failure of code execution where:
• require will produce a fatal error (E_COMPILE_ERROR) and stop the
script from executing

• include will only produce a warning (E_WARNING) and the script will
continue

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 65
PHP File Upload
 PHP offers a robust mechanism for handling file uploads from
web forms. Here's a breakdown of the key steps involved:
1. HTML Form Creation:
• Construct an HTML form element with the <form> tag.
• Set the action attribute to the PHP script that will process
the upload.
• Use the method attribute and set it to POST (standard for file
uploads).
• Include a file input field using the <input type="file"
name="filename"> element, where filename is the name you'll
reference in your PHP script.
• Add a submit button using the <input type="submit"
value="Upload"> element.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 66
PHP File Upload

2. PHP Script for Handling Upload:


• Create a PHP script (e.g., upload.php) to receive and process
the uploaded file.
• Access the uploaded file information using the super global
array $_FILES.
• Key considerations and security measures:
• Check for upload errors using $_FILES['myfile']['error'].
Common errors include file size exceeding limits or
unsuccessful upload.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 67
PHP File Upload

• Validate the uploaded file type using $_FILES['myfile']


['type']. However, don't rely solely on this as clients
can manipulate it.
• Restrict file size using $_FILES['myfile']['size'].
• Generate a unique filename to prevent overwriting
existing files (e.g., using uniqid() or time()).
• Sanitize the filename to remove special characters that
could compromise the server (e.g., using pathinfo() and
strtolower()).
• Choose an appropriate upload directory with proper
access permissions.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 68
PHP File Upload

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 69
PHP File Upload

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 70
PHP File Upload

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 71
PHP Date() Function
 The date() function is used to format a time or a date.
 Syntax: string date (format,timestamp)
• This function returns a string formatted according to the
specified format.
 The format parameter in the date() function specifies the format of
returned date and time.
 The timestamp is an optional parameter, if it is not included then
the current date and time will be used.
 PHP Date() - Format the Date
• The required format parameter in the date() function specifies how
to format the date/time.
• Here are some characters that can be used:
• d - Represents the day of the month (01 to 31)
• m - Represents a month (01 to 12)
• Y - Represents a year (in four digits)
@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 72
PHP Date() Function
 Other characters, like"/", ".", or "-" can also be inserted
between the letters to add additional formatting:
 Example 1.
< ?php
echo date("Y/m/d") . "<br />";
echo date("Y.m.d") . "<br />";
echo date("Y-m-d");
?>
• The time() function is used to get the current time as a
Unix timestamp
 The mktime() function is used to create the timestamp for a
specific date and time
 Syntax: mktime(hour, minute, second, month, day, year)

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 73
PHP Date() Function
 Example 2
<?php
//Prints something like: Monday
echo date("l");

//Prints something like: Monday 15th of January 2003 05:51:38 AM


echo date("l F Y h:i:s A");

//Prints something like: Monday the 15th


echo date("l \\t\h\e jS");
?>

 Write a program that will output "Have a good morning!" if the


current time is less than 10, and "Have a good day!" if the current
time is less than 20. Otherwise it will output "Have a good night!"
@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 74
PHP Cookies
 A cookie is often used to identify a user.
 A cookie is a small file that the server embeds on the user's computer.
 Characteristics:
 Storage: Cookies are stored on the client-side (browser).
 Size Limit: Limited to a few kilobytes.
 Lifetime: Can have an expiration date, allowing them to persist
for a specific duration or until the browser is closed.
 Accessibility: Can be accessed both on the client and server
side.
 Purpose: Often used for tracking user preferences, storing
session identifiers, and implementing features like "Remember
Me."
• Cookies are typically sent with every HTTP request to the same
domain, allowing the server to recognize the client.
@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 75
PHP Cookies
 Cookie Properties and Methods
• setcookie() Options:
• Name: is the name of the cookie used by the server for
retrieving(mandatory).
• Value: is the value of the cookie.
• Expire: is the expiration timestamp.
• Path: is the path on the server for which the cookie will be
available.
• Domain: is the domain for which the cookie is available(cookie
access hierarchy).
• Secure: is a Boolean indicating if the cookie should only be
sent over secure connections (HTTPS).
• Httponly: is a Boolean indicating if the cookie should be
accessible only through the HTTP protocol, not client side
scripting. i.e. javascript.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 76
PHP Cookies
 Creating a Cookie:
• setcookie(name, value, expire, path, domain, secure, httponly): Sets a
cookie with the specified parameters.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 77
PHP Cookies
 we use the isset() function to find out if a cookie has been set
 Retrieving a Cookie:
• $_COOKIE: An associative array containing all cookies sent by the
client.

 Modifying a Cookie:

 Deleting a Cookie:
• Setting the expiration time to a past value deletes the cookie.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 78
PHP Session
 A session is a way to store information on the server side that
persists across multiple requests from the same user during a
defined session.
 Characteristics:
• Storage: Information is stored on the server side.
• Size Limit: Generally has a higher limit compared to cookies.
• Lifetime: Usually tied to the user's session and expires when the
user closes the browser or remains inactive for a specified
period.
• Accessibility: Accessed and managed on the server side.
• Purpose: Used to maintain user-specific data, such as login
information, throughout a user's interaction with a website.

 Sessions are often used for more sensitive information that


shouldn't be exposed on the client side.
@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 79
PHP Session

 Session Properties and Methods


• session_start(): Initiates a new session or resumes the existing
session.
• $_SESSION: An associative array used to store session variables.
• session_destroy(): Destroys all data registered to a session.
• session_unset(): Unsets all session variables.
• session_id(): Gets or sets the session ID.
• session_name(): Gets or sets the session name.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 80
PHP Session
 Starting a Session

 Storing Data in a Session

 Retrieving Data from a Session

 Ending a Session

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 81
PHP Session

 Session Configuration:
• session_save_path(): Gets or sets the current session save path.
• session_set_save_handler(): Sets user-level session storage
functions which are used for storing and retrieving data
associated with a session.

 Session Security:
• session_regenerate_id(): Updates the current session id with a
newly generated one.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 82
PHP Session
 Handling Session Timeout

 Handling Session Variables Safely


 Validating Session Variables

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 83
PHP Session

 Session Hijacking Prevention


 Session ID Regeneration

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 84
File Handling with PHP

 In PHP, file handling is a common task that involves reading


from and writing to files on the server or local machine.
 PHP provides a set of functions for handling files.

 Here are some basic file handling operations using PHP:


• Opening and Closing Files
• Reading from Files
• Writing to a File

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 85
File Handling with PHP

 Opening and Closing Files:


• fopen() - Open a file or URL

• fclose() - Close an open file pointer

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 86
File Handling with PHP

 Reading from Files:


• fread() - Read from an open file

• fgets() - Read a line from an open file

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 87
File Handling with PHP

 Reading from Files:


• file_get_contents() - Read entire file into a string

• file() - Reads entire file into an array

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 88
File Handling with PHP

 Write to Files:
• fwrite() - Write to an open file

• file_put_contents() - Write data to a file

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 89
File Handling with PHP

 File Modes:
• Read Modes:
• 'r': Open for reading.
• 'r+': Open for reading and writing.
• Write Modes:
• 'w': Open for writing. If the file doesn't exist, create it.
If it exists, truncate it.
• 'w+': Open for reading and writing. If the file doesn't exist,
create it. If it exists, truncate it.
• Append Modes:
• 'a': Open for writing. If the file doesn't exist, create it.
If it exists, move the file pointer to the end.
• 'a+': Open for reading and writing. If the file doesn't exist,
create it. If it exists, move the file pointer to the end.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 90
File Handling with PHP

 Checking File Existence:


• file_exists() - Checks whether a file or directory exists

 Deleting Files:
• unlink() - Deletes a file

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 91
File Handling with PHP
 Handling Errors:
• feof() - Tests for end-of-file on a file pointer

 File Information:
• filesize() - Gets the size of the file

• filemtime() - Gets the last modification time of the file

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 92
File Handling with PHP
 Directory Operations:

• opendir() and readdir() -


Open and read from a
directory

• scandir() - List files and


directories inside a path

• mkdir() - Create a directory

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 93
File Handling with PHP
 File Copy and Rename:
 copy() - Copy a file

 rename() - Rename a file

 rmdir() - Remove a directory (if it's empty)

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 94
File Handling with PHP

 File and Directory Deletion:


 unlink() and rmdir() together - Recursively delete files and
directories

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 95
PHP Mathematical Functions
 PHP provides a variety of mathematical functions to perform
operations like basic arithmetic, rounding, logarithmic
functions, trigonometry, etc.
 Basic Arithmetic Functions:
• abs(number): Returns the absolute (positive) value of a number.
• ceil(number): Rounds a number up to the nearest integer.
• floor(number): Rounds a number down to the nearest integer.
• round(number, precision): Rounds a number to a specified
precision (optional second argument).
• exp(number): Calculates the exponent of e (Euler's number) raised
to the power of number.
• log(number, base): Calculates the logarithm of number to a
specified base (optional second argument, defaults to base 10).
• log10(number): Calculates the base-10 logarithm of number.
• pow(number, power): Raises number to the power of power.
@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 96
PHP Mathematical Functions
 Basic Arithmetic Functions:

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 97
PHP Mathematical Functions

 Trigonometric Functions (operate in radians):


• sin(angle): Sine of an angle.
• cos(angle): Cosine of an angle.
• tan(angle): Tangent of an angle.
• asin(number): Arcsine (inverse sine) of a number.
• acos(number): Arccosine (inverse cosine) of a number.
• atan(number): Arctangent (inverse tangent) of a number.
• atan2(y, x): Arctangent of y divided by x (useful for calculating
angles in two dimensions).
• deg2rad(degrees): Converts degrees to radians.
• rad2deg(radians): Converts radians to degrees.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 98
PHP Mathematical Functions
 Trigonometric Functions (operate in radians):

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 99
PHP Mathematical Functions

 Other Mathematical Functions:


• pi(): Returns the value of pi (approximately 3.14159).
• sqrt(number): Calculates the square root of a number.
• min(number1, number2, ...): Returns the smallest of a list of
numbers.
• max(number1, number2, ...): Returns the largest of a list of
numbers.
• rand(min, max): Generates a random integer between min
(inclusive) and max (exclusive). Use mt_rand() for more secure
random number generation.
• is_finite(number): Checks if a value is a finite number (not
infinite or NaN).
• is_infinite(number): Checks if a value is positive or negative
infinity.
• is_nan(number): Checks if a value is Not a Number (NaN).
@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 100
PHP Mathematical Functions

 Other
Mathematical
Functions:

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 101
PHP OOP
 OOP is a programming paradigm that uses objects and classes to structure code.
 Procedural programming is about writing procedures or functions that perform
operations on the data, while OOP is about creating objects that contain both
data and functions.

 Classes & objects are the two main


aspects of object-oriented
programming.
 Class: is a blueprint/templet for
creating objects.
 It defines properties (attributes) and
methods (functions) that the objects will
have.
 Object: is an instance of a class. It
represents a specific entity with its own
set of properties and behaviors.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 102
PHP OOP

 Object-oriented programming has several advantages over


procedural programming:

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes
the code easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less
code and shorter development time

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 103
PHP OOP
Constructors and destructors helps for reducing the amount of code.

 Constructor: is a special
method called when an object
is created.
 It is mainly used to
initialize object properties
upon creation of the object.

 Destructor: is a special
method called when an object
is destroyed/exited.
 It is automatically called at
the end of the script & used for
cleanup tasks
@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 104
PHP OOP
Basic OOP Concepts
 Encapsulation: is the bundling of
data (properties) and methods that
operate on the data into a single
unit (class).
 Wrapping up data member and method
together into a single unit
 Enclosing the internal details of
the object to protect from external
sources

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 105
PHP OOP
Basic OOP Concepts …
 Inheritance: allows a class
(subclass/derived class) to
inherit properties and
methods(Public/protected)
from another class
(superclass/base class).
 An inherited class is defined
by using the extends keyword.
 Inherited methods can be
overridden by redefining the
methods (use the same name)
in the child class.
 What is Final keyword.
@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 106
PHP OOP
Basic OOP Concepts …
 Polymorphism: allows objects of different
classes to be treated as objects of a
common superclass. It involves method
overriding.
 the ability of objects of d/t classes to
take on different forms and exhibit
different behaviors while sharing a common
interface.
 allows methods to perform different
actions based on the object they are
called upon, enhancing code flexibility
and reusability.
Q. What is the difference between Compile-time polymorphism
(Overloading) and Run-time polymorphism(overriding)?
@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 107
PHP OOP
Basic OOP Concepts …
Interfaces and abstract classes can also facilitate polymorphism

 Abstraction: involves hiding the


complex implementation details and
showing only the necessary features of
an object.
 An abstract class is a class that
contains at least one abstract method.
 An abstract method is a method that is
declared, but not implemented in the
code.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 108
PHP OOP
Basic OOP Concepts …
 Interfaces: define a contract for
classes that implement them. They
ensure that classes have specific
methods.
 Multiple classes can implement the
same interface, enabling
polymorphism by treating different
objects as instances of the same
interface.

Q. What is the difference & similarities between abstract class


and interfaces?
@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 109
PHP OOP
Basic OOP Concepts …

 Static methods and


properties belong to
the class rather than
instances. They can
be accessed without
creating an object.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 110
PHP OOP
Basic OOP Concepts …

 Access/Visibility modifiers:
control the access level of
properties and methods.
 public: Accessible from
anywhere.
 protected: Accessible within
the class and its subclasses.
 private: Accessible only
within the class.

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 111
PHP OOP
Basic OOP Concepts …

 Example:
Creating, Using,
and Extending
Classes:

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 112
Reading assignment on other OOP concepts: -
• Aggregation
• Association
• Composition
• Namespaces
• Traits
• Constants

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 113
Thank You!!!
Question???

@ WDU: WiT: School of Computing: Programming Chair 2024 Hypertext Preprocessor (PHP): Chapter 5
Slide 114

You might also like