0% found this document useful (0 votes)
16 views34 pages

WD Unit V (c20)

Uploaded by

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

WD Unit V (c20)

Uploaded by

reddynanda426
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

UNIT-V

What is HTTP?
The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients
and servers.
HTTP works as a request-response protocol between a client and server.
A web browser may be the client, and an application on a computer that hosts a web site may be
the server.
Example: A client (browser) submits an HTTP request to the server; then the server returns a
response to the client. The response contains status information about the request and may also
contain the requested content.
Web server:
A web server is a system that delivers content or services to end users over the internet.
A Web server is a computer where the web content is stored.
A web server communicates with a web browser using the Hypertext Transfer Protocol (HTTP).

The content of most web pages is encoded in Hypertext Markup Language (HTML).
The content can be static (for example, text and images) or dynamic (for example, a computed
price or the list of items a customer has marked for purchase).
5.1:Web Server architecture and Working
Web server respond to the client request in either of the following two ways:
 Sending the file to the client associated with the requested URL.
 Generating response by invoking a script and communicating with database
Key Points
 When client sends request for a web page, the web server search for the requested page if
requested page is found then it will send it to client with an HTTP response.
 If the requested web page is not found, web server will the send an HTTP
response:Error 404 Not found.
 If client has requested for some other resources then the web server will contact to the
application server and data store to construct the HTTP response.
5.2:List various Web servers ::
i) IIS(Internet Information Server)
ii) PWS(Personal Web Server)
iii) Apache Server
5.3 :List Various HTTP Request types (or)HTTP Request Methods
 GET
 POST
 PUT
 HEAD
 DELETE
 PATCH
 OPTIONS
The GET Method
GET is used to request data from a specified resource.
GET is one of the most common HTTP methods.
Some other notes on GET requests:
 GET requests can be cached
 GET requests remain in the browser history
 GET requests can be bookmarked
 GET requests should never be used when dealing with sensitive data
 GET requests have length restrictions
 GET requests is only used to request data (not modify)
The POST Method
POST is used to send data to a server to create/update a resource.
POST is one of the most common HTTP methods.
Some other notes on POST requests:
 POST requests are never cached
 POST requests do not remain in the browser history
 POST requests cannot be bookmarked
 POST requests have no restrictions on data length

GET POST

1) In case of Get request, only limited amount of In case of post request, large amount of
data can be sent because data is sent in header. data can be sent because data is sent in body.

2) Get request is not secured because data is exposed Post request is secured because data is not
in URL bar. exposed in URL bar.

3) Get request can be bookmarked. Post request cannot be bookmarked.

4) Get request is idempotent . It means second Post request is non-idempotent.


request will be ignored until response of first request
is delivered

5) Get request is more efficient and used more than Post request is less efficient and used less
Post. than get.

5.4:Differences between Apache and IIS

Apache IIS (Internet Information Server)

Apache is open source IIS is packaged with Windows.


Apache can run on almost any OS including IIS only runs on Windows.
UNIX, Apple’s OS X, and on most Linux ( platform- dependent)
Distributions.( platform -independent)
Apache doesn’t need any license to run IIS will require a license from Microsoft to
commercially operate commercially.
Apache supports PHP and MySQL. IIS supports PHP, .net framework .
Apache has enhance security than IIS server IIS has less security than Apache server

Personal Web Server (PWS):


 Microsoft produces a cut-down version of IIS called Personal Web Server (PWS).
 designed to create and manage a web server on a desktop computer(PC).
 the main functions of PWS is to provide an environment where web programmers can
test their programs and web pages.
 allows users to store, or publish information on the web or on a home network.
 a personal web server is owned or controlled by an individual, and operated for the
individual's needs, instead of by a company.

5.5: How to combine HTML and PHP

When building a complex web page, at some point you will be faced with the need to combine
PHP and HTML to achieve your needed results.
 PHP is designed to interact with HTML .
 PHP scripts can be included in an HTML page without a problem.

5.5.1)PHP in HTML
In an HTML page, PHP code is enclosed within special PHP tags.

Ex-1:

<html>
<body>
<p>Hello, welcome</p>
<?php
echo "mohan";
echo " svgp";
echo "bye";
?>
</body>
</html>

EX-2:

<html>
<body>
<p>Hello, today is:</p>
<?php
echo date('l, F jS, Y');
?>.
</body>
</html>

