You are on page 1of 123

WEB PROGRAMMING

Client/Server technology

Safar M. Asaad

Aynda Private Technical Institute


IT Department
Outline
■ Course Overview
■ Course Objectives
■ Course Prerequisites
■ Teaching Methodology
■ Course Rules and Policies
■ Assessment
■ Syllabus
■ Client/server technology
■ Categories of C/S Computing
Course Overview
■ This course will teach students the skills and techniques necessary for creating sophisticated and

accessible interactive dynamic web applications.

■ It focuses on the server-side languages, tools, and libraries that professionals use to build the

web sites that are used every day.

■ Students will learn not only the basic syntax and mechanics of dynamic web development, but

also the best practices that separate professional developers from amateurs.

■ Upon completing this course, students will be able to build robust web applications, and will

have the foundation for independently learning new skills in the every-changing world of web

development.

■ Advanced Web Development (with PHP, MySQL) course provides students an opportunity
to build a Great Career in web and eCommerce web application development world,

■ Program is covering PHP, MySQL and Website Design Concepts and common tasks need
for deployment and administration of a website
Course Aims
■ This Course gives the students skills in the following:
1. creating rich-featured dynamic websites and web portals.
2. Understand the major areas and challenges of dynamic web
programming.
3. Distinguish web-related technologies.
4. Use advanced tools and techniques in server side web
development
5. Use a server-side scripting language, PHP
6. Use a relational DBMS, MySQL
7. Use PHP to access a MySQL database.
8. Understanding and managing the web content (CMS)
9. Design and implement
■ dynamic web applications.
■ web applications that use asynchronous communication.
■ secure 3-tier data-driven web applications.
Prerequisites
■ Basic knowledge of computer and internet

■ Good knowledge of fundamental programming concepts (loops,


conditionals, arrays, objects, functions)

■ Good knowledge of object-oriented programming features (i.e., build


classes, instantiate objects, leverage the this keyword, etc.)

■ Ability to build basic static front-end websites using HTML, CSS and
JavaScript. Ability to use and configure HTML tags (attributes) and
listen to DOM events.

■ Good knowledge of asynchronous JavaScript calls with callbacks and


async/await syntax.
Module Learning Outcomes
■ Through this module, you will learn how to build dynamic,
data-driven websites using databases, front-end frameworks
and server-side programming.

■ This module provides the skill set required to do full stack web
development work.
Teaching Methodology
■ The syllabus will be entirely covered in class, using

– PPT presentation and projector tool to view the slides of the


topics,
– the pen and whiteboard will also be used to make a frequent step
by step communication with the students,
– solving assignments and problem sets.

– All course materials, e.g., books, articles, slides and videos are
available on the class website (Moodle) which can easily be
downloaded by students at any time.

– Therefore, the students should visit and read the content of the
class website regularly.
Course Rules and Policies
■ It is highly recommended for the students to be in the
classroom in its starting time.
■ Students can ask the lecturer to leave the classroom for
reasonable excuse.
■ Students are not allowed to use smart devices during the class,
such as; cell phone, laptop, tablets ... etc.
■ Marks may or may not be awarded for attendance, but Marks
are absolutely awarded for class participation.
■ Students are allowed to come to my office during office hours.
■ For further questions or feedback, you can always contact me
through (safar.maghdid@koyauniversity.org)
Syllabus
■ The basic principles of client/server computing;
– Distinguished characteristics of client/server systems and
application areas;
– Comparison of 2 tier versus three tier client/server solutions;
Web programming model; Interactive web.

■ An Overview of Modern HTML, CSS and JavaScript.

■ Server-Side Web Programming:

– Approaches to server-side programming.

– Benefits and limitations of server-side web programming.

– Development framework for server-side programming based on


PHP.
Syllabus
■ Server-Side Scripting using PHP (Starting with PHP statements,
codes, blocks, comments, variables, and operators).

■ More programming in PHP - covering PHP control statements and


PHP loops.

■ More programming in PHP - covering PHP Strings, and data


processing with arrays and Functions.

■ PHP Form processing, Session control and Cookies.

■ Mid-Term Exam

■ PHP Exception Handling…catching statement, and throwing


statement.

■ Object Orientation Programming with PHP.


Syllabus
■ Working with database:
– Introduction to Database:
■ File and database processing systems;
■ Definition of database;
■ DBMS examples.
■ Data Modelling:
– Entity relationship model;
– Elements of the E.R. model.
Syllabus
■ Working with MySQL DBMS:
– SQL statements for data manipulation,
– Introduction to MySQL,
– How to use PHP to access MySQL: MySQL database
creation, editing database and tables, primary key, foreign
key, inserting, updating, deleting data to the DB and
finally Creating ERD (Entity Relationship Diagram).
■ An Introduction to SQL injection and data binding, types of
PHP data binding and how data binding works.
Syllabus
■ Functions Advanced Web Programming- (Secure communication and
encryption/decryption, Regular expression, Session management and
timeout, Pushing data to client, Asynchronous communications with
JSON, XML, and AJAX, Server-Sent Event (SSE), Development of
API using classes and objects and Other miscellaneous topics)

■ Preparatory Week

■ Final Exam
Assessment
■ Mid-term Exam
– Lab Exams (15%)
– Theoretical Exam (10%)
– Activities (35%)
■ Projects
■ Seminars
■ Attendance
■ Report
■ Quiz

■ Final Exam
– Theoretical (15%)
– Practical (25%)
client/server technology
■ Systems architecture describing technologies that cooperate
together on a computer network

■ users operate PCs (clients) that connect to central computers


