Sunteți pe pagina 1din 43

PART - A

1. What is XML parse tree? [N/D 15]


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>
2. Why is XSLT an important tool in development of web applications? [M/J 16]
The original document is not changed; rather, a new document is created based on the
content of an existing one.Typically, input documents are XML files, but anything from
which the processor can build an XQuery and XPath Data Model can be used, for
example relational database tables, or geographical information systems.
3. When should the super global arrays in PHP be used? Which super global array in
PHP would contain a HTML forms POST data? [M/J 16]
$GLOBALS is a PHP super global variable which is used to access global variables from
anywhere in the PHP script (also from within functions or methods).
PHP stores all global variables in an array called $GLOBALS[index]. The index holds the
name of the variable.
The example below shows how to use the super global variable $GLOBALS:
<?php
$x= 75;
$y= 25;
function addition()

$GLOBALS['z']= $GLOBALS['x']+ $GLOBALS['y'];


}

addition();
echo $z;
?>
In the example above, since z is a variable present within the $GLOBALS array, it is also
accessible from outside the function
PHP $_POST is widely used to collect form data after submitting an HTML form with
method="post". $_POST is also widely used to pass variables.
$_SERVER['REQUEST_METHOD'] - Returns the request method used to access the
page (such as POST)
4. Name any four built-in functions in PHP. [N/D 15]
array() - Creates an array
cal_days_in_month() - Returns the number of days in a month for a specified year and
calendar
date.timezone - The default timezone (used by all date/time functions)
chdir() - Changes the current directory
5. Define XML.
Extensible Markup Language (XML) is a markup language that defines a set of rules
for encoding documents in a format that is both human-readable and machine-readable. It
is defined by the W3C's XML 1.0 Specification and by several other related
specifications, all of which are free open standards.
The basic building block of an XML document is an element, defined by tags. An
element has a beginning and an ending tag. All elements in an XML document are
contained in an outermost element known as the root element.
6. Define DTD.
A document type definition (DTD) is a set of markup declarations that define a
document type for an SGML-family markup language (SGML, XML, and HTML). A
Document Type Definition (DTD) defines the legal building blocks of an XML
document. It defines the document structure with a list of legal elements and attributes.
7. What are the XML rules for distinguishing between the content of a document and
the XML markup element?

The start of XML markup elements is identified by either the less than symbol (<)
or the ampersand (&) character.

Three other characters, the greater than symbol (>), the apostrophe or single quote

() and the double quotation marks () are used by XML for markup.

To use these special characters as content within your document, you must use the
corresponding general XML entity.
8. What is DOM?
The DOM is a W3C (World Wide Web Consortium) standard. The DOM defines a
standard for accessing documents: "The W3C Document Object Model (DOM) is a
platform and language-neutral interface that allows programs and scripts to dynamically
access and update the content, structure, and style of a document."
9. What is XSLT?
XSLT (ExtensibleStylesheet

Language

Transformations)

is

language

for transforming XML documents into other XML documents, or other formats such
as HTML for web pages, plain text or into XSL Formatting Objects, which may
subsequently be converted to other formats, such as PDF, PostScript and PNG.
10. What is metadata?
Metadata is simply data about data, or, to put it another way, data that describes other
data. Take, for example, an XML document. An XML document contains markup, which
is a form of metadata. Consider this fragment:
<p>The <library-name>foobar</library-name> library contains the routines <routinename>foo()</routine-name> and <routine-name>bar()</routine-name>.</p>
The <p> tag is metadata that tells us that the string it contains is a paragraph. The
<library-name> and <routine-name> tags are metadata that tell us that the strings they
contain are library names and routine names respectively.
11. What are the uses of XLink,Xpath,Xquery?.
XLink is used to create hyperlinks in XML documents.
XPath: provides a common syntax and semantics for functionality shared between XSLT
and XPointer.
XQuery: query language. It facilitates the data extraction from XML documents.
12. Define PHP.
PHP: Hypertext Preprocessor is a server-side scripting language designed for web
development but also used as a general-purpose programming language. PHP code may
be embedded into HTML code, or it can be used in combination with various web
template systems, web content management systems and web frameworks.

PHP code is usually processed by a PHP interpreter implemented as a module in the web
server or as a Common Gateway Interface (CGI) executable.
13. What are the rules to write variables in PHP?
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
Rules for PHP variables:

A variable starts with the $ sign, followed by the name of the variable

A variable name must start with a letter or the underscore character

A variable name cannot start with a number

A variable name can only contain alpha-numeric characters and underscores (A-z,

0-9, and _ )

Variable names are case-sensitive ($age and $AGE are two different variables)

14. What is meant by RSS and ATOM?


RSS stands for both Rich Site Summary and Really Simple Syndication but it always
refers to the same technology. It is a mean of transmitting and updating news in an
automated way. Most news sites (including virtually all blogs) will publish what is called
an RSS feed which is regularly updated with the latest available headlines and/or articles.
The RSS feed is not human readable. It is an XML format which is designed to be read
by machines rather than humans.
The name Atom applies to a pair of related Web standards. The Atom Syndication
Format is

an XML language

used

for web

feeds,

while

the Atom

Publishing