5.5.2) HTML in PHP using echo


A possible way to integrate HTML tags in a PHP file is via the echo command:

Note: Possible yet not recommended usage:

<?php
echo "<html>";
echo "<head></head>";
echo "<body>";
echo "Hello, today is ";
echo date('l, F jS, Y'); //other php code here
echo "</body>";
echo "</html>";
?>

5.6:How to access HTML and PHP documents from Web Server


Step 1: Open the Apache Friends website and download XAMPP for Windows, and install it.
Step 2: Start the XAMPP Program Control Panel. Click on the “Start” button.
Step 3: Place your PHP files in the “htdocs” folder located under the “XAMPP” folder on your
drive (i.e. C/D/E etc).
Step 4: Open up any web browser and enter “localhost/filename”.
Note:
 For example , if you want to access(run) your html file named ”sample.html” then Open
up any web browser and enter “localhost/Sample.html”.
 For example , if you want to access(run) your php file named ”sample.php” then Open
up any web browser and enter “localhost/Sample.php”.

5.7:List and Explain Various Datatypes with Example

PHP supports the following data types:


 String
 Integer
 Float ( also called double)
 Boolean
 Array
 Object
 NULL
 Resource
Note:PHP is a loosely typed language, it means PHP automatically converts the variable to its
correct data type.

PHP String

A string is a sequence of characters, like "Hello world!".


A string can be any text inside quotes. You can use single or double quotes:
Ex:
<?php
$x = "Hello world!";
$y = 'Hello world!';

echo $x;
echo "<br>";
echo $y;
?>

PHP Integer

An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.


Ex:
<?php
$x = 5985;
echo $x;
echo "<br>";
var_dump($x);
?>

Note: In the above example $x is an integer. The PHP var_dump() function returns the data type
and value:

PHP Float

A float (floating point number) is a number with a decimal point or a number in exponential
form.
In the following example $x is a float. The PHP var_dump() function returns the data type and
value:
Ex:
<?php
$x = 10.365;
echo $x;
echo “<br>”
var_dump($x);
?>
PHP Boolean
Boolean have only two possible values either true or false. PHP provides a couple of constants
especially for use as Booleans: TRUE and FALSE.
Booleans are often used in conditional testing.
Ex:
<!DOCTYPE html>
<html>
<body>
<?php
if (TRUE)
print("This will always print<br>");

else
print("This will never print<br>");
?>
</body>
</html>

PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the data type
and value.

Ex-1:
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo ","BMW" ,"Toyota");
var_dump($cars);
?>
</body>
</html>
Ex-2:
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo","BMW","Toyota");
echo $cars[0];
echo $cars[1];
echo $cars[2];
?>
</body>
</html>
PHP Object

An object is a data type which stores data and information on how to process that data.
In PHP, an object must be explicitly declared.
First we must declare a class of object. For this, we use the class keyword. A class is a structure
that can contain properties and methods.

5.8)How to declare Variables and Constants in PHP


PHP Variables
Variables are "containers" for storing information.

In PHP, a variable starts with the $ sign, followed by the name of the variable:

Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo "$txt<br>";
echo "$x <br>";
echo "$y" ;
?>
EX: Addition of two nunmbers
<?php

$a=10;
$b=20;
$c=$a + $b;
print "value of c:$c ";

?>
PHP Constants

A constant is an identifier (name) for a simple value. The value cannot be changed during the
script.
A valid constant name starts with a letter or underscore (no $ sign before the constant name).

Create a PHP Constant

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

Syntax
define(name, value, case-insensitive)
Parameters:

 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

Example-1
<?php
define("pi" , 3.141);
echo pi;
?>
Example-2:
<?php
define("GREETING", "Welcome to SVGP");
echo GREETING;
?>
5.9:List and Explain String manipulation functions

echo() It is used for output one or more strings.

print() It is used for output one or more strings.

printf() It is used to show output as a formatted string.

ucfirst() Make the first character of the string to uppercase

ucwords() Make the first character of each word in a string to uppercase

Lcfirst() It is used to convert the first character of a string to lowercase.

sprintf() Return a formatted string

sscanf() It is used to parse input from a string according to a format.

strcasecmp() It is used to compare two strings.

strchr() It is used to find the first occurrence of a string inside another string.