(servers) over a computer network

■ both computers cooperate to spilt the work of performing


various tasks
Client/Server Computing
■ Model of computing in which very powerful personal
computers (clients) are connected in a network with one or
more server computers that perform common functions for the
clients, such as storing files, software applications, etc.

■ Primary way of delivering computing power to the desktop


Client
■ User point of entry into a network

– normally a desktop computer, workstation, or laptop

■ User generally interacts directly only with the client portion of


an application.

– Clients provide user interface - GUI - graphical user


interface
■ Users use desktop computers to do much of their work locally
■ When they need to access shared information or to use
resources of another (more powerful) machine, they connect
their desktop (client) machine to the remote machine (server)
using a network.
■ run the client side of client-server applications
Server
■ Satisfies some or all of a user’s request for data

– runs the application software

■ Can be a mainframe or another desktop computer

■ Servers store and process shared data.


– shared resources that are accessible over the network; used
by clients
■ combine both hw and sw
■ clients contact servers with requests
■ servers process the request and return the results to the clients
■ many clients use the server; end-users can share information
by accessing a common database (stored on the client)
Characteristics of C/S Computing
■ The c/s computing works with a system of request and response.
– The client sends a request to the server, and the server responds with
the desired information.

■ The client and server should follow a common communication protocol.


– So they can easily interact with each other.
– All the communication protocols are available at the application layer.

■ A server can only accommodate a limited number of client requests at a time.


– So it uses a system based on priority to respond to requests.

■ Denial of Service attacks servers' ability to respond to authentic client requests


by inundating them with false requests.

■ An example of a client-server computing system is a web server.


– It returns the web pages to the clients that requested them.
Difference between C/S Computing and
P2P Computing
■ In C/S computing, a server is a central node that services many
client nodes. While in a P2P system, the nodes collectively use
their resources and communicate with each other.

■ In C/S computing, the server is the one that communicates with


the other nodes. In peer-to-peer computing, all the nodes are
equal and share data with each other directly.

■ C/S computing is a subcategory of the peer to peer computing.


Advantages of C/S Computing
■ All the required data is concentrated in a single place i.e. the server.

– So it is easy to protect the data and provide authorisation and


authentication.

■ The server need not be located physically close to the clients.

– Yet the data can be accessed efficiently.

■ It is easy to replace, upgrade or relocate the nodes (clients) in the


client server model because all the nodes are independent and request
data only from the server.

■ All the clients and server may not be build on similar platforms yet
they can easily facilitate the transfer of data.
Disadvantages of C/S Computing
■ If all the clients simultaneously request data from the server, it
may get overloaded.

– This may lead to congestion in the network.

■ If the server fails for any reason, then none of the requests of
the clients can be fulfilled.

– This leads of failure of the client server network.

■ The cost of setting and maintaining a client server model are


quite high.
Categories of C/S Computing
■ There are four main categories of client-server computing:

– One-Tier architecture: consists of a simple program running on


a single computer without requiring access to the network.

■ User requests don’t manage any network protocols, therefore


the code is simple and the network is relieved of the extra
traffic.

– Two-Tier architecture: consists of the client, the server, and the


protocol that links the two tiers.

■ The Graphical User Interface code resides on the client host


and the domain logic resides on the server host.
Categories of C/S Computing
■ Three-Tier architecture: consists of

– a presentation tier, which is the User Interface layer,

– the application tier, which is the service layer that performs detailed processing,

– and the data tier, which consists of a database server that stores information.

• A web-based patient appointment application for a medical


center, which enables patients to schedule appointments with
doctors and specialists
• the graphical interface of the web browser can be adjusted to
work on different computing devices such as laptops or
phones, without affecting the other tiers.
• The logic tier connects to the presentation tier and consists
of user authorization processes. In addition, there are
scheduling and validation forms on a web server hosted on a
different machine.
• the logic tier connects to the data tier and consists of a
MySQL database hosted on another machine. The database
hosts the details of patients, doctors and specialists. It also
contains information on available times for each of the
doctors and specialists. Here, the appointment scheduled by
the user is also saved on the database.
Categories of C/S Computing
■ N-Tier architecture: An N-tier architecture divides an application into
logical layers and physical tiers.

– logical layers separate responsibilities and manage dependencies,

– physical tiers run on separate machines, improve scalability, and add


latency from the additional network communication (increase in latency due
to the physical separation of components)

– N-Tier architecture can be


■ closed-layer, in which a layer can only communicate with the next layer
down, or
■ open-layer, in which a layer can communicate with any layers below it.
WEB PROGRAMMING
An Introduction to PHP

Safar M. Asaad

Aynda Private Technical


Institute IT Department
Outline
■ Server-Side Web programming
– Static and Dynamic websites
■ PHP functions.
■ Why Learn PHP?
■ What do You Need?
■ Comments
■ Variables & Values.
– String
– Numbers
– Booleans
– Null
– Array
■ Operations
■ Functions
Server-Side Web programming
■ Web browsers communicate with web servers using HTTP.
– When user click a link on a web page, submit a form, or run a search, an
HTTP request is sent from your browser to the target server.

■ The request includes


– URL identifying the affected resource,

– method that defines the required action (get or post methods),

– and may include additional information encoded in URL parameters (the field-
value pairs sent via a query string),

– and/or cookie data

■ Web servers wait for client request messages, process them when they arrive,
and reply to the web browser with an HTTP response message.
– The response contains a status line indicating whether or not the request
succeeded (e.g. "HTTP/1.1 200 OK" for success).
Static sites
■ A static site is one that returns the same hard-coded content from the
server whenever a particular resource is requested).

