Professional Documents
Culture Documents
UNIT IV
Syllabus: An introduction to PHP: PHP- Using PHP- Variables- Program control- Built-in functions-Form
Validation- Regular Expressions - File handling – Cookies - Connecting to Database.
XML: Basic XML- Document Type Definition- XML Schema DOM and Presenting XML, XML Parsers and
Validation, XSL and XSLT Transformation, News Feed (RSS and ATOM).
i) The bottom tier (also called the data tier or the information tier) maintains the
application’s data. This tier typically stores data in a relational database management system
(RDBMS).
ii) The middle tier implements business logic, controller logic and presentation
logic to control interactions between the application’s clients and its data.
➢ Business logic in the middle tier enforces business rules and ensures that data is reliable
before the application updates a database or presents data to users.
iii) The top tier, or client tier, is the application’s user interface, which gathers
input and displays output.
Client-side Scripting versus Server-side Scripting
➢ Server-side Scripting
o Programmers have more flexibility with server-side scripts, which often
generate custom responses for clients.
o Server-side scripting languages have a wider range of programmatic capabilities
than their client-side equivalents.
o Server-side scripts also have access to server-side software that extends server
functionality.
o PHP is the most popular server-side scripting language for creating dynamic, data-driven web
applications.
JSP PHP
Java Server Pages Hypertext Preprocessor
Server-side programming
Server-side scripting language
technology
Uses Java as the base for Does not need any other
programming programming language
Used to develop small to medium
Used to develop web applications
sized web applications with dynamic
with dynamic content.
content.
JSP requires more code and is PHP is simple and needs fewer lines
complex. of codes.
JSP allows to define custom tags. PHP won't allow custom tags.
JSP has better memory PHP memory management
management techniques techniques are difficult
o The Apache HTTP Server, maintained by the Apache Software Foundation, is the most
popular web server in use today because of its stability, efficiency, portability, security and
small size. It’s open source software that runs on Linux, Mac OS X, Windows and numerous
other platforms.
o MySQL is the most popular open-source database management system. It, too, runs on
Linux, Mac OS X and Windows.
o PHP is the most popular server-side scripting language for creating dynamic, data-driven
web applications.
o The Apache HTTP Server, MySQL database server and PHP can each be downloaded and
installed separately, but this also requires additional configuration on our part.
o We’ll use the XAMPP integrated installer provided by the Apache Friends website
(www.apachefriends.org).
What is XAMPP?
XAMPP is the most popular PHP development environment. XAMPP is a completely free, easy to
install Apache distribution containing MariaDB, PHP, and Perl.
XAMPP installation
2. Running XAMPP
Once we have installed XAMPP, we can start the Apache and MySQL servers for windows platform
as described below.
Windows:
o Go to c:\xampp folder (or the folder in which we installed XAMPP) and double click
xampp_start.exe.
o If we need to stop the servers, use xampp_stop.exe in the same folder.
o PHP code is inserted between the delimiters <?php and ?> and can be placed anywhere in
HTML.
o PHP tag, informs interpreter to execute PHP code.
Comments
Single line comments: # or //
Multiline comments: /* */
Statements
o In this case the echo() function outputs a quoted string (as its argument) within its
parentheses.
o Each statement must end with a semi-colon (;)
<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php echo("Hello, World! \n"); ?>
o Save the file with First_php.php and place this file under C:\xampp\htdocs
o Open browser and launch the URL http://localhost:90/First_php.php
PHP Variables
Assigned by Value
$num = 10 ;
$name= "SVCK" ;
Assigned by Reference
o Prefix & (ampersand) to variable being referenced
$num2 = &$num1 ;
✓ Converting between different data types may be necessary when performing arithmetic
operations with variables.
✓ Type conversion can be done in two ways:
✓ When converting from a string to a number, PHP uses the value of the number that
appears at the beginning of the string. If no number appears at the beginning, the string
evaluates to 0.
<!DOCTYPE html>
<html>
<head><title>Type Conversions</title></head>
<body>
<?php
$strvar = "7.3 seconds";
print("<h1>String $strvar as double type : </h1>");
settype($strvar, "double");
print("<h1>$strvar </h1>");
print("<h1>Data type after conversion=".gettype($strvar). "</h1>");
WT – UNIT IV – R19 Page 6
$doublevar = "7.356";
print("<p><h1>Double $doublevar as int type : </h1>");
settype($doublevar, "integer");
print("<h1>$doublevar </h1>");
$intvar = 7;
print("<h1>Int $intvar as String type : </h1>");
settype($intvar, "string");
print("<h1>$intvar </h1>");
?>
</body>
</html>
2. Type Casting
• Another option for conversion between types is casting (or type casting).
• Unlike settype, casting does not change a variable’s content—it creates a temporary copy of
a variable’s value in memory.
• Casting is useful when a different type is required in a specific operation but you would like
to retain the variable’s original value and type.
<html>
<head>
<title>PHP Type Casting</title>
</head>
<body>
<?php
$doublevar = 100.24;
print("<h1>double val=" . $doublevar ."</h1>");
print("<h1>integer value=" . (int)$doublevar ."</h1>");
print("<h1>String value=" . (string)$doublevar ."</h1>");
print("<h1>Type of the data= " . gettype($doublevar) ."</h1>");
?>
</body>
</html>
Output
Arithmetic Operators
• PHP provides several arithmetic operators.
• Strings are converted to integers or doubles when they’re used in arithmetic operations.
• A copy of the value of variable str, "3 dollars", is converted to the integer 3 for use in the
calculation.
<!DOCTYPE html>
<html>
<head>
<title>PHP Operators</title>
</head>
<body>
<?php
define("b",30);
$a = 10;
print("<h1> Value of a = $a</h1>");
$a = $a + 10;
print("<h1> Value of a after adding 20 = $a</h1>");
$a = b + $a;
?>
</body>
String Concatenation
• The concatenation operator (.) combines multiple strings in the same print statement.
String Comparison
<html>
<head>
<title>PHP Strings Comparison operations</title>
</head>
<body>
<?php
$sw = array("C","JAVA","Oracle");
if(strcmp($sw[1],"PHP"))
print("<b><p>$sw[1] precedes before PHP</p></b>");
Output
Meta characters
<html>
<head>
<title>PHP-Strings with Regular Expression</title>
</head>
<body>
<?php
if(preg_match("/[a-z]/",$str))
print("<b><p> a-z is found</p></b>");
else
print("<b><p> a-z is not found</p></b>");
if(preg_match("/[a-z]*ing/",$str))
print("<b><p> ing is found at the end</p></b>");
else
print("<b><p> ing is not found at the end</p></b>");
?>
</body>
</html>
Output
PHP Arrays
• An array is a data structure that stores one or more similar type of values in a single value.
• For example if you want to store 100 numbers then instead of defining 100 variables its easy
to define an array of 100 length
There are three different kind of arrays and each array value is accessed using an ID which is
called array index.
• Indexed array − An array with a numeric index. Values are stored and accessed in linear
way.
• 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.
• Multidimensional array − An array containing one or more arrays and values are accessed
using multiple indices.
1st way:
$season=array("summer","winter","spring","autumn");
2nd way:
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
• We can associate name with each array elements in PHP using => symbol.
1st way:
$salary=array(“Sachin"=>"350000",“Jadeja"=>"450000","Kartik"=>"200000");
2nd way:
$salary[" Sachin"]="350000";
$salary[" Jadeja"]="450000";
$salary["Kartik"]="200000";
• PHP multidimensional array can be represented in the form of matrix which is represented by
row * column.
$emp = array
array(2,"jadeja",500000),
array(3,“Karthik",300000)
);
Method 1
<html>
<head>
<title>PHP Arrays</title>
</head>
<body>
<?php
Output
<html>
<head>
<title>PHP Arrays - Method 2</title>
</head>
<body>
<?php
Output
<html>
<head>
<title>PHP Associative Arrays</title>
</head>
<body>
<?php
Output
<html>
<head>
<title>PHP Associative Arrays - Method 4</title>
</head>
<body>
<?php
// create array months
print( " <h1><p>Function array - Associative Array</h1></p>" );
$months = array("JAN","FEB");
$months = array(
"January" => "JAN", "February" => "FEB");
Output
Function Syntax
function functionName(parameters)
{
function-body
}
Example
<html>
<head>
<title>Function Example</title>
</head>
<body>
<?php
$r = display();
echo "<b><p>$r</p></b>";
function display()
{
echo "<b><p>PHP Function</p></b>";
$i = 10;
return $i;
}
?>
</body>
</html>
Output
list() function
✓ The list() function is used to assign values to a list of variables in one operation.
<!DOCTYPE html>
<html>
<body>
$colors = array("red","blue","green");
?>
</body>
</html>
return statement
• The return() statement returns any ensuing value back to the function caller, returning
program control back to the caller’s scope in the process.
<html>
<head>
<title>Functions Return multiple values</title>
</head>
<body>
<?php
function retriveDetails($name,$college)
{
$details[0] = $name;
$details[1] = $college;
return $details;
}
list($n,$c) = retriveDetails("501","SVCK");
echo "<h1>Name = $n - College = $c</h1>";
?>
</body>
</html>
Output
• In Pass-By-Value, any changes made to those values within the scope of the function are
ignored outside of the function.
• Passing Arguments by Reference is done by appending an ampersand to the front of the
argument.
<html>
<head>
<title>Call-By-Value and Call-By-Reference Example</title>
</head>
<body>
<?php
//Call by value and call by reference
$x = 10;
$y = 20;
demoParams($x,$y);
echo "<b><p>x = $x</p></b>";
echo "<b><p>y = $y</p></b>";;
Output
• Default values can be assigned to input arguments, which will be automatically assigned to
the argument if no other value is provided.
<?php
function sum($i,$j=50)
{
$sum = $i + $j;
return $sum;
}
$x = 10;
$r = sum($x);
echo "<h1>Sum= $r</h1>";
?>
</body>
</html>
Output
Recursive Functions
• Recursive functions, or functions that call themselves, are used to divide an otherwise
complex problem into a simple case, reiterating that case until the problem is resolved.
<html>
<head>
<title>Factorial - Recursion Example</title>
</head>
<body>
<?php
$n=5;
$res = fact($n);
echo "<h1>Factorial of $n is = $res </h1>";
function fact($x)
{
if($x == 0)
return 1;
else
return $x * fact($x-1);
Output
Function Libraries
• Functions offer a great way to reuse code and are often collectively assembled into libraries
and subsequently repeatedly reused within similar applications.
• PHP libraries are created via the simple aggregation of function definitions in a single file.
<?php
?>
User_Functions.php
<html>
<head>
<title>User defined Library Functions Example
</title>
</head>
<body>
<?php
function add($a,$b)
{
return $a+$b;
}
function sub($a,$b)
{
return $a-$b;
}
?>
Import_Lib_Fun.php
<html>
<head>
<title>Importing Library Functions Example
</title>
</head>
<body>
<?php
WT – UNIT IV – R19 Page 22
require_once("User_functions.php");
$r = add(5,9);
echo "<h1>Sum = $r</h1>";
$r = sub(5,9);
Output:
PHP Cookies
What is a Cookie?
▪ A website can store a cookie on a client’s computer to record user preferences and other
information that the website can retrieve during the client’s subsequent visits.
▪ Websites should not store critical information, such as credit card numbers or passwords, in
cookies, because cookies are typically stored in text files that any program can read.
▪ A server can access only the cookies that it has placed on the client.
▪ A cookie also has an expiration date, after which the web browser deletes it.
Types of Cookies
▪ Session Cookie:
Cookies.php
<html>
<head>
<meta charset = "utf-8">
<title>Writing a cookie to the client computer</title>
Cookies_display.php
<!DOCTYPE html>
<html>
<head>
<title>Displaying Cookie</title>
</head>
<body>
<?php
define( "FIVE_DAYS", 60 * 60 * 24 * 5 ); // define constant
</body>
</html>
Output
• FORM : A webform, web form or HTML form on a web page allows a user to enter data
that is sent to a server for processing
Methods:
• GET - $_GET($name)
POST - $_POST($name)
Form1.php
<html>
<head>
<title>Date Example
</title>
</head>
<body>
Form2.php
<html>
<head>
<title>Form Example
</title>
</head>
<body>
<?php
// If the name field is filled in
if (isset($_POST['submit'])) //
{
$name = $_POST['username'];
$email = $_POST['email'];
printf("Hi %s! <br />", $name);
printf("The Email address is - %s <br />", $email);
}
?>
</body>
</html>
POST Method
• http://localhost:90/forms2.php
GET Method
• http://localhost:90/forms2.php?name=CSE&email=1234%40gmail.com&submit=Go%21
1. Register Driver
2. Create connection
3. Create statement object
4. Execute Query
5. Close the connection
Example
data.php
<!DOCTYPE html>
<head>
</head>
<body>
<option selected>*</option>
<option>ID</option>
<option>Title</option>
<option>Category</option>
<option>Author</option>
</select></p>
</form>
</body>
</html>
Query_db_display.php
<!DOCTYPE html>
<html>
<head>
<title>Search Results</title>
background-color: lightyellow; }
border-collapse: collapse;
td { padding: 5px; }
tr:nth-child(odd) {
background-color: white; }
</style>
</head>
<body>
<?php
include 'db_connection.php';
// Connect to MySQL
} // end if
mysql_close( $database);
<table>
FROM books"</caption>
<?php
while($row = $result->fetch_assoc())
print( "<tr>" );
print( "<td>$value</td>" );
print( "</tr>" );
} // end while
</table>
</body>
</html>
mysql_db_connection.php
<?php
function mysql_connect()
$dbhost = "localhost";
$dbuser = "WIT";
$dbpass = "WIT";
$db = "WIT";
function mysql_close($conn)
function mysql_query($query,$conn)
$result = $conn->query($query);
return $result;
function mysql_error()
?>
• The Extensible Markup Language (XML) was developed in 1996 by the World Wide Web
Consortium’s (W3C’s) XML Working Group.
• XML describes data in a way that human beings can understand and computers can process.
Rules of XML
XML Structure
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
Example:
<Library>
<book cateogry="Techniccal">
<title>CP</title>
<author gender="M">James</author>
<cost>500</cost>
</book>
<book cateogry="Science">
<title>Physics</title>
<author gender="M">Roy</author>
<cost>600</cost>
</book>
</Library>
• XML documents delimit elements with start tags and end tags.
• start tag consists of the element name in angle brackets
• An end tag consists of the element name preceded by a forward slash (/) in angle
brackets
• Every XML document must have exactly one root element that contains all the other
elements.
• To view and modify an XML document, we just need a Simple Text Editor with ASCII /
Unicode character support.
Example
Notepad++
XML attributes
• XML elements can have attributes. By the use of attributes we can add the information about
the element.
• XML attributes enhance the properties of the elements.
• XML attributes must always be quoted. We can use single or double quote.
<book publisher="Tata McGraw Hill"></book>
XML Validation
• https://www.xmlvalidation.com/index.php?id=1&L=0
XML DOM
➢ It is a standard document model that is used to access and manipulate XML. It defines the
XML file in tree structure.
➢ This hierarchical tree structure is called a Document Object Model (DOM) tree, and an XML
parser that creates this type of structure is known as a DOM parser.
• A DTD describes the structure of an XML document and enables an XML parser to verify
whether an XML document is valid (i.e., whether its elements contain the proper attributes
and appear in the proper sequence).
• A DTD expresses the set of rules for document structure using an EBNF (Extended Backus-
Naur Form) grammar.
Example
<library>
<book BookId="101">
<title>CP</title>
<auth>Kan</auth>
<publisher>B</publisher>
<yop>2010</yop>
<price>2000</price>
</book>
<member MemberId="M01">
<name>Rahul</name>
<address>Kadapa</address>
<phone>9555</phone>
</member>
<staff StaffId="S01">
<name>GS</name>
<address>CHN</address>
<phone>2345</phone>
</staff>
<author AuthorId="A01">
<name>VVS</name>
<address>VJA</address>
<phone>1456</phone>
</author>
</library>
Library.dtd file
• Keyword #IMPLIED specifies that if the parser finds a contact element without a type
attribute, the parser can choose an arbitrary value for the attribute or can ignore the attribute.
• Keyword #REQUIRED specifies that the attribute must be present in the element.
• Keyword #FIXED specifies that the attribute (if present) must have the given fixed value.
o Keyword CDATA (line 9) specifies that attribute type contains character data
(i.e., a string).
o Keyword #PCDATA specifies that an element (e.g., name) may contain parsed
character data (i.e., data that’s processed by an XML parser).
• Parsed Character Data cannot contain markup characters, such as less than (<), greater than
(>) or ampersand (&).
• The document author should replace any markup character in a #PCDATA element with the
character’s corresponding character entity reference.
➢ It is a XML document.
Validation
www.xmlforasp.net/SchemaValidator.aspx
• Extensible Stylesheet Language (XSL) documents specify how programs are to render
XML document data.
• XPath is a string-based language of expressions used by XML and many of its related
technologies for effectively and efficiently locating structures and data (such as specific
elements and attributes) in XML documents.
• XSL Transformations (XSLT)—is a technology for transforming XML documents into other
documents—i.e., transforming the structure of the XML document data to another structure.
o For example, XSLT allows you to convert a simple XML document to an XHTML
document that presents the XML document’s data (or a subset of the data) formatted
for display in a web browser.
Ex:
XML Namespaces
• An XML namespace is a collection of element and attribute names.
✓ Two popular types of URI are Uniform Resource Name (URN) and Uniform Resource
Locator (URL).
<subject>Geometry</subject>
<subject>Cardiology</subject>
<highschool:subject>Geometry</highschool:subject>
<medicalschool:subject>Cardiology</medicalschool:subject>
✓ Processing an XML document requires software called an XML parser (or XML
processor).
✓ Document’s contents, a parser checks that the document follows the syntax rules
specified by the W3C’s XML Recommendation (www.w3.org/XML).
✓ XML parser is used to read, update, create and manipulate an XML document
• Content Syndication is a mechanism using which the contents of a website including articles,
news, blogs and forums are published partially or fully to other websites in a specific format.
• RSS and Atom are the two main standards of web syndication.
What’s a “feed”?
• RSS feed and ATOM feed are small text files that provide information about content on
websites.
• When content is updated, the feed text file is also updated, either manually or
programmatically.
• Applications called “readers” or “aggregators” can then check these small text files and
notify someone when new content is available.
• If you already have an RSS feed, creating an Atom feed is extremely easy.
• With RSS it is possible to distribute up-to-date web content from one web site to thousands
of other web sites around the world.
• RSS allows fast browsing for news and updates.
• RSS stands for Really Simple Syndication
<channel>
<title>W3Schools Home Page</title>
<link>https://www.w3schools.com</link>
<description>Free web building tutorials</description>
<item>
<title>RSS Tutorial</title>
<link>https://www.w3schools.com/xml/xml_rss.asp</link>
WT – UNIT IV – R19 Page 39
<description>New RSS tutorial on W3Schools</description>
</item>
<item>
<title>XML Tutorial</title>
<link>https://www.w3schools.com/xml</link>
<description>New XML tutorial on W3Schools</description>
</item>
</channel>
</rss>
What is ATOM?
• Atom is the name of an XML-based Web content and metadata syndication format, and an
application-level protocol for publishing and editing Web resources belonging to periodically
updated websites.
• All Atom feeds must be well-formed XML documents, and are identified with
the application/atom+xml media type.
<title>Example Feed</title>
<link href="http://example.org/"/>
<updated>2003-12-13T18:30:02</updated>
<author>
<name>John Doe</name>
</author>
<entry>
<title>Atom-Powered Robots Run Amok</title>
<link href="http://example.org/2003/12/13/atom03"/>
<updated>2003-12-13T18:30:02Z</updated>
<summary>Some text.</summary>
</entry>
</feed>