strcmp() Binary safe string comparison (case-sensitive)

sprintf() Return a formatted string

substr() Return the part of a string


strtolower() Convert the string in lowercase

strtoupper() Convert the strings in uppercase

strrev() It is used to reverse a string.

strlen() It is used to return the length of a string.

EX-1:

<?php
$str="my name is mohan raj";
$str=strlen($str);
echo $str;
?> output: 20

Ex-2:
<?php
$str="my name is mohan raj";
$str=strrev($str);
echo $str;
?> output: jar nahom si eman ym

Ex-3:
<?php
$str="my name is mohan raj";
$str=ucwords($str);
echo $str;
?> output: My Name Is Mohan Raj
Ex-4:
<?php
$str="MY NAME IS MOHAN";
$str=lcfirst($str);
echo $str;
?> output: mY NAME IS MOHAN RAJ

5.10: Understand Arrays in PHP


An array is a special variable, which can hold more than one value at a time.
Create an Array in PHP
In PHP, the array() function is used to create an array:
EX-1:
$cars = array("Volvo", "BMW", "Toyota");
Ex-2:
$a=array( 1,2,3,4,5);
Ex-3:
$ar=array(“mohan”, 100.25,111,’z’);
5.11: Explain Types of arrays in PHP

In PHP, there are three types of arrays:

 Indexed arrays - Arrays with a numeric index


 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays
PHP Indexed Arrays
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like this:

$cars = array("Volvo", "BMW", "Toyota");

Or the index can be assigned manually:

$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";

Example-1:
<?php
$a=array(1,2,3,4,5);
echo $a[0];
echo $a[1];
echo $a[2];
echo $a[3];
echo $a[4];
?>
Example-2:
<?php
$a=array(1,2,3,4,5);
for($i=0;$i<5;$i++)
{
echo $a[$i];
echo "<br>";
}
?>
Note:The count() function is used to return the length (the number of elements) of an array.
Example-3:

<?php
$a=array(1,2,3,4,5);
$len=count($a);
for($i=0;$i<$len;$i++)
{
echo $a[$i];
echo "<br>";
}
?>
PHP Associative array
An array with strings as index. This stores element values in association with key values rather
than in a strict linear index order.
There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Example:
<?php
$age = array("raj"=>35, "hari"=>37, "ram"=>43);
echo $age['raj'] ;
echo $age['hari'] ;
echo $age['ram'] ;
?>
PHP - Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.
EX:
$a=array( array(1,2),
array(3,4)
);
Program-1:

<?php
$a=array( array(1,2),
array(3,4)
);

echo $a[0][0];
echo $a[0][1];
echo $a[1][0];
echo $a[1][1];
?>

Program-2:
<?php
$a=array( array(1,2),
array(3,4)
);
for($i=0;$i<2;$i++)
{
for($j=0;$j<2;$j++)
{
echo $a[$i][$j];
echo "<br>";
}
}
?>
5.12:Program using Arrays:Addition of two matrices
<?php
$a=array( array(1,2),
array(3,4)
);
$b=array( array(5,6),
array(7,8)
);
for($i=0;$i<2;$i++)
{
for($j=0;$j<2;$j++)
{
$c[$i][$j]= $a[$i][$j]+$b[$i][$j];
}
}
for($i=0;$i<2;$i++)
{
for($j=0;$j<2;$j++)
{
echo $c[$i][$j];
echo "<br>";
}
}

?>

5.13:Explain Form Handling using $_GET and $_POST methods


$_GET and $_POST are Superglobal variables in PHP which used to collect data from HTML
form and URL.
The PHP super globals $_GET and $_POST are used to collect form-data.
Ex:
Sample.html
<html>
<body>

<form action="welcome.php" method="post">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

When the user fills out the form above and clicks the submit button, the form data is
sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP
POST method.