■ When a user wants to navigate to a page, the browser sends an HTTP


"GET" request specifying its URL.

■ The server retrieves the requested document from its file system and returns
an HTTP response containing the document and a success status (usually 200
OK).

■ web server architecture


for a static site
Dynamic Sites
■ A dynamic website is one where some of the response content
is generated dynamically, only when needed.

■ On a dynamic website HTML pages are normally created by inserting


data from a database into placeholders in HTML templates

– this is a much more efficient way of storing large amounts of


content than using static websites.

■ Most of the code to support a dynamic website must run on the server.

– Creating this code is known as "server-side programming" or


"back-end scripting".
Dynamic Sites
■ The diagram below shows a simple architecture for a dynamic
website.
Front End and Back End Engineering
■ The components of a webserver is divided into two distinct parts:
– front-end

– back-end.

■ front-end developer
– The Front End consists of the HTML, CSS, and any Client-Side Programs
(i.e., JavaScript).
■ back-end developer
– The Back End consists of Server-Side Programs and the Database

– Back-end engineers would also work on


■ server-side configuration,

■ load balancing,
■ content delivery network (CDN) and
■ server infrastructure issues.
Basic Models of Server-Side Programming
■ Two traditional methods for creating a webpage server-side.

1. HTML with Server-Side Code Added


■ With this approach a webpage on the server-side looks almost like a
tradition HTML file, except in a few places, we ask the server to insert new
information based on code executed on the server.

2. Server-Side Code Generating HTML

■ In this approach we generate a new HTML file from scratch.


Server-Side Programs
PHP
PHP
■ PHP stands for "PHP Hypertext Preprocessor”

■ PHP is a widely-used, open source scripting language

■ An HTML-embedded server-side scripting language

■ used to make web pages dynamic

– process form information

– authenticate users

– provide different content depending on context interface with


other services: database, e-mail, etc.

■ generates HTML and/or client-side scripts sent to client browsers

■ similar syntax to JavaScript


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

■ With PHP you are not limited to output HTML. You can output
images, PDF files, and even Flash movies. You can also output any
text, such as XHTML and XML.
Why PHP?
■ Many other options: ASP.NET, ColdFusion, JSP...

■ PHP is:

– free and open source: anyone can run a PHP-‐enabled server.

– compatible with almost all servers used today (Apache, IIS, etc.)

– simple: lots of built-‐in functionality;

– familiar syntax.

– PHP supports a wide range of databases

– PHP runs on various platforms (Windows, Linux, Unix, Mac OS X,


etc.)
Why use PHP instead of JavaScript?
■ PHP has access to server's important and/or private data

■ avoids many browser JS compatibility issues

■ faster for users (browsers) (doesn't have to run a script to view


each page)

■ client can't see your source code.

■ fewer security restrictions (can write to files, open web pages


on other servers, connect to databases, ...)
Similarities between PHP and JavaScript
■ Interpreted

■ Relaxed syntax and rules

 "loose" data types

 variables don't need to be declared (initialized to NULL)

■ variable names case sensitive

■ built-‐in regular expressions


PHP files
■ generally have .php

■ generally contain both HTML and PHP

■ when a client views the source, only HTML is visible.

■ all PHP script blocks start with <?php and end with ?>, which can be
put any where in the file.

<?php

// PHP code goes here

?>
A typical web server request using PHP

■ browser requests a .html file (static content): server just sends that file.

■ browser requests a .php file (dynamic content): server reads it, runs
any script code inside it, then sends result across the network
■ script produces output that becomes part of the HTML page
What Do You Need?
■ To start using PHP, you can:

o Find a web host with PHP and MySQL support, OR

o install a web server on your own PC, and then install PHP
and MySQL.

■ Alternatively, You can Install WAMP Server, For


Windows OS, which contains PHP and MySQL as well.

■ Or You can use MAMP, For Mac OS.

■ Or YOU CAN USE XAMMP FOR BOTH OPERATING


SYSTEMS.
Installing WAMP Server to run PHP
1. Goto www.wampserver.com and download WAMP Server.
2. install it like other softwares by just clicking next, next…
3. Now go to START menu of windows and start wampserver.
4. Generally, the path is Start -‐> WapmServer -‐> start WampServer
5. Open your web browser and type http://localhost (or http://127.0.0.1 )
6. If you see a default WampServer home page, you installation is success.
7. Put your php code in www folder in your wamp installation directory.
8. Usually this is C:\wamp\www
9. Now type http://localhost/filename.php in your browser. (where
filename is your php file name). It will execute your php code.. Thats
it...
■ You can start or stop your server via an icon in the bottom right, where
the clock is.
Comments in PHP
 Standard C, C++, and shell comment symbols:

// C++ and Java-style single line comment

# Shell-style single line comment

/* C-style comments
These can span multiple lines */
PHP echo and print Statements
■ print are more or less the same.
o They are both used to output data to the screen.
o They can be used with or without parentheses.
 Echo “hi”; or echo(“hi”);
o They can contain HTML markup.

■ The differences are small:


 echo has no return value while print has a return value of 1 so it
can be used in expressions.
 echo can take multiple parameters, while print can take one
argument.
 echo is marginally faster than print.
Creating (Declaring) PHP Variables
■ In PHP, a variable starts with the $ sign, followed by the name of the
variable.

■ Rules for PHP variables:


