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

Chapter 6 (PHP, Web Service &web Sec)

2 Objectives By the study of the chapter, you will be able to: Describe what are Web services Describe are differences between website access and Web

Uploaded by

Ermias Taye
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)
28 views

Chapter 6 (PHP, Web Service &web Sec)

2 Objectives By the study of the chapter, you will be able to: Describe what are Web services Describe are differences between website access and Web

Uploaded by

Ermias Taye
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
You are on page 1/ 55

Sessions and Cookies

management in PHP
Topics
 What are cookies?
 Create and use cookies.
 What are sessions?
 Create and use sessions

2 Sessions and Cookies management in PHP


Introduction
 HTTP is a stateless protocol.
 A stateless protocol does not require the server to retain
information or status about each user for the duration of multiple
requests.
 this means that after an exchange is over...
 a browser requests a resource from a server
 the web server sends the resource to the browser
 ...the connection will be closed and forgotten
 this has its advantages
 because there is nothing to be kept track of, it is relatively easy to build
web servers that are very efficient
 But also it has drawbacks
 it makes it hard to follow a user on a website
3 Sessions and Cookies management in PHP
Why to follow a user’s?
 It is often extremely useful to be able to follow a user’s
activities on a website so that one can for example
 have a shopping cart
 maintain the user’s identity
 display information specifically tailored to the individual user
 Increased ability to provide the user a richer experience of
using that website
 a fine example of a site that truly exploits the user’s identity is
Amazon, which in many ways has set the standard in the
application of user identity to provide a rich experience

4 Sessions and Cookies management in PHP



 Login

Another aspect is the ability to log into a site with username
and password

this provides some level of security

One gets the opportunity to have “your own” page

with personal things, like your own photos on Facebook

a personal configuration of the page

a user identity for postings on web boards
 etc.

5 Sessions and Cookies management in PHP


 Some of the scenarios do not need to know “who” you
are
 “a specific browser on a particular machine” is often enough
 here we often talk about the temporary nature of information

 In other situations it is useful to know “who” people are


 one can get a more personalized experience of the site (this helps
perhaps also with loyalty)
 one can log on from different machines and have the same user
experience

6 Sessions and Cookies management in PHP


So what can we do?
 One can add a parameter to the URL and remember it so
that all subsequent links on the site contain it
 but that gives ugly URLs that are difficult to maintain (one
always has to rewrite all the URLs in a document) and
 are vulnerable to trivial hacks
 Since the web server can see, where a request comes
from, one could use the user’s machine address as an ID
 but what if it is a shared computer?
 or if it just looks like one computer due to NAT or a proxy?
 It would be great if a website could save a little bit of
data on the user’s machine ...
7 Sessions and Cookies management in PHP
So…
 So, web applications need to track the user's progress from
page to page, for example when a web server is required to
customize the content of a web page for a user.
 Solutions to address the above mentioned problems are cases
that include:
 the use of HTTP cookies.
 server side sessions,
 hidden variables (when the current page contains a form), and
 URL-rewriting using URI-encoded parameters, e.g., /index.php?
session_id=some_unique_session_code.

8 Sessions and Cookies management in PHP


Solution…
 HTTP remains stateless – there is no fixed connection between
web server and browser
 While the stateless nature of HTTP has some important benefits
 after all, maintaining state requires some overhead
 it presents a unique challenge to developers who need to create state-
full web applications.
 With no way to identify the client, it is impossible to determine
 whether the user is already logged in,
 has items in a shopping cart, or needs to register.
 An elegant solution to this problem, originally conceived by
Netscape, is a state management mechanism called cookies.

9 Sessions and Cookies management in PHP


Cookies
 a web server can leave a “cookie” in the browser (i.e.
on the user’s computer)
 it is up to the browser to manage these cookies
 the cookie gets transmitted to the server in future connections
 A cookie is a small piece of data (typically max 4 KB,
usually far less) that is used by the web server to
identify the user
 Cookies may be limited in time with an expiration date
 else the cookie will be deleted when the browser is closed