To display the submitted data you could simply echo all the variables. The "welcome.php"
looks like this:
<html>
<body>
<?php
$name=$_POST["name"];
$email=$_POST["email"];
echo "Welcome $name <br>";
echo "Your email address is:$email";
?>
</body>
</html>
The output could be something like this:
Welcome Mohan
Your email address is mohan123@example.com
Note: The same result could also be achieved using the HTTP GET method:
Example:
Sample1.html
<html>
<body>
<form action="welcome1.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
Welcome1.php:
<html>
<body>
<?php
$name=$_GET["name"];
$email=$_GET["email"];
echo "Welcome $name <br>";
echo "Your email address is:$email";
?>
</body>
</html>
5.14:List and Explain MySql database functions

 mysql_affected_rows — Get number of affected rows in previous MySQL operation


 mysql_close — Close MySQL connection
 mysql_connect — Open a connection to a MySQL Server
 mysql_create_db — Create a MySQL database
 mysql_data_seek — Move internal result pointer
 mysql_db_name — Retrieves database name from the call to mysql_list_dbs
 mysql_db_query — Selects a database and executes a query on it
 mysql_drop_db — Drop (delete) a MySQL database
 mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
 mysql_fetch_assoc — Fetch a result row as an associative array
 mysql_fetch_field — Get column information from a result and return as an object
 mysql_fetch_lengths — Get the length of each output in a result
 mysql_fetch_object — Fetch a result row as an object
 mysql_get_server_info — Get MySQL server info
 mysql_ping — Ping a server connection or reconnect if there is no connection
 mysql_query — Send a MySQL query
 mysql_real_escape_string — Escapes special characters in a string for use in an SQL statement
 mysql_result — Get result data
 mysql_select_db — Select a MySQL database
 mysql_set_charset — Sets the client character set
 mysql_stat — Get current system status
 mysql_tablename — Get table name of field
 mysql_thread_id — Return the current thread ID
 mysql_unbuffered_query — Send an SQL query to MySQL without fetching and buffering the
result rows

5.15:Explain the steps for connecting to a database


1. Create a connection
2. Select database
3. Perform database query
4. Use return data
5. Close connection

1. Create a connection

It is very important when you want to start a dynamic website to create a connection with your
SQL (we are talking about MySQL) by using mysql_connect() function. In mysql_connect()
arguments should be a string and it’s important to use die() function with mysql_error() function
to check if there is a problem with the connection or not.
2. Select database

Now we have to select the database which we are creating and saving our data by using
mysql_select_db() function which the arguments are the name of the database and connection we
made earlier.

3. Perform database query

In this step, we have to select out data from the database and bring it into our web page. The best
decision to use mysql_query() function which it will Send a MySQL query with 2 arguments as
displayed in the above code.

4. Use return data

To display the result on your web page, you have to use while() loop function in addition to
mysql_fetch_array() function which fetches a result row as an associative array, a numeric array,
or both.

5. Close connection

To close connection, it is better to use mysql_close() function to close MySQL connection.


5.16:Know about retrieving data from the database

The SELECT statement is used to select data from one or more tables:

SELECT column_name(s) FROM table_name

or we can use the * character to select ALL columns from a table:

SELECT * FROM table_name

5.17:Know about updating data in the database

The UPDATE statement is used to update existing records in a table:


UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

5.18:Know about inserting data into the database

After a database and a table have been created, we can start adding data in them.

Here are some 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

The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)

5.19:Know about deleting data from the database

The DELETE statement is used to delete records from a table:

DELETE FROM table_name


WHERE some_column = some_value

5.20. write Simple program for insert, update , select and delete data operations
Database Connection with PHP
Connect.php
<?php
$host="localhost";
$user="root";
$password="";

$con=mysqli_connect($host,$user,$password);
if($con)
{
echo "<script>alert('DB connected');</script>";
}
else
{
echo "<script>alert('DB connected');</script>";
}
mysqli_close($con);
?>

<?php
$host="localhost";
$user="root";
$password="";

$con=mysqli_connect($host,$user,$password);
if($con)
{
echo "DB connected";
}
else
{
echo "DB connected";
}
mysqli_close($con);
?>
Create Database:
<?php
$host="localhost";
$user="root";
$password="";

$con=mysqli_connect($host,$user,$password);
if($con)
{
echo "<script>alert('DB connected');</script>";
}
else
{
echo "<script>alert('DB connected');</script>";
}
$sql="create database Raji";
$res=mysqli_query($con,$sql);
if($res)
{
echo "<script>alert('DB created');</script>";
}
else
{
echo "<script>alert('DB not created');</script>";
}
mysqli_close($con);
?>
Create table
<?php
$host="localhost";
$user="root";
$password="";
$database="raji";