– A variable starts with the $ sign, followed by the name of the
variable.
– A variable name must start with a letter or the underscore
character.
– A variable name cannot start with a number.
– A variable name can only contain alpha-‐numeric characters
and underscores (A-‐z, 0-‐9, and _ ).
– Variable names are case-‐sensitive ($age and $AGE are two
different variables).
Creating (Declaring) PHP Variables
• Example:
<?php
$txt = "Hello world!"; //holds the value Hello world!
$x = 5;
//holds the value 5
$y = 10.5;
echo $txt ; //holds the value 10.5
echo $x, $y;
?>
■ Note: When you assign a text value to a variable, put quotes
around the value.
■ Note: Unlike other programming languages, PHP has no
command for declaring a variable. It is created the moment
you first assign a value to it.
PHP Case Sensitivity
■ In PHP, all keywords (e.g. if, else, while, echo, etc.), classes,
functions, and user-‐defined functions are NOT case-‐sensitive.
<html><body>
• For example, all three echo <?php
statements are legal (equal): ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body></html>

• However; all variable names are


<?php
case-sensitive.
$color = "red";
• $color, $COLOR, and echo "My car is " . $color . "<br>";
$coLOR are treated as three echo "My house is " . $COLOR . "<br>";

different variables echo "My boat is " . $coLOR . "<br>";


?>
PHP Data Types
• Variables can store data of different types, and different data
types can do different things.

• PHP supports the following data types.

1. String

2. Numbers

3. Boolean

4. Array

5. Object

6. NULL
String
A string is any characters between two quotes,
For Example:

– “This is a string ”,
– ʻThis is also a stringʼ
• Example:

<?php
$fName=“Azad”;
$sName=‘Ahmed’
Echo “Hello ”. $fName.” “.$sName;
?>
Numbers
 There are only two types of numbers:

 Integer number

 Floating point number.

 You donʼt have to worry about those types, because PHP will
convert back and forth when necessary.

 Example: <?php
$Number=10;
$Number2=10.3;
Echo $Number.”<br>”.$Number2 ;
?>
Boolean
 Boolean has two values:
1. True

2. False

 Those are keywords in PHP which means you cannot use them
for anything other than Boolean values.

 Example:

<?php
$students=TRUE;
Echo $students;
?>
Null
 This is the data type that represents nothing: the valueless value.

 That is a keyword too.

 Example:

<?php
$will_be_null;
?>
Array
 It is the most complex type that we have looked at yet, and that
is because it can be made up of other variable types that we
have looked at.

 Example:

<?php
$cars = array("Volvo","BMW",2.6, true, null, array(6,7));
var_dump($cars);
?>

 The PHP var_dump() function returns the data type and


value.
Array
There are three types of array:
1. Indexed arrays -‐ Arrays with a numeric index
2. Associative arrays -‐ Arrays with named keys
3. Multidimensional arrays -‐ Arrays containing one or more
arrays
Indexed arrays
 By default, arrays use numerical indices;

 The indices start at 0, not 1.

 Example: <?php