10 Sessions and Cookies management in PHP


Cookies
 are an extension of the HTTP protocol.
 they consist of two HTTP headers:
 the Set-Cookie response header and
 the Cookie request header.
 When a client sends a request for a particular URL, the server can
opt to include a Set-Cookie header in the response, so as to
request for the client to include a corresponding Cookie header in
its future requests
 Cookies
 allow a unique identifier to be included in each request (in a Cookie
header),
 This help to uniquely identify clients and associate their requests
together.
11 Sessions and Cookies management in PHP
12 Sessions and Cookies management in PHP
Create Cookies in PHP
 Use setcookie() function to create a cookie.
Syntax
setcookie(string name, string value, int expire, string path,
string domain, int secure);
Example:

<?php
// Setting a cookie
setcookie("username", “Abebe", time()+10*24*60*60);
?>

13 Sessions and Cookies management in PHP


Parameter Description
name The name of the cookie.
value The value of the cookie.
expires The expiry date in UNIX timestamp format.
This implies, After this time cookie will become inaccessible.
The default value is 0.

path Specify the path on the server for which the cookie will be
available.
If set to '/', the cookie will be available within the entire domain.

domain Specify the domain for which the cookie is available to


e.g www.example.com.

secure This field, if present, indicates that the cookie should be sent only
if a secure HTTPS connection exists.
Is a Keyword referring that the cookie will not be sent over a plain
HTTP connection
14 Sessions and Cookies management in PHP
Accessing cookie
 The PHP $_COOKIE super global variable is used to
retrieve a cookie value.
<html>
<head><title>sample on cookie</title></head>
<body>
<?php
if(!isset($_COOKIE["username"]))
{

setcookie("username", "Abebe", time()+10*24*60*60);


}
else{
echo $_COOKIE["username"]; // used to access a cookie
}?>
</body>
</html>
15 Sessions and Cookies management in PHP
Check if Cookies are Enabled
 count the $_COOKIE array variable
<?php
setcookie("username", "Abebe", time()+10*24*60*60);
?>
<html>
<body>

<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
16 Sessions and Cookies management in PHP
Removing Cookies
Cookies can be deleted by calling the setcookie() function
with the cookie name and any value (such as an empty
string) with expiration date set in the past,

<?php
// Deleting a cookie
setcookie("username", "", time()-3600);
?>

17 Sessions and Cookies management in PHP


Scope of cookies
 Cookies can only be read from the site from which they were
set
 this helps to ensure that one can not steal cookies (and thus
identities) through hostile websites

18 Sessions and Cookies management in PHP


Cookies and their use
 Shopping cart
 when the front page appears, set a new (empty) cookie
 items are added by updating the cookie
 alternatively, one can store goods in the server’s database and just
store an ID in the cookie that points to your basket
 Login
 user inputs name and password into a form
 after the combination has been verified, it sends a cookie to the user
that identifies the user to the system
 next time the user visits the page, the web server checks if there is a
cookie, and if so the user is identified

19 Sessions and Cookies management in PHP


Criticism of cookies
 One can not be completely anonymous on the net
 most ads/banners come from relatively few advertisers.
 these may, with the help of cookies, follow a browser/ computer
combination on all the sites they advertise on.
 there have been examples of security vulnerabilities in
browsers, so that adversaries can get access to cookies
 which they can use to gain access to sites with a faked identity

20 Sessions and Cookies management in PHP


Sessions
 A combination of cookies and data stored on the server
(automatically by PHP)
 saves a cookie containing an ID on the user’s computer that
points to a session on the server
 A session is a global PHP array ($_SESSION)
 A session is designed as an easy way to store data – for a
short period
 a session’s lifetime in PHP is only 24 minutes by default

21 Sessions and Cookies management in PHP


Starting PHP session
 Sessions must be started at the top of the page before it is
used
session_start()
 Session_start() function creates a new session and
generate a unique session ID for the user.
 it first checks for an existing session ID. If it finds one, i.e. if
the session is already started, it sets up the session variables
and if doesn't, it starts a new session by creating a new session
ID.

22 Sessions and Cookies management in PHP


Storing and Accessing Session Data
 session data can be stored as key-value pairs in the
$_SESSION[] super global array.
 The stored data can be accessed during lifetime of a session.
<?php
// Starting session
session_start();

// Storing session data


$_SESSION["firstname"] = “Abebe";
$_SESSION["lastname"] = “Lemlem";
?>
23 Sessions and Cookies management in PHP
Accessing session data
 We can access the session data we set on our previous
example from any other page on the same web
domain
 Simply recreate the session by calling session_start()
and then pass the corresponding key to the
$_SESSION associative array.

<?php
session_start();
echo $_SESSION["Name"];
?>
24 Sessions and Cookies management in PHP
Destroying PHP session
 allglobal session variables can be removed by
destroing the session using
 session_unset(“sessionId”) //remove all session variables
 session_destroy():// destroy the session

<?php
session_start();
<?php
// Removing session data session_start();
if(isset($_SESSION[“username"])){ // Destroying session
session_unset($_SESSION[“usernam
e"]);
session_destroy();
} ?>
?> 25 Sessions and Cookies management in PHP
Session for login
 Sessions are tied to an individual user and a
corresponding browser
 therefore, they are well suited to handle logins
 Useful command in this context: header()
 header() is used to send HTTP headers to the browser
 as other header information (such as cookies and
sessions), such a command should precede any HTML in
a PHP file
 a particularly interesting header in this context is
Location:, which redirects the browser to another URL

26 Sessions and Cookies management in PHP


Data Base manipulation using
PHP
Chapter 6
1

Review on Database terms


 Database: is a collection of related data
 Database Management System (DBMS): A software
package/ system to facilitate the creation and maintenance of a
computerized database.

Software to process queries


+
Software to access data
Relational DataBase Management
System (RDBMS)
 Enables you to implement a database with tables, columns
and indexes.
 Guarantees the Referential Integrity between rows of
various tables.
 Updates the indexes automatically.
 Interprets an SQL query and combines information from
various tables
RDBMS Terminology:
 Database: A database is a collection of tables, with related data.
 Table: A table is a matrix with data
 Column: One column (data element) contains data of one and the
same kind, to represent one property of an entity
 Row: A row (= tuple, entry or record) is a group of related data, to
represent one instance of an entity
 Redundancy: Storing data twice, redundantly to make the system
faster.
 Primary Key: A primary key is unique. A key value can not occur
twice in one table. With a key, you can find at most one row.
 Foreign Key: A foreign key is the linking pin between two tables
 Constraints: rules set over database elements
Introduction to MySQL
 MySQL is a RDBMS
 Is an open-source software
 Use standard form of SQL data language
 supports large databases, up to 50 million rows or
more in a table
 The MySQL command line monitor Creating database
tables Queries
Basic queries
 CREATE: create databases and tables
 CREATE TABLE tableName(columnName Datatype constraint, …. );
 SELECT: select table rows based on certain conditions
 SELECT columnName, columnName… FROM tableName WHRER condition;
 DELETE: delete one or more rows of a table
 DELETE FROM tableName WHERE condition;
 INSERT: insert a new row in a table
 INSERT INTO tableName(column list) VALUES (column values);
 UPDATE: update rows in a table
 UPDATE tableName SET columnName = NewValues;
 ALTER: alter the structure of a table
 ALTER TABLE tableName ADD columnBame dataType;
 ALTER TABLE tableName DROP columnName;
 ALTER TABLE tableName MODIFY columnName Datatype [NULL value] [DEFAULT value];
 ALTER TABLE tableName CHANGE old_columnName new_columnName datatype;
 ALTER TABLE tableName RENAME TO new_tableName;
Administrative MySQL Command:
 USE Databasename: This will be used to select a particular database
in MySQL work area.
 SHOW DATABASES: Lists the databases that are accessible by the
MySQL DBMS.
 SHOW TABLES: Shows the tables in the database once a database
has been selected with the use command.
 SHOW COLUMNS FROM tablename: Shows the attributes, types
of attributes, key information, whether NULL is permitted, defaults,
and other information for a table.
 SHOW INDEX FROM tablename: Presents the details of all indexes
on the table, including the PRIMARY KEY.
 SHOW TABLE STATUS LIKE tablename\G: Reports details of the
MySQL DBMS performance and statistics.
PHP and MySQL functions
 Connecting to a Database
 Making a query
 Using results of a query
 Freeing resources
 closing the connection
Connecting to a Database
$servername=“servername:port";
$username=“mysql_user_name“;
$password=“mysql_password";
$dbname=“database_name“;
$con = mysqli_connect($servername, $username, $password, $dbname);

• Opens a new connection MySQL server


• $servername can be either a host name or an IP address
• the default is the string "localhost:3306"
• username is a string for the user name
• password is a string for the password
• dbname is the name of the database to connect with
• returns FALSE on failure
Example PHP for DB connection
<?php
function connect_db($dbname){
$con = mysqli_connect("localhost:3306", "root", "",
$dbname);
if(mysqli_connect_errno()){
echo "Connection failed: " . mysqli_connect_error();
}
return $con;
}
?>
Making a query (1. SELECT)
$query="SELECT SID, StudName, age, sex FROM student";
$result=mysqli_query($con, $query);

• This task involve preparing a query and submitting it to


the database engine for retrieval
• $con is the connection string
• query is a string for the MySQL query
• It makes a select query
• Don't end the query with a semi-colon
• Return value is a resource identifier or FALSE if the
query is SELECT or SHOW
Making a query (2. INSERT and UPDATE)
 for these queries a resource is not returned
 TRUE is returned on success
 FALSE is returned on failure
 Syntax rules to follow:
 The SQL query must be quoted in PHP
 String values inside the SQL query must be quoted
 Numeric values must not be quoted
 The word NULL must not be quoted
$sql1 = "INSERT INTO student (StudName, age, sex, SID) VALUES ('$studname',
'$age', '$sex', '$sid')";

$sql2= “UPDATE student SET StudName='$studname', age='$age', sex='$sex‘


WHERE SID='$sid‘ ";
Using the query result
• Involves two subsequent tasks
• Identify the number of rows affected by the query
• Fetch the data from the database server
• In this step, we can iterate through the result and display the
record in a certain format. Example: in a tabular format
$row=mysqli_num_rows($result);//number of rows

$row_record=mysqli_fetch_row()
 /*each call returns the next row as an indexed array where result is a resource returned from a call
to mysqli_query (FALSE if no more rows)*/

$row_record=mysqli_fetch_assoc($result);//record set
 /*as in mysql_fetch_row but next row is returned as an associative array*/

$row_record=mysqli_fetch_array(result)
 /*combines mysqli_fetch_row, mysqli_fetch_assoc
 returns row information as both an associative array and an indexed array*/
Example PHP for DB query (SELECT)
<?php
function viewData($dbname){
$dbname= $dbname;
$con = connect_db($dbname);
$sql = "SELECT SID, StudName, age, sex FROM student";
$result=mysqli_query($con, $sql);
if(mysqli_num_rows($result)>0){
echo "<table border='1'><th>ID</th><th>NAME</th><th>AGE</th><th>SEX</th>";
while($row=mysqli_fetch_assoc($result)){
echo "<tr><td>".$row["SID"]."</td><td>".$row["StudName"]."</td><td>".$row["age"]."</td><td>".
$row["sex"]."</td></tr>";
}
echo "</table>";
}
else{
echo "no record found";
}
}
?>
Freeing query resources
mysqli_free_result($result)
 free memory associated with the given resource
 called result (after a select query).
 Not necessary except for large result sets
 Done automatically when script exits.
closing the connection
mysqli_close($con)
 closethe database connection associated with
the given database link, ($con).
Error handling
mysqli_connect_errno()
 Returns the last error code number from the last call to
mysqli_connect
 An error code value for the last call to mysqli_connect, if it
failed.
 zero means no error occurred

mysqli_connect_error
 Returns a string description of the last connect error
 NULL is returned if no error occurred.
Other functions
ysqli_real_escape_string($con, $ escapeString);
 This function is used to create a legal SQL string that you
can use in an SQL statement.
 The given string is encoded to an escaped SQL string,
taking into account the current character set of the
connection.
 parameters
 $con: a link identifier returned by mysqli_connect
 $escapeString: the string to be escaped.
 Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-
Z.
Student register example
First create a database and the table

CREATE DATABASE sampledb;


USE sampledb;
CREATE TABLE student
(
SID int PRIMARY KEY NOT NULL AUTOINCREMENT,
studName varchar(50),
sex varchar(10),
age int
);
Insert.html (insert.php)
<html>
<body>
<fieldset>
<legend><h1>Register here...</h1></legend>
<form action="register.php" method="post">
Name: &nbsp; <input type="text" name="name"><br><br>
ID:&tbsp; &nbsp; &nbsp; &nbsp; <input type="text" name="id"><br><br>
Sex:&nbsp; &nbsp; &nbsp; <input type="text" name="sex"><br><br>
Age:&nbsp; &nbsp; &nbsp; <input type="text" name="age"><br><br>
<input type="submit" value="insert"><br><br>
</form>
</fieldset>
</body>
</html>
Register.php
<?php
$studname= mysqli_real_escape_string($con, $_POST['name']);
$age=mysqli_real_escape_string($con, $_POST['age']);
$sex=mysqli_real_escape_string($con, $_POST['sex']);
$sid=mysqli_real_escape_string($con, $_POST['id']);
$sql = "INSERT INTO student (StudName, age, sex, SID) VALUES ('$studname', '$age',
'$sex', '$sid')";
if (!mysqli_query($con, $sql)) {
$err=1;
}
mysqli_close($con);
if(isset($err)){
header("location: index.html?err=1");
}
else{
header("location: index.html");
}
?>
View.php
<?php require_once('connect_db.php')?>
<html>
<body>
<?php
$dbname="sampledb";
$con = connect_db($dbname);
$sql = "SELECT SID, StudName, age, sex FROM student";
$result=mysqli_query($con, $sql);
if(mysqli_num_rows($result)>0){
echo "<table border='1'><th>ID</th><th>NAME</th><th>AGE</th><th>SEX</th>";
while($row=mysqli_fetch_assoc($result)){
Echo"<tr><td>".$row["SID"]."</td><td>".$row["StudName"]."</td><td>".$row["age"]."</td><td>".$row["sex"]."</td></
tr>";
}
echo "</table>";
}
else{
echo "no record found";
}
mysqli_close($con);
?>
</body></html>
Web service

Web Service is can be defined by following ways:


• It is a client-server application or application component for communication.
• The method of communication between two devices over the network.
• It is a software system for the interoperable machine to machine communication.

• It is a collection of standards or protocols for exchanging information between two devices or application .
Cont’d
The basic web services platform is XML + HTTP. All the standard web services work using the following
components −
• SOAP (Simple Object Access Protocol)
• UDDI (Universal Description, Discovery and Integration)
• WSDL (Web Services Description Language)

SOAP
 Web Services use the Simple Object Access Protocol (SOAP) which uses XML as a payload or request body.
 This is a stateful protocol as there is no independent method for the specific type of operation.
 All the requests and responses are carried at once through XML and no independent methods like GET, PUT, POST
or DELETE are explicitly provided.

WSDL
 This SOAP request makes use of Web Services Description Language (WSDL) which is a very useful
component of Web Service.
 This defines where the Web Service actually resides and also the type of Web Service to be picked up
for a specific request.
 This makes use of an XML file that describes the Web Service functionality.
Cont’d

UDDI
• Another useful component is UDDI. This stands for Universal Description Discovery and Integration.
There is a service provider who provides the Web Service.
• Hence, for a particular service provider, this UDDI is used for describing, discovering, and
publishing those Web Services.
• UDDI is responsible for letting a client find out (UDDI provides a repository for WSDL) where the
WSDL’s XML file is located.
Architecture Of A Web Service
Cont’d
There are three roles of web service architecture:
Service Provider: 
The service provider defines a service description for the Web service and publishes it to a service
requestor or service registry
It is the platform that hosts the services.
 It creates web service and makes it available to client applications who want to use it.
 Service Requestor: 
Service Requestor uses a find operation to retrieve the service description locally or from the service
registry and uses the service description to bind with the service provider and invoke or interact with
the Web service implementation.
It is the application that is looking for and invoking or initiating an interaction with a service. Here, the
browser plays the requester role, driven by a consumer or a program without a user interface. In short,
the client application that needs to contact a web service is Service Requestor.
The client application can be a .Net application, a Java application, or any other language-based
application that looks for some sort of functionality.
Service Registry: 
Service requestors find the service and obtain binding information for services during development.
It is the application that provides access to the UDDI.
 The UDDI enables the client application to locate the web service.
Web security

 Web security in web application development refers to the practices and measures taken to protect web
applications and their users from various security threats and vulnerabilities.
 Web security in dynamic web applications refers to the measures and practices implemented to protect
the security and integrity of web applications that dynamically generate content and interact with users in
real-time. Dynamic web applications often involve server-side scripting, database interactions, user input
processing, and dynamic content generation
 It involves implementing security controls and best practices to ensure the confidentiality, integrity, and
availability of the application and its data .
Here are some key aspects of web security in web application development
Authentication and Authorization:
 Proper authentication ensures that only authorized users can access the application.
 This involves implementing secure login mechanisms, such as username/password authentication, multi-
factor authentication, or integration with external authentication providers.
 Authorization controls what actions and resources each authenticated user can access within the
application.
Input Validation and Sanitization:
 Web applications should validate and sanitize all user input to prevent common security vulnerabilities
like cross-site scripting (XSS) and SQL injection attacks.
 Input validation ensures that user-supplied data meets the expected format and criteria, while
sanitization removes or escapes potentially malicious content.
Cont’d

Secure Communication :
Web applications should use secure communication protocols, such as HTTPS, to encrypt data
transmitted between the client and the server.
This helps protect sensitive information, such as login credentials or personal data, from
eavesdropping and tampering.

Session Management :
 Proper session management is crucial to prevent session hijacking and session fixation attacks.
 This involves generating secure session identifiers, setting appropriate session timeouts, and
securely storing session data on the server-side .
Cross-Site Scripting (XSS)
 Cross-Site Request Forgery (CSRF) Prevention: XSS attacks occur when malicious scripts
are injected into web pages and executed in the user's browser.
 CSRF attacks exploit the trust a website has in a user's browser to perform unauthorized
actions on behalf of the user.
 Implementing measures like input validation, output encoding, and using anti-CSRF tokens
can help mitigate these vulnerabilities.
Cont’d

Security Testing :
 Regular security testing, including vulnerability scanning, penetration testing, and code
reviews, helps identify and address security weaknesses in web applications.
 This ensures that security measures are effective and up-to-date.

Security Updates and Patching :


Keeping the web application and its dependencies up-to-date with the latest security patches is
essential to address known vulnerabilities and protect against emerging threats.
SQL Injection: SQL injection attacks occur when an attacker inserts malicious SQL statements into a
web application's database query.
This can allow the attacker to manipulate or retrieve sensitive data, modify or delete data, or even gain
unauthorized access to the underlying server.
Security Misconfigurations: Misconfigurations in web servers, frameworks, or application components
can expose sensitive information or provide unauthorized access to attackers.
Examples include default or weak passwords, unnecessary open ports, or improper file permissions.
File Upload Vulnerabilities: Insecure file upload functionality can allow attackers to upload malicious
files, which can then be executed on the server or used to compromise other users' systems

You might also like