$con=mysqli_connect($host,$user,$password,$database);
if($con)
{
echo "<script>alert('DB connected');</script>";
}
else
{
echo "<script>alert('DB connected');</script>";
}
$sql="create table stu(sno int, name varchar(20), age int)";
$res=mysqli_query($con,$sql);
if($res)
{
echo "<script>alert('table created');</script>";
}
else
{
echo "<script>alert('table not created');</script>";
}
mysqli_close($con);
?>

Insert record into table:


<?php
$host="localhost";
$user="root";
$password="";
$database="raji";

$con=mysqli_connect($host,$user,$password,$database);
if($con)
{
echo "<script>alert('DB connected');</script>";
}
else
{
echo "<script>alert('DB connected');</script>";
}
$sql="insert into stu(sno, name,age) values(1,'mohan',35)";
$res=mysqli_query($con,$sql);
if($res)
{
echo "<script>alert('record inserted');</script>";
}
else
{
echo "<script>alert('record not inserted');</script>";
}
mysqli_close($con);
?>
Update record:
<?php
$host="localhost";
$user="root";
$password="";
$database="raji";

$con=mysqli_connect($host,$user,$password,$database);
if($con)
{
echo "<script>alert('DB connected');</script>";
}
else
{
echo "<script>alert('DB connected');</script>";
}
$sql="update stu set name='hari' where sno=1";
$res=mysqli_query($con,$sql);
if($res)
{
echo "<script>alert('record updated');</script>";
}
else
{
echo "<script>alert('record not updated');</script>";
}
mysqli_close($con);
?>

5.21)Define Cookie
A cookie is a small file that the server embeds on the user's computer.
(OR)
PHP cookie is a small piece of information which is stored at client browser.
Note:The maximum size of a cookie is 4KB .
Cookie is created at server side and saved to client browser. Each time when client sends request
to the server, cookie is embedded with request. Such way, cookie can be received at the server
side.

In short, cookie can be created, sent and received at server end.


5.21.1) Importance of Cookies(OR) Uses of Cookies(OR)Purpose of cookies
a)A cookie is often used to identify a user.(OR)It is used to recognize the user.
b)Cookies are used to keep track of your movement on a website, your visits, and activities.
c) Sometimes , you may be asked to fill out a form providing personal information; like your
name, e-mail address, and interests. This information is packaged into a cookie and sent to your
Web browser, which then stores the information for later use. The next time you go to the same
Web site, your browser will send the cookie to the Web server. The message is sent back to the
server each time the browser requests a page from the server.
d) Session cookies are used by government websites and online banks. They keep track of your
browsing session while you actively navigate the site. Once you close the browser, the cookies
will automatically expire. This prevents any malicious users from visiting those websites later
using your saved session data.
e)Permanent cookies are usually meant to help users by keeping track of their previous logins
so that they don’t need to enter usernames and passwords every time they visit a website.
Though “keep me logged in” or “remember me” feature on websites is handy and makes
things easier, it’s not exactly safe in terms of security and can be risky if people with malicious
intentions somehow get access to your computer. For security purposes, some websites offer an
option to disable cookies.
f) Third-party websites store cookies on your computer for the purpose of being able to collect as
much information about you as possible to be able to display more relevant ads. This may
include your search queries, behaviors, interests and more.
That’s why sometimes when you visit a website you may see a banner or advertisement of a
product you have previously looked at elsewhere. By tracking your movements with the help of
cookies advertisers can get very specific when it comes to what they show you.
Google, Facebook, YouTube, and Twitter are some of the most common websites using third-
party cookies.
g)A secure cookie can only be transmitted over an encrypted connection (i.e. HTTPS).
5.22)Creating a Cookie
A cookie is created with the setcookie() function.
Once cookie is set, you can access it by $_COOKIE super global variable.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);

Only the name parameter is required. All other parameters are optional.

Program:
<?php
setcookie("name", "mohan999", time() +3600);
echo "User Name is:";
echo $_COOKIE["name"];
?>
5.22.1) Deleting a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past.
<?php
// set the expiration date to one hour ago
setcookie("name", "Raj999", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie is deleted :<br>";
echo $_COOKIE['name'];
?>
</body>
</html>
5.24) Define Session
A session is a global variable stored on the server.
Note:
- Sessions are a simple way to store data for individual users against a unique session ID.
- Each session is given a unique ID that is used to track the variables for a user.
-Sessions have the capacity to store relatively large data compared to cookies.
-The session values are automatically deleted when the browser is closed.