Protocol (AtomPub or APP) is a simple HTTP-based protocol for creating and updating
web resources. A feed contains entries, which may be headlines, full-text articles,
excerpts, summaries, and/or links to content on a website, along with various metadata.
The Atom format was developed as an alternative to RSS.
15. How to connect a database in PHP?
We should establish a connection to the MySQL database. This is an extremely important
step because if our script cannot connect to its database, our queries to the database will
fail. A good practice when using databases is to set the username, the password and the

database name values at the beginning of the script code. If we need to change them later,
it will be an easy task.
$username="our_username";$password="our_password";$database="our_database";
We should replace "our_username", "our_password" and "our_database" with the
MySQL username, password and database that will be used by our script.
Next we should connect our PHP script to the database. This can be done with the
mysql_connect PHP function:
mysql_connect(localhost,$username,$password);
Part B
1. Write a PHP program to do string manipulations.
Following are valid examples of string

[Nov/Dec15](16)

$string_1 = "This is a string in double quotes";


$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables
with their values as well as specially interpreting certain character sequences.
<?php
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
print "<br />";
$literally = "My $variable will print!\\n";
print($literally);
?>
This will produce the following result
My $variable will not print!\n
My name will print

String Concatenation Operator


To concatenate two string variables together, use the dot (.) operator
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
This will produce the following result
Hello World 1234
strlen() function
The strlen() function is used to find the length of a string.
Let's find the length of our string "Hello world!":
<?php
echo strlen("Hello world!");
?>

This will produce the following result


12
strpos() function
The strpos() function is used to search for a string or character within a string. If a match is
found in the string, this function will return the position of the first match. If no match is found,
it will return FALSE. Let's see if we can find the string "world" in our string
<?php
echo strpos("Hello world!","world");
?>

This will produce the following result


6

To ensure all the letters in a specific string were uppercase, we can use the strtoupper()function
as follows:
<?php
$str = "Like a puppet on a string.";
$cased = strtoupper($str);
// Displays: LIKE A PUPPET ON A STRING.
echo $cased;

It is perhaps obvious but still worth noting that numbers and other non-alphabet characters will
not be converted.
The strtolower() function does the exact opposite of strtoupper() and converts a string into all
lowercase letters:
<?php
$str = "LIKE A PUPPET ON A STRING.";
$cased = strtolower($str);
// Displays: like a puppet on a string.
echo $cased;

Likewise when we want to ensure certain words, such as names or titles, just have the first letter
of each word capitalized. For this we can use the ucwords() function:
<?php
$str = "a knot";
$cased = ucwords($str);
// Displays: A Knot
echo $cased;

It is also possible to manipulate the case of just the first letter of a string using the lcfirst() and
ucfirst() functions. If we want the first letter to be lowercase, use lcfirst(). If we want the first
letter to be uppercase, use ucfirst(). The ucfirst() function is probably the most useful since we
can use it to ensure a sentence always starts with a capital letter.
<?php

$str = "how long is a piece of string?";


$cased = ucfirst($str);
//Displays: How long is a piece of string?
echo $cased;
2. Explain in detail about i) XML Schema
[Nov / Dec 15] (8)
Let's have a look at this XML document called "shiporder.xml"
<?xml version="1.0" encoding="UTF-8"?>
<shiporder orderid="889923"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="shiporder.xsd">
<orderperson>JohnSmith</orderperson>
<shipto>
<name>OlaNordmann</name>
<address>Langgt23</address>
<city>4000Stavanger</city>
<country>Norway</country>
</shipto>
<item>
<title>EmpireBurlesque</title>
<note>SpecialEdition</note>
<quantity>1</quantity>
<price>10.90</price>
</item>
<item>
<title>Hideyourheart</title>
<quantity>1</quantity>
<price>9.90</price>
</item>
</shiporder>

The XML document above consists of a root element, "shiporder", that contains a
required attribute called "orderid".
The "shiporder" element contains three different child elements: "orderperson", "shipto"
and "item".
The "item" element appears twice, and it contains a "title", an optional "note" element, a
"quantity", and a "price" element.

The line above: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" tells the


XML parser that this document should be validated against a schema.

The line: xsi:noNamespaceSchemaLocation="shiporder.xsd" specifies WHERE the


schema resides (here it is in the same folder as "shiporder.xml").

Create an XML Schema


Now we want to create a schema for the XML document above.

We start by opening a new file that we will call "shiporder.xsd".


To create the schema we could simply follow the structure in the XML document and
define each element as we find it.

We will start with the standard XML declaration followed by the xs:s element that defines
a schema:

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


<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
...
</xs:schema>

In the schema above we use the standard namespace (xs), and the URI associated with
this namespace is the Schema language definition, which has the standard value of
http://www.w3.org/2001/XMLSchema.
Next, we have to define the "shiporder" element.

This element has an attribute and it contains other elements, therefore we consider it as a
complex type.

The child elements of the "shiporder" element is surrounded by a xs:sequence element


that defines an ordered sequence of sub elements:

<xs:element name="shiporder">
<xs:complexType>
<xs:sequence>
...
</xs:sequence>
</xs:complexType>
</xs:element>

