Chapter 6 (PHP, Web Service &web Sec)
Chapter 6 (PHP, Web Service &web Sec)
management in PHP
Topics
What are cookies?
Create and use cookies.
What are sessions?
Create and use sessions
<?php
// Setting a cookie
setcookie("username", “Abebe", time()+10*24*60*60);
?>
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.
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"]))
{
<?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);
?>
<?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
$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
• 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.