PHP session creates unique user id for each browser to recognize the user and avoid conflict
between multiple browsers.
5.27) Importance of Sessions (OR)Uses of Sessions
a) Sessions are used to store important information such as the user id more securely on the
server where malicious users cannot temper with them.
b)Sessions are used to pass values from one page to another.
c) Sessions are used to store global variables in an efficient and more secure way compared to
passing them in the URL
d)Sessions are used to make data accessible across the various pages of an entire website .
e)Sessions are the alternative to cookies on browsers that do not support cookies.
Session Functions
 session_start() — Start new or resume existing session
 session_name — Get and/or set the current session name
 session_status() — Returns the current session status
 session_register() — Register one or more global variables with the current session
 session_unregister() — Unregister a global variable from the current session
 session_unset() — Free all session variables
 session_reset() — Re-initialize session array with original values
 session_destroy() — Destroys all data registered to a session
5.25) Creating a Session (OR) Start a Session

A session is started with the session_start() function.


Session variables are set with the PHP global variable: $_SESSION.

 session_start() function is used to start the session. It starts a new or resumes existing
session. It returns existing session if session is created already. If session is not available,
it creates and returns new session.
 $_SESSION is an associative array that contains all session variables. It is used to set
and get session variable values.
Program:
<?php
session_start();

$_SESSION['name']="mohan999";
$_SESSION['id']=123;
echo $_SESSION['name'];
echo $_SESSION['id']

?>
5.26) Destroy a PHP Session

-To remove all global session variables and destroy the session,
use session_unset() and session_destroy().

-Session_destroy removes all the session data including cookies associated with the session.
-Unset only frees the individual session variables.
EX:

<?php
session_start();

// remove all session variables


session_unset();

// destroy the session


session_destroy();
?>

5.28 :Difference Between Session and Cookies :

Cookie Session

Cookies are client-side files on a local Sessions are server-side files that contain
computer that hold user information. user data.

When the user quits the browser or logs out


Cookies end on the lifetime set by the user. of the programmed, the session is over.

It can only store a certain amount of info. It can hold an indefinite quantity of data.

Because cookies are kept on the local


computer, we don’t need to run a function to To begin the session, we must use the
start them. session_start() method.

Session are more secured compare than


Cookies are not secured. cookies.
Cookies stored data in text file. Session save data in encrypted form.

Cookies stored on a limited data. Session stored a unlimited data.

In PHP, to get the data from Cookies , In PHP , to set the data from Session,
$_COOKIE the global variable is used $_SESSION the global variable is used

5.29:Explain How to pass data from one web page to another web page
1. Using Cookies
2. Using Sessions
3. Using GET and POST Through HTML Form
1. Store the data in a session variable. By storing the data, the data can be passed from one page
to another.
2. Store data in a cookie. By storing data in a persistent cookie, data can be passed from one form
to another.
3. Store data in a form. By using GET and POST method , data can be passed from one form to
another.
1) Using Cookie:
Webpage1.php
<?php
setCookie("animal", "Dog");
echo " data sent";
?>
Webpage2.php
<?php
$value = $_COOKIE['animal'];
echo $value;
?>
2)Using Session:
Webpage1.php:
<?php
session_start();
$_SESSION["animal"] = "Dog";
echo "data sent";
?>
Webpage2.php:
<?php
session_start();
$value = $_SESSION["animal"];
echo $value;
?>
3)Using HTML Forms
3.1)Using GET Method:
Webpage1.php
<html>
<body>
<form action="welcome.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
Webpage2.php
<?php
$name=$_GET["name"];
$email=$_GET["email"];
echo $name ;
echo $email;
?>

3.2)Using POST method:


Webpage1.php
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
Webpage2.php
<?php
$name=$_POST["name"];
$email=$_POST["email"];
echo $name ;
echo $email;
?>
Unit-III-XML

XML stands for eXtensible Markup Language.

What is xml:
o XML(eXtensible Markup Language) is a mark up language.
o XML is designed to store and transport data.
o XML became a W3C Recommendation on February 10, 1998.
o XML is designed to carry data, not to display data.
o XML tags are not predefined. You must define your own tags.
o XML is platform independent and language independent.

o XML was designed to be both human- and machine-readable.

Why xml