3. List at least five significant differences between DTD and XML schema for defining
XML document structures with appropriate examples.[May/June 16] (8)
XML Schema vs. DTD

DTD, or Document Type Definition, and XML Schema, which is also known as
XSD, are two ways of describing the structure and content of an XML document.

DTD is the older of the two, and as such, it has limitations that XML Schema has
tried to improve.

The first difference between DTD and XML Schema, is namespace awareness;
XML Schema is, while DTD is not.

Namespace awareness removes the ambiguity that can result in having certain
elements and attributes from multiple XML vocabularies, by giving them
namespaces that put the element or attribute into context.

Part of the reason why XML Schema is namespace aware while DTD is not, is
the fact that XML Schema is written in XML, and DTD is not.

Therefore, XML Schemas can be programmatically processed just like any XML
document.

XML Schema also eliminates the need to learn another language, as it is written in
XML, unlike DTD.

Another key advantage of XML Schema, is its ability to implement strong typing.

An XML Schema can define the data type of certain elements, and even constrain
it to within specific lengths or values.

This ability ensures that the data stored in the XML document is accurate.

DTD lacks strong typing capabilities, and has no way of validating the content to
data types.

XML Schema has a wealth of derived and built-in data types to validate content.

It also has uniform data types, but as all processors and validators need to support
these data types, it often causes older XML parsers to fail.

A characteristic of DTD that people often consider both as an advantage and


disadvantage, is the ability to define DTDs inline, which XML Schema lacks.

This is good when working with small files, as it allows you to contain both the
content and the schema within the same document, but when it comes to larger
documents, we have to pull content every time while we retrieve the schema. This
can lead to serious overhead that can degrade performance.

1. XML Schema is namespace aware, while DTD is not.


2. XML Schemas are written in XML, while DTDs are not.
3. XML Schema is strongly typed, while DTD is not.
4. XML Schema has a wealth of derived and built-in data types that are not available in
DTD.
5. XML Schema does not allow inline definitions, while DTD does.
No.

DTD
for Document

XSD

1)

DTD stands
Definition.

Type

XSD stands for XML Schema Definition.

2)

DTDs are derived from SGML syntax.

XSDs are written in XML.

3)

DTD doesn't support datatypes.

XSD supports datatypes for elements and attributes.

4)

DTD doesn't support namespace.

XSD supports namespace.

5)

DTD doesn't define order for child


elements.

XSD defines order for child elements.

6)

DTD is not extensible.

XSD is extensible.

7)

DTD is not simple to learn..

XSD is simple to learn because you don't need to learn

new language..
8)

DTD provides less control on XML


structure.

XSD provides more control on XML structure

4. Explain in detail about XML parsers and Validation

[N / D 15] (8)

XML PARSERS:
An XML parser is a software library or package that provides interfaces for client applications to
work with an XML document. The XML Parser is designed to read the XML and create a way
for programs to use XML.
XML parser validates the document and check that the document is well formatted.
Let's understand the working of XML parser by the figure given below:

Types of XML Parsers


These are the two main types of XML Parsers:
1. DOM
2. SAX
DOM (Document Object Model)
A DOM document is an object which contains all the information of an XML document. It is
composed like a tree structure. The DOM Parser implements a DOM API. This API is very
simple to use.

Features of DOM Parser


A DOM Parser creates an internal structure in memory which is a DOM document object and the
client applications get information of the original XML document by invoking methods on this
document object.
DOM Parser has a tree based structure.
Advantages
1) It supports both read and write operations and the API is very simple to use.
2) It is preferred when random access to widely separated parts of a document is required.
Disadvantages
1) It is memory inefficient. (Consumes more memory because the whole XML document needs
to loaded into memory).
2) It is comparatively slower than other parsers.
SAX (Simple API for XML)
A SAX Parser implements SAX API. This API is an event based API and less intuitive.
Features of SAX Parser

It does not create any internal structure.

Clients does not know what methods to call, they just overrides the methods of the API
and place his own code inside method.

It is an event based parser, it works like an event handler in Java.

Advantages
1) It is simple and memory efficient.
2) It is very fast and works for huge documents.
Disadvantages
1) It is event-based so its API is less intuitive.
2) Clients never know the full information because the data is broken into pieces.
XML VALIDATION:
A well formed XML document can be validated against DTD or Schema.
A well-formed XML document is an XML document with correct syntax. It is very necessary to
know about valid XML document before knowing XML validation.
Valid XML document

It must be well formed (satisfy all the basic syntax condition)

It should be behave according to predefined DTD or XML schema

Rules for well formed XML


o

It must begin with the XML declaration.

It must have one unique root element.

All start tags of XML documents must match end tags.

XML tags are case sensitive.

All elements must be closed.

All elements must be properly nested.

All attributes values must be quoted.

XML entities must be used for special characters.

5.
List the essential features of XML parsers.
[May/June 16] (8)
XML is widely used in the era of web development. It is also used to simplify data storage and
data sharing.
The main features or advantages of XML are given below.
1) XML separates data from HTML

If we need to display dynamic data in your HTML document, it will take a lot of work to
edit the HTML each time the data changes.

With XML, data can be stored in separate XML files. This way we can focus on using
HTML/CSS for display and layout, and be sure that changes in the underlying data will
not require any changes to the HTML.