$an_array= array(”PHP","BMW",2.6, true, null,);
?>

$an_array[0] holds the value PHP.

$an_array[2] holds the value 2.6.

 This is also a way to get the values out of an array.


Associative arrays
• Use strings as their indices; Of course, you have to define a
string for each value you put in the array.
• Example: <?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

Or
<?php
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43”;
?>
Multidimensional arrays
• A multidimensional array is an array containing one or more arrays.
• PHP understands multidimensional arrays that are two, three, or more
levels deep. However, arrays more than three levels deep are hard to
manage for most people.
• The dimension of an array indicates the number of indices you
need to select an element.
• For a two-‐dimensional array you need two indices to select an
element
• For a three-‐dimensional array you need three indices to select an
element

$cars = array( array("Volvo",22,18),


array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2]."<br>”;
Objects

More About PHP Objects in the next


lectures.
PHP Operators
 Operators are used to perform operations on variables and
values.

 PHP divides the operators in the following groups:

1. Arithmetic operators
2. Assignment operators

3. Comparison operators
4. Increment/Decrement operators
5. Logical operators

6. String operators
7. Array operators
Arithmetic operators
 Arithmetic operators are used with numeric values to perform
common arithmetical operations:
Assignment operators
 assignment operators are used with numeric values to write a
value to a variable:
Comparison operators
 comparison operators are used to compare two values (number
or string):
Increment/Decrement operators
• They are used to increment/decrement a variable's value:
Logical operators
• logical operators are used to combine conditional statements
String operators
• PHP has two operators that are specially designed for strings
Array operators
• The PHP array operators are used to compare arrays
PHP Conditional Statements
1. if statement -‐ executes some code only if a specified condition
is true
2. if...else statement -‐ executes some code if a condition is true
and another code if the condition is false
3. if...elseif....else statement -‐ specifies a new condition to test, if
the first condition is false
4. switch statement -‐ selects one of many blocks of code to be
executed
PHP Conditional Statements
1. if statement: 2. if...else statement:
<?php <?php
$a=5; $b=2; $a=5; $b=2;
if ($a > $b) { if ($a > $b) {
echo "a is bigger than b"; echo "a is bigger than b";
} } else {
?> echo "a is smaller than b”; }
?>

3. if...elseif....else statement:
<?php
$a=5; $b=2;
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b”; }
?>
PHP Conditional Statements
• switch statement

<?php
$destination = "Tokyo";
echo "Traveling to”. $destination.”<br />";
switch ($destination){
case "Las Vegas”: echo "Bring an extra $500”;
break;
case "Amsterdam”: echo "Bring an open mind”;
break;
case "Egypt”: echo "Bring 15 bottles
Water”; break;
case "Tokyo”: echo "Bring lots of money";
break;
case "Caribbean Islands”: echo "Bring a swimsuit";
break;
Default: echo “ Have a good journey”;
}
?>
PHP Loops
• In PHP, we have the following looping statements:

1. while -‐ loops through a block of code as long as the


specified condition is true.

2. do...while -‐ loops through a block of code once, and then


repeats the loop as long as the specified condition is true.
3. for -‐ loops through a block of code a specified number of
times

4. foreach -‐ loops through a block of code for each element


in an array
while Loops

1. While: <?php
$x = 1;
while($x <= 5) {
echo "The number is:”. $x.” <br>";
$x++;
}
?>

2. do...while:
<?php
$x = 6;
do {
echo "The number is:”. $x.” <br>";
$x++;
} while ($x <= 10);
?>
for Loops
<?php
3. for: for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>

Syntax
4.foreach: foreach (array_expr as $value)
{
statement
}
Example
<?php
$fruits = array ("Orange", "Apple", "Banana”, "Cherry", " Mango");
foreach ( $fruits as $value )
{
echo "$value<br />”;
}?>
Loop Through an Array
<?php
Indexed Array: $cars = array("Volvo", "BMW", "Toyota");
The count() function is used to $arrlength = count($cars);
return the length (the number of
for($x = 0; $x < $arrlength; $x++)
elements) of an array
{ echo $cars[$x]; echo "<br>";
} ?>
 Associative Array:

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value; echo "<br>";
}
?>
PHP Variables Scope
■ In PHP, variables can be declared anywhere in the script.
■ PHP has three different variable scopes:
1. Global
■ A variable declared outside a function has a GLOBAL
SCOPE and can only be accessed outside a function
2. Local
■ A variable declared within a function has a LOCAL
SCOPE and can only be accessed within that function:
3. Static
■ when a function is completed/executed, all of its
variables are deleted. However, sometimes we want a
local variable NOT to be deleted. We need it for a
further job.
■ To do this, use the static keyword when you first
declare the variable
Global and Local Scope
<?php
$x = 5; // global scope

function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
Note: myTest();
echo "<p>Variable x outside function is: $x</p>";
You can have local ?>
variables with the same
<?php
name in different function myTest() {
functions, because local $x = 5; // local scope
variables are only echo "<p>Variable x inside function is: $x</p>";
recognized by the }
function in which they myTest();
are declared. // using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
The global Keyword
<?php
■ The global keyword is used to access a $x = 5; $y = 10;
global variable from within a function. function myTest() {
global $x, $y;
■ To do this, use the global keyword before $y = $x + $y;
the variables (inside the function) }
myTest();
echo $y; // outputs 15
?>
■ PHP also stores all global variables in an array called
$GLOBALS[index].
■ The index holds the name of the variable.
<?php
■ This array is also $x = 5; $y = 10;
accessible from within function myTest() {
functions and can be $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
used to update global }
myTest();
variables directly. echo $y; // outputs 15
?>
PHP The static Keyword
■ Then, each time the function <?php
function myTest() {
is called, that variable will
static $x = 0;
still have the information it echo $x;
contained from the last time $x++;
}
the function was called.

■ Note: The variable is still myTest();


myTest();
local to the function.
myTest();
?>
WEB PROGRAMMING
More Advanced PHP

Safar M. Asaad

Aynda Private Technical Institute


I.T Department
Outline
■ PHP function.

■ PHP Constants

■ Get and POST HTTP Methods

■ Interacting with Forms.

■ PHP File Inclusion

■ PHP Sessions
PHP Functions
1. The built-in PHP functions
2. PHP User Defined Functions
 Besides the built-in PHP functions, we can create our own
functions.
 A function is a block of statements that can be used repeatedly
in a program whenever needed.
 A function will not execute immediately when a page loads.
 A function will be executed by a call to the function.
 Syntax: Function names are
NOT case-sensitive
function functionName(arguments) {
code to be executed;
}
PHP Functions-Examples
 Example 1 : -
<?php
A function with two function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
arguments ($fname and }
familyName("Hege", "1975");
$year). familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>

<?php
 Example 2:- function setHeight($minheight = 50)
{ echo "The height is : $minheight <br>";
}
A function with a Default setHeight(350);
setHeight(); // will use the default value of 50
Argument Value setHeight(135);
setHeight(80);
?>
PHP Functions-Examples
■ Example 1 : -

<?php
function mySum($numX, $numY){
$total = $numX +
$numY; return $total;
}
$myNumber = 0;
echo "Before the function, myNumber = ". $myNumber ."<br />";
$myNumber = mySum(3, 4); // Store the result of mySum in
$myNumber
echo "After the function, myNumber = " . $myNumber ."<br />";

?>

■ To let a function return a value, use the return statement;


Array Functions
■ There are huge number of array built-in functions, like
■ sort() - sort arrays in ascending order
■ rsort() - sort arrays in descending order
■ asort() - sort associative arrays in ascending order, according to
the value
■ ksort() - sort associative arrays in ascending order, according to
the key
■ arsort() - sort associative arrays in descending order, according
to the value
■ krsort() - sort associative arrays in descending order, according
to the key.
Array Functions
 count($ar) - How many elements in an array

 is_array($ar) - Returns TRUE if a variable is an array

 isset($ar['key']) - Returns TRUE if key is set in the array

 shuffle($ar) - Shuffles the array into random order

 Visit http://www.w3schools.com/php/php_ref_array.asp to get