Platform Independent and Language Independent: The main benefit of xml is that you can
use it to take data from a program like Microsoft SQL, convert it into XML then share that XML
with other programs and platforms. You can communicate between two platforms which are
generally very difficult.
The main thing which makes XML truly powerful is its international acceptance. Many
corporation use XML interfaces for databases, programming, office application mobile phones
and more. It is due to its platform independent feature.

3.1)XML Usage/ Applicaions of XML

 XML plays an important role in many different IT systems.


 XML is often used for distributing data over the Internet.
 XML can be used to exchange the information between organizations and systems.
 XML can be used for offloading and reloading of databases.
 Virtually, any type of data can be expressed as an XML document.
 XML is used to describe day-to-day data transactions:

-Stocks and Shares


-Financial transactions
-Medical data
-Mathematical data
-News information

Applicaions of XML
 Web publishing: XML allows you to create interactive pages, allows the customer to
customize those pages, and makes creating e-commerce applications more intuitive. With
XML, you store the data once and then render that content for different viewers or
devices based on style sheet processing using an Extensible Style Language (XSL)/XSL
Transformation (XSLT) processor.
 Web searching and automating Web tasks: XML defines the type of information
contained in a document, making it easier to return useful results when searching the
Web.
 General applications: XML provides a standard method to access information, making it
easier for applications and devices of all kinds to use, store, transmit, and display data.
 e-business applications: XML implementations make electronic data interchange (EDI)
more accessible for information interchange, business-to-business transactions, and
business-to-consumer transactions.
 Metadata applications: XML makes it easier to express metadata in a portable, reusable
format.
 Pervasive(wireless) computing: XML provides portable and structured information
types for display on pervasive (wireless) computing devices such as personal digital
assistants (PDAs), cellular phones, and others. For example, WML (Wireless Markup
Language) and VoiceXML are currently evolving standards for describing visual and
speech-driven wireless device interfaces.

3.2)HTML vs XML:

There are many differences between HTML (Hyper Text Markup Language) and XML
(eXtensible Markup Language). The important differences are given below:

No. HTML XML

1) HTML is used to display data and XML is a software and hardware independent tool used to
focuses on how data looks. transport and store data. It focuses on what data is.

2) HTML is a markup language itself. XML provides a framework to define markup languages

3) HTML is not case sensitive. XML is case sensitive.

4) HTML is a presentation language. XML is neither a presentation language nor a programming


language.

5) HTML has its own predefined tags. You can define tags according to your need.

6) In HTML, it is not necessary to use XML makes it mandatory to use a closing tag.
a closing tag.
7) HTML is static because it is used to XML is dynamic because it is used to transport data.
display data.

8) HTML does not preserve XML preserve whitespaces.


whitespaces.

3.3)XML Tree Structure/XML Syntax:

XML documents form a tree structure that starts at "the root" and branches to "the leaves".

XML documents are formed as element trees.


An XML tree starts at a root element and branches from the root to child elements.
All elements can have sub elements (child elements):
<root>
<child>
<subchild>.....</subchild>
</child>
</root>

Note:XML documents must contain one root element that is the parent of all other
elements.
XML Naming Rules:

XML elements must follow these naming rules:


 Element names are case-sensitive
 Element names must start with a letter or underscore
 Element names cannot start with the letters xml (or XML, or Xml, etc)
 Element names can contain letters, digits, hyphens, underscores, and periods
 Element names cannot contain spaces
Any name can be used, no words are reserved (except xml).

XML Example-1:

<?xml version="1.0" encoding="UTF-8"?>


<note>
<to>Students</to>
<from>Mohan Sir</from>
<heading>Reminder</heading>
<body>There will be an exam tomorrow!</body>
</note>
Note:
1)<?xml version="1.0" encoding="UTF-8"?> . This line is called the XML prolog.
The XML prolog is optional. If it exists, it must come first in the document.
2) UTF-8 is the default character encoding for XML documents.
3) In this example , <note> is the root element.
4) The next 4 lines describe 4 child elements of the root (to, from, heading, and body).

3.4)Structuring Data/Organization of data in the form of XML


XML allows you to describe data precisely in a well-structured format (or)well-formed format.

.A well-formed XML document is a document that conforms to the XML syntax rules, like:

o It must begin with the XML declaration.