With a few lines of JavaScript code, we can read an external XML file and update the
data content of your web page.

2) XML simplifies data sharing

In the real world, computer systems and databases contain data in incompatible formats.

XML data is stored in plain text format. This provides a software- and hardwareindependent way of storing data.

This makes it much easier to create data that can be shared by different applications.

3) XML simplifies data transport

One of the most time-consuming challenges for developers is to exchange data between
incompatible systems over the Internet.

Exchanging data as XML greatly reduces this complexity, since the data can be read by
different incompatible applications.

4) XML simplifies Platform change

Upgrading to new systems (hardware or software platforms), is always time consuming.

Large amounts of data must be converted and incompatible data is often lost.

XML data is stored in text format. This makes it easier to expand or upgrade to new
operating systems, new applications, or new browsers, without losing data.

5) XML increases data availability

Different applications can access your data, not only in HTML pages, but also from XML
data sources.

With XML, your data can be available to all kinds of "reading machines" (Handheld
computers, voice machines, news feeds, etc), and make it more available for blind people,
or people with other disabilities.

6) XML can be used to create new internet languages


A lot of new Internet languages are created with XML.
Here are some examples:
o

XHTML

WSDL for describing available web services

WAP and WML as markup languages for handheld devices

RSS languages for news feeds

RDF and OWL for describing resources and ontology

SMIL for describing multimedia for the web

6. Write notes on XSL and XSL Transformation.

(16)

What is XSL?

XSL is a language for expressing style sheets. An XSL style sheet is, like with CSS, a file
that describes how to display an XML document of a given type.

XSL shares the functionality and is compatible with CSS2 (although it uses a different
syntax).

A transformation language for XML documents: XSLT. Originally intended to perform


complex styling operations, like the generation of tables of contents and indexes, it is
now used as a general purpose XML processing language.
XSLT is thus widely used for purposes other than XSL, like generating HTML web

pages from XML data.

Advanced styling features, expressed by an XML document type which defines a set of
elements called Formatting Objects, and attributes (in part borrowed from CSS2
properties and adding more complex ones.

How Does It Work?


Styling requires a source XML documents, containing the information that the style sheet will
display and the style sheet itself which describes how to display a document of a given type.
The following shows a sample XML file and how it can be transformed and rendered.
The XML file
<scene>
<FX>General Road Building noises.</FX>
<speech speaker="Prosser">
Come off it Mr Dent, you can't win
you know. There's no point in lying
down in the path of progress.
</speech>
<speech speaker="Arthur">
I've gone off the idea of progress.
It's overrated
</speech>
</scene>

This XML file doesn't contain any presentation information, which is contained in the
stylesheet.

Separating the document's content and the document's styling information allows
displaying the same document on different media (like screen, paper, cell phone), and it

also enables users to view the document according to their preferences and abilities, just
by modifying the style sheet.
The Stylesheet
Here are two templates from the stylesheet used to format the XML file. The full
stylesheet (which includes extra information on pagination and margins) is available.
...
<xsl:template match="FX">
<fo:block font-weight="bold">
<xsl:apply-templates/>
</fo:block>
</xsl:template>
<xsl:template match="speech[@speaker='Arthur']">
<fo:block background-color="blue">
<xsl:value-of select="@speaker"/>:
<xsl:apply-templates/>
</fo:block>
</xsl:template>
...

The stylesheet can be used to transform any instance of the DTD it was designed for.

The first rule says that an FX element will be transformed into a block with a bold
font. <xsl:apply-templates/> is a recursive call to the template rules for the contents of the
current element.

The second template applies to all speech elements that have the speaker attribute set
to Arthur, and formats them as blue blocks within which the value speaker attribute is
added before the text.

XSL TRANSFORMATION

XSLT essentials and goals


XSLT is a transformation language for XML. That means, using XSLT, we could
generate any sort of other document from an XML document.
XSLT is a W3C XML language (the usual XML well-formedness criteria apply)

XSLT can translate XML into almost anything , e.g.:

wellformed HTML (closed tags)

any XML, e.g. yours or other XML languages like SVG, X3D

non XML, e.g. RTF (this is a bit more complicated)

In principle, the input data to be transformed is always XML.

With XSLT we then can produce some "enriched" or otherwise transformed XML or
directly some other format that is used to render the contents.

An XSLT program is an XML document. It's top-level skeleton looks like this:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
....
</xsl:stylesheet>
Mandatory "elements"

An XML declaration on top of the file

A stylesheet root tag, including version and namespace attributes (as seen in the example
above):

version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
Association of XML and an XSLT file
XSLT was already implemented in IE 5.5., i.e. in the last millenium...
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="project.xsl" type="text/xsl" ?>
<yourxml>
....
</yourxml>
There exist various so-called XSLT processors. Most programming languages and all well-know
server-side scripting languages like PHP include an XSLT library. XML editors usually include
an XSLT processor.
Below is the complete code for a simple "Hello XSLT" example.
XML file (source)

hello.xml
<?xml version="1.0"?>
<?xml-stylesheet href="hello.xsl" type="text/xsl"?>
<page>
<title>Hello</title>
<content>Here is some content</content>
<comment>Written by DKS.</comment>
</page>
Wanted result document
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REChtml40/strict.dtd">

<html>
<head>
<title>Hello</title>
</head>
<body bgcolor="#ffffff">
<h1 align="center">Hello</h1>
<p align="center"> Here is some content</p>
<hr><i>Written by DKS</i>
</body>
</html>
The XSLT Stylesheet

hello.xslt
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="page">
<html>
<head>
<title> <xsl:value-of select="title"/>
</title>
</head>
<body bgcolor="#ffffff">
<xsl:apply-templates/>
</body>
</html>

</xsl:template>

<xsl:template match="title">
<h1 align="center"> <xsl:apply-templates/> </h1>
</xsl:template>

<xsl:template match="content">
<p align="center"> <xsl:apply-templates/> </p>
</xsl:template>

<xsl:template match="comment">
<hr/> <i><xsl:apply-templates/> </i>
</xsl:template>
</xsl:stylesheet>
7. Explain in details about variables in PHP.
The main way to store information in the middle of a PHP program is by using a variable.
Here are the most important things to know about variables in PHP.

All variables in PHP are denoted with a leading dollar sign ($).

The value of a variable is the value of its most recent assignment.

Variables are assigned with the = operator, with the variable on the left-hand side and the
expression to be evaluated on the right.

Variables can, but do not need, to be declared before assignment.

Variables in PHP do not have intrinsic types - a variable does not know in advance
whether it will be used to store a number or a string of characters.

Variables used before they are assigned have default values.

PHP does a good job of automatically converting types from one to another when
necessary.

PHP variables are Perl-like.

PHP has a total of eight data types which we use to construct our variables

Integers are whole numbers, without a decimal point, like 4195.

Doubles are floating-point numbers, like 3.14159 or 49.1.

Booleans have only two possible values either true or false.

NULL is a special type that only has one value: NULL.

Strings are sequences of characters, like 'PHP supports string operations.'

Arrays are named and indexed collections of other values.

Objects are instances of programmer-defined classes, which can package up both other
kinds of values and functions that are specific to the class.

Resources are special variables that hold references to resources external to PHP (such
as database connections).

The first five are simple types, and the next two (arrays and objects) are compound - the
compound types can package up other arbitrary values of arbitrary type, whereas the simple
types cannot.
Integers
They are whole numbers, without a decimal point, like 4195. They are the simplest type .they
correspond to simple whole numbers, both positive and negative. Integers can be assigned to
variables, or they can be used in expressions, like so
$int_var = 12345;
$another_int = -12345 + 12345;
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format. Decimal
format is the default, octal integers are specified with a leading 0, and hexadecimals have a
leading 0x.
For most common platforms, the largest integer is (2**31 . 1) (or 2,147,483,647), and the
smallest (most negative) integer is . (2**31 . 1) (or .2,147,483,647).
Doubles
They like 3.14159 or 49.1. By default, doubles print with the minimum number of decimal
places needed. For example, the code
<?php

$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
print("$many + $many_2 = $few <br>");
?>
It produces the following browser output
2.28888 + 2.21112 = 4.5
Boolean
They have only two possible values either true or false. PHP provides a couple of constants
especially for use as Booleans: TRUE and FALSE, which can be used like so
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
Interpreting other types as Booleans
Here are the rules for determine the "truth" of any value not already of the Boolean type

If the value is a number, it is false if exactly equal to zero and true otherwise.

If the value is a string, it is false if the string is empty (has zero characters) or is the
string "0", and is true otherwise.

Values of type NULL are always false.

If the value is an array, it is false if it contains no other values, and it is true otherwise.
For an object, containing a value means having a member variable that has been
assigned a value.

Valid resources are true (although some functions that return resources when they are
successful will return FALSE when unsuccessful).

Don't use double as Booleans.

Each of the following variables has the truth value embedded in its name when it is used in a
Boolean context.

$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = "";
NULL
NULL is a special type that only has one value: NULL. To give a variable the NULL value,
simply assign it like this
$my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case insensitive; you
could just as well have typed
$my_var = null;
A variable that has been assigned NULL has the following properties

It evaluates to FALSE in a Boolean context.

It returns FALSE when tested with IsSet() function.

Strings
They are sequences of characters, like "PHP supports string operations". Following are valid
examples of string
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters

Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences.
<?php
$variable = "name";

$literally = 'My $variable will not print!';


print($literally);
print "<br>";
$literally = "My $variable will print!";
print($literally);
?>
This will produce following result
My $variable will not print!\n
My name will print
There are no artificial limits on string length - within the bounds of available memory, you
ought to be able to make arbitrarily long strings.
Strings that are delimited by double quotes (as in "this") are preprocessed in both the following
two ways by PHP

Certain character sequences beginning with backslash (\) are replaced with special
characters

Variable names (starting with $) are replaced with string representations of their values.

The escape-sequence replacements are

\n is replaced by the newline character

\r is replaced by the carriage-return character

\t is replaced by the tab character

\$ is replaced by the dollar sign itself ($)

\" is replaced by a single double-quote (")

\\ is replaced by a single backslash (\)

8. Explain in detail about built in functions in PHP.

Functions are reusable bits of code that you use throughout a project.

They help to better organize your application as well as eliminate the need to copy/paste
repetitive pieces of code.

In an ideal world an application should not have multiple functions doing the same thing.

PHP has a lot of built in functions and while we are not expected to learn all of them at
once there are some useful functions that can help in everyday programming and we will
start from there.

STRING MANIPULATION FUNCTIONS


Some of the most useful PHP functions are string manipulation functions. As the name suggests
they manipulate strings.
FINDING THE LENGTH OF A STRING
The strlen() functions works by passing a string or variable and then returns the total number of
characters including spaces.
<?php
$name = "Matthew ";
echo strlen($name); // 8
?>
RETURN PART OF A STRING
The substr() function is used to return a substring or part of a string. This function has 3
parameters which you can pass along.
Syntax
substr($string, $start,$length);

$string a string of text or a variable containing a string of text. Input must be at least
one character.

$start think of the string as an array starting from [0]. If we wanted to start from the

first character you would enter 0. A negative value will go to the end of the string.
$length (Optional) is the number of characters returned after the start character. If this

value is less than or equal to the start value then it will return false.
<?php
$name = "Matthew ";
echo substr($name, 0, 5); // Matth
echo substr($name, 2); // tthew
echo substr($name, -6, 5); // tthew
?>
CONVERTING STRINGS TO UPPER OR LOWER CASE
Two useful string functions that are simple to use are strtoupper() andstrtolower(), these
functions can convert your strings to all UPPERCASE or all lowercase.
They are very useful for case sensitive operations where you may require all characters to be
lowercase for example.
<?php
$name = "Matthew ";
echo strtoupper($name); // MATTHEW
echo strtolower($name); // matthew
?>
Searching for a needle in a haystack!
Sometimes we need to find a substring within a string and to do that we can use strpos.
Syntax
strpos ($haystack,$needle,$offset)

$haystack this is the string in which you are going to find the $needlestarting from [0].

$needle this is what you are going to search for in the $haystack.

$offset (Optional) search will start from this number of characters counted from the

beginning of the string. Cannot be negative.


<?php
$name = "Matthew ";
echo strpos($name, "M"); // 0
echo strpos($name, "hew"); // 4
echo strpos($name, "m"); // false
?>
Notice that the last example is false. That is because this function is case sensitive and could not
find a match.
We can almost make use of an if statement and some variables to make the strops function more
useful and meaningful.
<?php
$string = "I am learning how to use PHP string functions!";
$search = "JavaScript";
if(strpos($string, $search) === false) {
echo "Sorry we could not find '$search' in '$string'.";
}
?>
This would echo Sorry we could not find JavaScript in I am learning how to use PHP string
functions!.
ARITHMETIC MANIPULATION FUNCTIONS
As well as string manipulation function, PHP also has functions to manipulate numbers.

ROUNDING NUMBERS
One of the most commonly used math function is round(). This function rounds numbers with
decimal points up or down. We can round a number to an integer (whole number) or to a floating
point (decimal numbers).
Syntax
round($val, $precision, $mode)

$val is the value to be rounded.

$precision (optional) number of decimal places to round to.

$mode the type of rounding that occurs and can be one of the following for more
details and examples of modes see PHP docs.

<?php
$number = 3.55776232;
echo
round($number) . "<br/>".

// 4

round($number, 1) . "<br/>". // 3.6


round($number, 3) . "<br/>"; // 3.558
?>
Other math functions for rounding are ceil() and floor() . To round a number to the nearest whole
number, these functions are better suited to that purpose.

ceil() rounds fractions up.

floor() rounds fractions down.

<?php
$number = 3.55776232;
echo
ceil($number) . "<br/>". // 4
floor($number) . "<br/>"; // 3

?>
Both functions require a value and unlike round(), do not have any additional parameters.
GENERATING RANDOM NUMBERS
Another very common math function is rand() which returns a random number between two
numbers.
Syntax
rand($min, $max)
$min (optional) sets the lowest value to be returned. Default is 0
$max (optional) sets the maximum value to be returned. Default returnsgetrandmax().

We will need to specify a $max value in order to return a larger number.

<?php
echo rand(). "\n"; //10884
echo rand(). "\n"; // 621
echo rand(2, 10); //2
?>
ARRAY FUNCTIONS

Array or array() is itself a function that stores multiple values in to a single variable. Aside from
the array() function there are a number of other functions to manipulate arrays, here we will look
at some of the most common ones.
ADDING NEW ELEMENTS
Adding new elements to the end of an array can be achieved by calling thearray_push() function.
Syntax
array_push($array, $value1, $value2)

$array the array in which you are adding new elements to.

$value1 (required) is the first value to push onto the end of the $array.

$value2 (optional) is the second value to push onto the end of the $array.

You can push as many values as you need.


<?php
$games = array();
$array = array_push($games, "Farcry 4");
$array = array_push($games, "Fallout 4");
$array = array_push($games, "Metal Gear");
$array = array_push($games, "Witcher 3");
echo $array; // returns 4
var_dump($games);
?>
However is is better to list each element in a single call like this:
<?php
$games = array(); // target array
$array = array_push($games,
"Farcry 4",
"Fallout 4",
"Metal Gear",
"Witcher 3");
echo $array; // returns 4
var_dump($games);
?>
Both methods result in the same outcome. If you echo or print array_push() it will return the
number of items to be pushed in to the array.
If you var_dump() the target array you you will see something like this.
array(4) {
[0] => string(8) "Farcry 4"

[1] => string(9) "Fallout 4"


[2] => string(10) "Metal Gear"
[3] => string(9) "Witcher 3"
}
SORTING AN ARRAY
As well as adding items to an array we sometimes need to be able to sort them. PHP has a handy
function called funnily enough sort() to do just that.
Syntax
sort($array, $sort_flags)

$array the array in which you wish to sort.

$sort_flags (optional) modifies the sorting behavior. For more information see PHP
docs.

By default the sorting behavior will reorganize an array alphabetically or numerically.


<?php
$games = array(

"Farcry 4",

"Metal Gear",

"Fallout 4",

"Witcher 3",

"Batman");
sort($games); // array to sort
echo join(", ", $games);
//output - Batman, Fallout 4, Farcry 4, Metal Gear, Witcher 3
?>
In order to echo or print out sorted arrays we can use a function called join()which is an alias of
another function called implode().
join(glue, array) or implode(glue, array) functions return a string from the elements of an array
and both have the same syntax.

glue (optional) also known as a separator is what to put between the array elements.

array (required) is the array to join to a string.

If you need to sort and reverse the order of any array then you can use a function called rsort(). It
works exactly the same way as sort() except the output is reversed.
<?php
$games = array(

"Farcry 4",

"Metal Gear",

"Fallout 4",

"Witcher 3",

"Batman");
rsort($games); // array to sort
echo join(", ", $games);
//output - Witcher 3, Metal Gear, Farcry 4, Fallout 4, Batman
?>
9. Explain in detail about Cookies.
Cookies are text files stored on the client computer and they are kept of use tracking purpose.
PHP transparently supports HTTP cookies.
There are three steps involved in identifying returning users

Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.

Browser stores this information on local machine for future use.

When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.

Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly
on a browser). A PHP script that sets a cookie might send headers that look something like this
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html

The Set-Cookie header contains a name value pair, a GMT date, a path and a domain.
The name and value will be URL encoded.

The expires field is an instruction to the browser to "forget" the cookie after the given
time and date.

If the browser is configured to store cookies, it will then keep this information until the
expiry date.

If the user points the browser at any page that matches the path and domain of the
cookie, it will resend the cookie to the server.

The browser's headers might look something like this

GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
A PHP script will then have access to the cookie in the environmental variables $_COOKIE or
$HTTP_COOKIE_VARS[] which holds all cookie names and values. Above cookie can be
accessed using $HTTP_COOKIE_VARS["name"].
SETTING COOKIES WITH PHP
PHP provided setcookie() function to set a cookie. This function requires upto six arguments
and should be called before <html> tag. For each cookie this function has to be called
separately.
setcookie(name, value, expire, path, domain, security);
Here is the detail of all the arguments

Name This sets the name of the cookie and is stored in an environment variable called
HTTP_COOKIE_VARS. This variable is used while accessing cookies.

Value This sets the value of the named variable and is the content that you actually
want to store.

Expiry This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970.
After this time cookie will become inaccessible. If this parameter is not set then cookie
will automatically expire when the Web Browser is closed.

Path This specifies the directories for which the cookie is valid. A single forward slash

character permits the cookie to be valid for all directories.


Domain This can be used to specify the domain name in very large domains and must

contain at least two periods to be valid. All cookies are only valid for the host and
domain which created them.
Security This can be set to 1 to specify that the cookie should only be sent by secure

transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular
HTTP.
Following example will create two cookies name and age these cookies will be expired after
one hour.
<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html>
<head>
<title>Setting Cookies with PHP</title>
</head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>
ACCESSING COOKIES WITH PHP
PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or
$HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above
example.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */

echo $HTTP_COOKIE_VARS["name"]. "<br />";


echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"] . "<br />";
?>
</body>
</html>
We can use isset() function to check if a cookie is set or not.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>
</body>
</html>
DELETING COOKIE WITH PHP
Officially, to delete a cookie you should call setcookie() with the name argument only but this
does not always work well, however, and should not be relied on.
It is safest to set the cookie with a date that has already expired
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>
<body>

<?php echo "Deleted Cookies" ?>


</body>
</html>
10. Explain in detail about Regular Expressions
Regular expressions are nothing more than a sequence or pattern of characters itself. They
provide the foundation for pattern-matching functionality.
Using regular expression you can search a particular string inside a another string, we can
replace one string by another string and you can split a string into many chunks.
PHP offers functions specific to two sets of regular expression functions, each corresponding to
a certain type of regular expression. We can use any of them based on your comfort.

POSIX Regular Expressions

PERL Style Regular Expressions

POSIX Regular Expressions

The structure of a POSIX regular expression is not dissimilar to that of a typical


arithmetic expression: various elements (operators) are combined to form more complex
expressions.

The simplest regular expression is one that matches a single character, such as g, inside
strings such as g, haggle, or bag.

Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions. They are
used to find a range of characters.
Sr.No
1

Expression & Description


[0-9]
It matches any decimal digit from 0 through 9.

[a-z]
It matches any character from lower-case a through lowercase z.

[A-Z]

It matches any character from uppercase A through uppercase Z.


4

[a-Z]
It matches any character from lowercase a through uppercase Z.

The ranges shown above are general; you could also use the range [0-3] to match any decimal
digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging
from b through v.
Quantifiers
The frequency or position of bracketed character sequences and single characters can be
denoted by a special character. Each special character having a specific connotation. The +, *, ?,
{int. range}, and $ flags all follow a character sequence.
Sr.No Expression & Description
1

p+
It matches any string containing at least one p.

p*
It matches any string containing zero or more p's.

p?
It matches any string containing zero or more p's. This is just an alternative way to use
p*.

p{N}
It matches any string containing a sequence of N p's

p{2,3}
It matches any string containing a sequence of two or three p's.

p{2, }
It matches any string containing a sequence of at least two p's.

p$

It matches any string with p at the end of it.


8

^p
It matches any string with p at the beginning of it.

Examples

Following examples will clear our concepts about matching characters.


Sr.No
1

Expression & Description


[^a-zA-Z]
It matches any string not containing any of the characters ranging from a through z and A
through Z.

p.p
It matches any string containing p, followed by any character, in turn followed by another p.

^.{2}$
It matches any string containing exactly two characters.

<b>(.*)</b>
It matches any string enclosed within <b> and </b>.

p(hp)*
It matches any string containing a p followed by zero or more instances of the sequence php.

Predefined Character Ranges


For our programming convenience several predefined character ranges, also known as character
classes, are available. Character classes specify an entire range of characters, for example, the
alphabet or an integer set
Sr.No
1

Expression & Description


[[:alpha:]]

It matches any string containing alphabetic characters aA through zZ.


2

[[:digit:]]
It matches any string containing numerical digits 0 through 9.

[[:alnum:]]
It matches any string containing alphanumeric characters aA through zZ and 0 through 9.

[[:space:]]
It matches any string containing a space.

PHP's Regexp POSIX Functions


PHP currently offers seven functions for searching strings using POSIX-style regular
expressions
Sr.No

Function & Description

ereg()
The ereg() function searches a string specified by string for a string specified by pattern,
returning true if the pattern is found, and false otherwise.

ereg_replace()
The ereg_replace() function searches for string specified by pattern and replaces pattern with
replacement if found.

eregi()
The eregi() function searches throughout a string specified by pattern for a string specified by
string. The search is not case sensitive.

eregi_replace()
The eregi_replace() function operates exactly like ereg_replace(), except that the search for
pattern in string is not case sensitive.

split()
The split() function will divide a string into various elements, the boundaries of each element
based on the occurrence of pattern in string.

spliti()
The spliti() function operates exactly in the same manner as its sibling split(), except that it is
not case sensitive.

sql_regcase()
The sql_regcase() function can be thought of as a utility function, converting each character
in the input parameter string into a bracketed expression containing two characters.

PERL Style Regular Expressions

Perl-style regular expressions are similar to their POSIX counterparts.

The POSIX syntax can be used almost interchangeably with the Perl-style regular
expression functions.

Lets give explanation for few concepts being used in PERL regular expressions
Meta characters
A meta character is simply an alphabetical character preceded by a backslash that acts to give
the combination a special meaning.
For instance, we can search for large money sums using the '\d' meta character: /([\d]+)000/,
Here \d will search for any string of numerical character.
Following is the list of meta characters which can be used in PERL Style Regular Expressions.
Character

Description

a single character

\s

a whitespace character (space, tab, newline)

\S

non-whitespace character

\d

a digit (0-9)

\D

a non-digit

\w

a word character (a-z, A-Z, 0-9, _)

\W

a non-word character

[aeiou]

matches a single character in the given set

[^aeiou]

matches a single character outside the given set

(foo|bar|baz) matches any of the alternatives specified


Modifiers
Several modifiers are available that can make your work with regexps much easier, like case
sensitivity, searching in multiple lines etc.

ModifierDescription
i

Makes the match case insensitive

Specifies that if the string has newline or carriage


return characters, the ^ and $ operators will now
match against a newline boundary, instead of a
string boundary

Evaluates the expression only once

Allows use of . to match a newline character

Allows you to use white space in the expression for clarity

Globally finds all matches

cg

Allows a search to continue even after a global match fails

PHP's Regexp PERL Compatible Functions


PHP offers following functions for searching strings using Perl-compatible regular expressions

Sr.No

Function & Description

preg_match()
The preg_match() function searches string for pattern, returning true if pattern exists, and
false otherwise.

preg_match_all()
The preg_match_all() function matches all occurrences of pattern in string.

preg_replace()
The preg_replace() function operates just like ereg_replace(), except that regular expressions
can be used in the pattern and replacement input parameters.

preg_split()
The preg_split() function operates exactly like split(), except that regular expressions are
accepted as input parameters for pattern.

preg_grep()
The preg_grep() function searches all elements of input_array, returning all elements
matching the regexp pattern.

preg_ quote()

Quote regular expression characters

S-ar putea să vă placă și