more built-in functions
String Functions
■ strlen()- returns the length of a string:
■ str_word_count() <?php
echo strlen("Hello");
counts the number of echo str_word_count("Hello world!");
words in a string. // outputs 2
echo strrev("Hello world!");
■ strrev() - reverses a // outputs !dlrow olleH
string. echo strpos("Hello world!", "world");
■ strpos() - searches for a // outputs 6
echo str_replace("world", "Dolly", "Hello world!");
specific text within a // outputs Hello Dolly!
string ?>
■ str_replace() - replaces some characters with some other
characters in a string.
■ Visit http://www.w3schools.com/php/php_ref_string.asp
link to get the list of String’s built-in functions.
Arrays and Strings
$inp = "This is a sentence with seven words";

$temp = explode(' ', $inp);

print_r($temp);
Out Put: -
Array(
[0] => This
[1] => is
[2] => a
[3] => sentence
[4] => with
[5] => seven
[6] => words
)
PHP Constants
■ A constant is an identifier (name) for a simple value.

– The value cannot be changed during the script.

■ constant name starts with a letter or underscore.

– (no $ sign before the constant name).

■ To create a constant, use the define() function.

■ Syntax

– define(name, value, case-insensitive)


■ name: Specifies the name of the constant

■ value: Specifies the value of the constant

■ case-insensitive: Specifies whether the constant name should be


case- insensitive. Default is false

■ Note: Unlike variables, constants are automatically global across the entire
script.
PHP Constants
<!DOCTYPE html>
<html>
<body>
<?php
// case-sensitive constant name
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>
</body>
</html>
Uniform Resource Locator
 URL is used to address a document (or other data) on the web with
following these syntax rules:

 scheme://prefix.domain:port/path/filename

 scheme - defines the type of Internet service (most common is http or


https)

 prefix - defines a domain prefix (default for http is www)

 domain - defines the Internet domain name (like w3schools.com)

 port - defines the port number at the host (default for http is 80)

 path - defines a path at the server (If omitted: the root directory of the site)

 filename - defines the name of a document or resource


PHP GET and POST Methods
 Browser client uses two HTTP methods to send information to the web server.
1. The GET Method

2. The POST Method

 Before the browser sends the information, it encodes it using a scheme called URL encoding.

 URL encoding is a mechanism for translating unprintable or special characters to a


universally accepted format by web servers and browsers.

 OR - URL encoding converts non-ASCII characters into a format that can be transmitted over
the Internet.

 URL encoding is also known as percent-encoding.

 In this scheme, name/value pairs are joined with equal signs and different pairs are
separated by the ampersand (&).
 name1=value1&name2=value2&name3=value3

 Spaces are removed and replaced with the + character or or %20,

 any other non-alphanumeric characters are replaced with a "%" followed by


hexadecimal digits.

 After the information is encoded it is sent to the server.


ASCII Encoding Examples
 Your browser will encode input, according to the character-set used in your page.

 The default character-set in HTML5 is UTF-8.

Character From Windows-1252 From UTF-8


€ %80 %E2%82%AC
£ %A3 %C2%A3
© %A9 %C2%A9
® %AE %C2%AE
À %C0 %C3%80
Á %C1 %C3%81
 %C2 %C3%82
à %C3 %C3%83
Ä %C4 %C3%84
Å %C5 %C3%85
The GET Method
■ It sends the encoded user information appended to the page request.

– The page and the encoded information are separated by the ? character.

■ http://www.test.com/index.htm?name1=value1&name2=value2

■ Information sent with the GET method is visible to everyone (all variable
names and values are displayed in the URL).

■ GET also has limits on the amount of information to send.

– The limitation is about 2000 characters.

■ However, because the variables are displayed in the URL, it is possible to


bookmark the page.

■ GET may be used for sending non-sensitive data.

– Note: GET should NEVER be used for sending passwords or other


sensitive information!
The POST Method
■ Transfers information via HTTP headers.

– The information is encoded as described in case of GET method and put


into a header called QUERY_STRING.
■ Information sent with the POST method is invisible to others

■ It has no limits on the amount of information to send

■ It can be used to send ASCII as well as binary data, like sending files.

■ The data sent by POST method goes through HTTP header so security depends
on HTTP protocol.

– By using Secure HTTP you can make sure that your information is secure.

■ because the variables are not displayed in the URL, it is not possible to
bookmark the page.
HTML Forms & GET Method
• The PHP provides $_GET associative array to access all
the sent information using GET method.
<?php
if(isset($_GET["name"]) || isset($_GET["age"]) )
{
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit(); // exit here and the remains code will not be executed.
}
echo" <html>
<body>
<form action=”.$_SERVER['PHP_SELF’]." method='GET'>
Name: <input type='text' name='name’ /><br>
Age: <input type='text' name='age’ /><br>
<input type='submit' />
</form>
</body>
</html>";
?>
HTML Forms & POST Method
The PHP provides $_POST associative array to access all the sent
information using POST method.
<?php
if(isset( $_POST["name"]) || isset($_POST["age"] ))
{
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years
old."; exit();
} ?>
<html>
<body>
<form action =”.$_SERVER['PHP_SELF’]." method="POST”>
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
The $_REQUEST variable
 The PHP $_REQUEST variable contains the contents of both
$_GET, $_POST.
<?php
if( isset($_REQUEST["name"]) || isset($_REQUEST["age"] ))
{
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years
old."; exit();
} ?>
<html>
<body>
<form action =”.$_SERVER['PHP_SELF’]." method="POST”> Name:
<input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
PHP Global Variables - Superglobals
■ they are variables which are always accessible, regardless of
scope - and you can access them from any function, class or file
without having to do anything special, like:

■ $_SERVER

■ $_REQUEST

■ $_POST

■ $_GET

■ $_SESSION

■ $_COOKIE
Element/Code
$_SERVER['PHP_SELF']
PHP
Description
Returns the filename of the currently executing script
$_SERVER['GATEWAY_INTERFACE']
$_SERVER['SERVER_ADDR'] $_SERVER
Returns the version of the Common Gateway Interface (CGI) the server is
using Returns the IP address of the host server
$_SERVER['SERVER_NAME'] Returns the name of the host server (such as localhost)
$_SERVER['SERVER_SOFTWARE'] Returns the server identification string (such as Apache/2.2.24)
$_SERVER['SERVER_PROTOCOL'] Returns the name and revision of the information protocol (such as
$_SERVER['REQUEST_METHOD'] HTTP/1.1) Returns the request method used to access the page (such as
$_SERVER['REQUEST_TIME'] POST)
$_SERVER['QUERY_STRING'] Returns the timestamp of the start of the request (such as 1377687496)
$_SERVER['HTTP_ACCEPT'] Returns the query string if the page is accessed via a query string
$_SERVER['HTTP_ACCEPT_CHARSET'] Returns the Accept header from the current request
$_SERVER['HTTP_HOST'] Returns the Accept_Charset header from the current request (such as utf-8,ISO-8859-1)
$_SERVER['HTTP_REFERER'] Returns the Host header from the current request
$_SERVER['HTTPS'] Returns the complete URL of the current page (not reliable because not all user-agents support it)
$_SERVER['REMOTE_ADDR'] Is the script queried through a secure HTTP protocol
$_SERVER['REMOTE_HOST'] Returns the IP address from where the user is viewing the current page
$_SERVER['REMOTE_PORT'] Returns the Host name from where the user is viewing the current page
$_SERVER['SCRIPT_FILENAME'] Returns the port being used on the user's machine to communicate with the web server
$_SERVER['SERVER_ADMIN'] Returns the absolute pathname of the currently executing script
Returns the value given to the SERVER_ADMIN directive in the web server configuration file (if your
script runs on a virtual host, it will be the value defined for that virtual host) (such as
$_SERVER['SERVER_PORT'] you@example.com)
$_SERVER['SERVER_SIGNATURE'] Returns the port on the server machine being used by the web server for communication (such as
$_SERVER['PATH_TRANSLATED'] 80) Returns the server version and virtual host name which are added to server-generated pages
$_SERVER['SCRIPT_NAME'] Returns the file system based path to the current script
$_SERVER['SCRIPT_URI'] Returns the path of the current script
Returns the URI of the current page
Forms - Required Fields
<!DOCTYPE HTML> <html> <head><style> .error {color: #FF0000;} </style>
</head> <body>
<?php
$nameErr = $genderErr = ""; // define variables and set to empty values
$name = $gender = $comment = "”;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
} Continue >>
Forms - Required Fields
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data); //Removes whitespace or other
characters from both sides of a string
return $data;
}
?>

Continue >>
Forms - Required Fields
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
Continue >>
Forms - Required Fields
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo
$comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
PHP File Inclusion
■ You can include the content of a PHP file into another PHP file
before the server executes it.

■ There are two PHP functions:

– The include() Function.

– The require() Function.

■ This helps in creating functions, headers, footers, or elements


that can be reused on multiple pages.

■ Help developers to make it easy to change the layout of


complete website with minimal effort.
include() VS require() Function
■ Both of them take all the text in a specified file and copies it
into the file that uses the functions.

■ If there is any problem in loading a file then:

– the include() function generates a warning but the script


will continue execution.

– the require() function generates a fatal error and halt the


execution of the script.
include 'filename';
■ Syntax
or

require 'filename';
include() VS require() Function
■ Example: -

■ create a file footer.php with the following content.

<?php
echo "<p>Copyright &copy; 1999-" . date("Y") . " W3Schools.com</p>";
?>

■ To include the footer file into Home.php page, use the include
statement or required statement:
html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>
</body>
</html>
PHP Sessions
■ It is a way to store information (in variables) to be used across
multiple pages.

– Unlike a cookie, the information is not stored on the users


computer.

■ It creates a file in a temporary directory on the server where


registered session variables and their values are stored.

– Session variables hold information about one single user, and


are available to all pages in one application.

■ By default, session variables last until the user closes the browser.
Starting a PHP session
■ You must first start the session. When you start a session,

– it must be at the very beginning of your code, before any


HTML or text is sent.

■ PHP Code to start Session:


<?php
session_start(); // start up your PHP session!
?>

■ This code will register the user's session with the server, allow
you to start saving user information and assign a UID (unique
identification number) for that user's session.
Storing a session variable
■ Session variables are set with the PHP global variable:
$_SESSION.

■ Now, let's create a new page called ”index.php". In this page, we start
a new PHP session and set some session variables, then link it to
test2.php
<?php <?php
session_start(); ?> session_start(); ?>
<html> <body> <html> <body>
<?php <?php
$_SESSION['color'] = 'red'; if(isset($_SESSION['color']))
// store session data echo "my favorite Color = ".
echo "my favorite Color = $_SESSION['color']; //retrieve data
". ?>
$_SESSION['color']; //retrieve data <br>
?> <a href="test_session.php"> Go
<br> back</a>
<a href="test2_session.php"> NEXT </body> </html>
Page To Check Session</a>
</body> </html>
cleaning and destroying a session
■ session's data is temporary and does not require that you explicitly clean after
yourself, you may wish to delete some data for your various tasks.

■ For Example: -

– You are running an online business and a user used your website to
buy your goods.

– The user has just completed a transaction on your website and you now
want to remove everything from their shopping cart

<?php
session_start();
if(isset($_SESSION['cart']))
unset($_SESSION['cart']);
?> <?php
session_start();
■ You can also completely destroy the session session_destroy();
?>
entirely by calling the session_destroy
function.
More Advanced topics
PHP heredoc string
■ When you place variables in a double-quoted string, PHP will expand the
variable names. If a string contains the double quotes (“), you need to escape
them using the backslash character(\).
$he = 'Bob';
$she = 'Alice';
$text = "$he said, \"PHP is awesome\". \"Of course.\" $she agreed.";
echo $text;

■ PHP heredoc strings behave like double-quoted strings, without the double-
quotes.
– It means that they don’t need to escape quotes and expand variables.
$he = 'Bob';
$she = 'Alice';
$text = <<<TEXT
$he said "PHP is awesome". "Of course" $she agreed."
TEXT;
echo $text;
PHP heredoc syntax
■ First, start with the $str = <<<IDENTIFIER
place a string here
– <<< operator,
it can span multiple lines
– an identifier, and and include single quote ' and double quotes "
IDENTIFIER;
– a new line

■ Second, specify the string, which can span multiple lines and includes single quotes (‘)
or double quotes (“).
■ Third, close the string with the same identifier.

– The identifier must contain only alphanumeric characters and underscores and
start with an underscore or a non-digit character.

■ The closing identifier must follow these rules:

– Begins at the first column of the line

– Contains no other characters except a semicolon (;).

– The character before and after the closing identifier must be a newline character
defined by the local operating system.
PHP heredoc strings’ use cases
■ In practice, the heredoc syntax is used to define a

– string that contains a single quote, double quotes, or variables.

– The heredoc string makes the string easier to read.

– Also, a heredoc string is used to generate HTML dynamically. For


example:

$title = 'My site';


$header = <<<HEADER
<header>
<h1>$title</h1>
</header>
HEADER;

echo $header;
PHP Nowdoc syntax
■ A nowdoc string is similar to a heredoc string except that it doesn’t expand
the variables.

■ Here’s the syntax of a nowdoc string:


$str = <<<'IDENTIFIER'
place a string here
it can span multiple lines
and include single quote ' and double quotes "
IDENTIFIER;
■ Example:

$he = 'Bob';
$she = 'Alice';
$str = <<<'IDENTIFIER'
$he said "PHP is awesome". "Of course" $she
agreed." IDENTIFIER;

echo $str;
PHP type casting
Cast Operators Conversion
(array) Array
(bool) or (boolean) Boolean
(int) or (integer) Integer
(object) Object
(float) Float echo (int)12.5 . '<br>'; // 12
(string) String $amount = (float)100;
echo $amount."<br>"; // 100

$message = 'Hi';
$num = (int) $message;
echo $num."<br>"; // 0

$qty = null;
echo (int)$qty; // 0
PHP Anonymous Functions
■ An anonymous function is a function that doesn’t have a name.

■ Since the function doesn’t have a name, you need to end it with a
semicolon (;)

– PHP treats it as an expression.

■ This anonymous function cannot be used like a named function.

– To use an anonymous function, it is assigned to a variable and call the


function via the variable:

$multiply = function ($x, $y)


{ return $x * $y;
};

echo $multiply(10, 20);


Scope of the anonymous function
■ By default, an anonymous function cannot access the variables from its
parent scope. $message = ‘Hello’;
$say = function () {
echo $message;
};
$say();
PHP Notice: Undefined variable: message in
...

■ To use the variables from the parent scope inside an anonymous function,
you place the variables in the use construct as follows:

$message = ‘Hello PHP’;


$say = function () use ($message)
{ echo $message;
};
$say();
Hello
PHP
PHP Arrow Functions
■ PHP 7.4 introduced the arrow functions that provide a more concise syntax
for the anonymous functions.

■ The following illustrates the basic syntax for arrow functions:

fn (arguments) => expression;


$eq = fn ($x, $y) => $x ==
– Start with the fn keyword. $y;
echo $eq(100, 1 (or true)
'100');
– Can have only one expression and return this expression.

■ The arrow function is functionally equivalent to the following anonymous


function:
function(arguments) { return expression; }

■ Unlike anonymous functions, arrow functions can automatically access


variables from their parent scopes.
PHP variable functions
■ It allow to use a variable like a function.

– When parentheses () is appended to a variable, PHP will look for the function
whose name is the same as the value of the variable and execute it.

<?php
$f = ''strlen;
echo $f('Hello'); 5

■ First, define a variable $f and initialize its value to the 'strlen' literal string.

■ Second, use the $f as a function by passing the string 'Hello' to it.

■ When PHP sees $f(), it looks for the strlen() function.

– Because the strlen() is a built-in function, PHP just invokes it.

■ If PHP cannot find the function name, it’ll raise an error.


PHP array_reduce function
■ The array_reduce() function reduces an array to a single value using a
callback function.
array_reduce(array, myfunction, initial)
Parameter Description
array Required. Specifies an array
myfunction Required. Specifies the name of the function or Anonymous function
initial Optional. Specifies the initial value to send to the function (default is null)

$numbers = [10,20,30]; $numbers = [10,20,30];


$total = 0; $total = array_reduce($numbers,
foreach ($numbers as $number) {
function ($previous, $current)
$total += $number; {
} return $previous + $current;
echo $total; // 60 }
);
echo $total; // 60
function myfunction($v1,$v2){
return $v1 . "-" . $v2;
}
$a=array("Dog","Cat","Horse");
echo(array_reduce($a,"myfunction", 5));

You might also like