o It must have one unique root element.
o All start tags of XML documents must match end tags.
o XML tags are case sensitive.
o All elements must be closed.
o All elements must be properly nested.
o All attributes values must be quoted.
o XML entities must be used for special characters.
XML Example- 2:
Following example demonstrates simple XML tree structure −

o <?xml version = "1.0"?>


o <Company>
o <Employee>
o <FirstName>Raaj</FirstName>
o <LastName>Mohan</LastName>
o <ContactNo>1234567890</ContactNo>
o <Email>rajmohan@gmail.com</Email>
o <Address>
o <City>Puttur</City>
o <State>Andhra Pradesh</State>
o <Zip>517583</Zip>
o </Address>
o </Employee>
o </Company>
Following tree structure represents the above XML document −
o In the above diagram, there is a root element named as <company>. Inside that, there is
one more element <Employee>. Inside the employee element, there are five branches
named <FirstName>, <LastName>, <ContactNo>, <Email>, and <Address>. Inside the
<Address> element, there are three sub-branches, named <City> <State> and <Zip>.
1. <?xml version="1.0"?>
2. <!DOCTYPE employee SYSTEM "employee.dtd">
3. <employee>
4. <firstname>Raaj</firstname>
5. <lastname>Mohan</lastname>
6. <email>Raaj@gmail.com</email>
7. </employee>
In the above example, the DOCTYPE declaration refers to an external DTD file. The content of
the file is shown in below paragraph.

3.6)XML- Namespaces

 XML Namespace is used to avoid element name conflict in XML document.

 The Namespace is identified by URI(Uniform Resource Identifiers).


 A Uniform Resource Identifier (URI) is a string of characters which identifies an
Internet Resource.
 The most common URI is the Uniform Resource Locator (URL) which identifies an
Internet domain address.

Name Conflicts
In XML, element names are defined by the developer(user). This often results in a conflict when
trying to mix XML documents from different XML applications.
Note: Generally name conflict occurs when we try to mix XML documents from different XML
applications.
Let's take an example with two tables:
Table1:
1. <table>
2. <tr>
3. <td>Apple</td>
4. <td>Mango</td>
5. </tr>
6. </table>
Table2: This table carries information about a computer table.
1. <table>
2. <name>Computer table</name>
3. <width>80</width>
4. <length>120</length>
5. </table>
If you add these both XML fragments together, there would be a name conflict because both
have <table< element. Although they have different name and meaning.
How to get rid of name conflict?

Method- 1) By Using a Prefix

You can easily avoid the XML namespace by using a name prefix.
1. <h:table>
2. <h:tr>
3. <h:td>Apple</h:td>
4. <h:td>Mango</h:td>
5. </h:tr>
6. </h:table>

7. <f:table>
8. <f:name>Computer table</f:name>
9. <f:width>80</f:width>
10. <f:length>120</f:length>
11. </f:table>
Method-2) By Using xmlns Attribute

You can use xmlns attribute to define namespace with the following syntax:

<element xmlns : name = "URL">

The Namespace starts with the keyword xmlns.


The word name is the Namespace prefix.
The URL is the Namespace identifier.
Example:
1. <root>
2. <h:table xmlns:h="http://www.mohan.com/TR/html4/">
3. <h:tr>
4. <h:td>Apple</h:td>
5. <h:td>Mango</h:td>
6. </h:tr>
7. </h:table>

8. <f:table xmlns:f="http://www.Raaj.com/furniture">
9. <f:name>Computer table</f:name>
10. <f:width>80</f:width>
11. <f:length>120</f:length>
12. </f:table>
13. </root>
In the above example, the <table> element defines a namespace and when a namespace is
defined for an element, the child elements with the same prefixes are associated with the same
namespace.

Method-3)The Default Namespace

The default namespace is used in the XML document to save you from using prefixes in all the
child elements.
The only difference between default namespace and a simple namespace is that: There is no need
to use a prefix in default namespace.

It has the following syntax:


Xmlns = "namespaceURI"

Example:

This XML carries HTML table information:


<table xmlns="http://www.Mohan.com/TR/html4/">
<tr>
<td>Apple</td>
<td>Mango</td>
</tr>
</table>
This XML carries information about a piece of furniture:
<table xmlns="https://www.Raaj.com/furniture">
<name>Computer Table</name>
<width>80</width>
<length>120</length>
</table>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy