WT
WT
WT
WEB TECHNOLOGIES - I
For T.Y.B.Sc. Computer Science : Semester – V
[Course Code CS 353 : Credits - 2]
CBCS Pattern
As Per New Syllabus, Effective from June 2021
Dr. A. B. Nimbalkar
M.C.S., M.Phil. D.C.L, Ph.D. (Comp. Sci.)
Asst. Professor, Annasaheb Magar Mahavidyalaya
Hadapsar, Pune
Price ` 360.00
N5863
WEB TECHNOLOGIES - I ISBN 978-93-5451-185-1
Second Edition : August 2022
© : Author
The text of this publication, or any part thereof, should not be reproduced or transmitted in any form or stored in any
computer storage system or device for distribution including photocopy, recording, taping or information retrieval system or
reproduced on any disc, tape, perforated media or other information storage device etc., without the written permission of Author
with whom the rights are reserved. Breach of this condition is liable for legal action.
Every effort has been made to avoid errors or omissions in this publication. In spite of this, errors may have crept in. Any
mistake, error or discrepancy so noted and shall be brought to our notice shall be taken care of in the next edition. It is notified
that neither the publisher nor the author or seller shall be responsible for any damage or loss of action to any one, of any kind, in
any manner, there from. The reader must cross check all the facts and contents with original Government notification or
publications.
Published By : Polyplate Printed By :
NIRALI PRAKASHAN YOGIRAJ PRINTERS AND BINDERS
Abhyudaya Pragati, 1312, Shivaji Nagar, Survey No. 10/1A, Ghule Industrial Estate
Off J.M. Road, Pune – 411005 Nanded Gaon Road
Tel - (020) 25512336/37/39 Nanded, Pune - 411041
Email : [email protected]
DISTRIBUTION CENTRES
PUNE
Nirali Prakashan Nirali Prakashan
(For orders outside Pune) (For orders within Pune)
S. No. 28/27, Dhayari Narhe Road, Near Asian College 119, Budhwar Peth, Jogeshwari Mandir Lane
Pune 411041, Maharashtra Pune 411002, Maharashtra
Tel : (020) 24690204; Mobile : 9657703143 Tel : (020) 2445 2044; Mobile : 9657703145
Email : [email protected] Email : [email protected]
MUMBAI
Nirali Prakashan
Rasdhara Co-op. Hsg. Society Ltd., 'D' Wing Ground Floor, 385 S.V.P. Road
Girgaum, Mumbai 400004, Maharashtra
Mobile : 7045821020, Tel : (022) 2385 6339 / 2386 9976
Email : [email protected]
DISTRIBUTION BRANCHES
DELHI BENGALURU NAGPUR
Nirali Prakashan Nirali Prakashan Nirali Prakashan
Room No. 2 Ground Floor Maitri Ground Floor, Jaya Apartments, Above Maratha Mandir, Shop No. 3,
4575/15 Omkar Tower, Agarwal Road No. 99, 6th Cross, 6th Main, First Floor, Rani Jhanshi Square,
Darya Ganj, New Delhi 110002 Malleswaram, Bengaluru 560003 Sitabuldi Nagpur 440012 (MAH)
Mobile : 9555778814/9818561840 Karnataka; Mob : 9686821074 Tel : (0712) 254 7129
Email : [email protected] Email : [email protected] Email : [email protected]
[email protected] | www.pragationline.com
Also find us on www.facebook.com/niralibooks
Preface …
I take an opportunity to present this Text Book on "Web Technologies - I" to the
students of Third Year B.Sc. (Computer Science) Semester-V as per the New Syllabus,
June 2021.
The book has its own unique features. It brings out the subject in a very simple and lucid
manner for easy and comprehensive understanding of the basic concepts. The book covers
theory of Introduction to HTML, HTTP and PHP, Function and String, Arrays, Files and
Database Handling and Handling Email with PHP.
A special word of thank to Shri. Dineshbhai Furia, and Mr. Jignesh Furia for
showing full faith in me to write this text book. I also thank to Mr. Amar Salunkhe and
Mr. Akbar Shaikh of M/s Nirali Prakashan for their excellent co-operation.
I also thank Ms. Chaitali Takle, Mr. Ravindra Walodare, Mr. Sachin Shinde, Mr. Ashok
Bodke, Mr. Moshin Sayyed and Mr. Nitin Thorat.
Although every care has been taken to check mistakes and misprints, any errors,
omission and suggestions from teachers and students for the improvement of this text book
shall be most welcome.
Author
Syllabus …
Program 2: A program to check given number is odd or even input is taken from user.
<html>
<body>
<form method="post">
Enter a number:
<input type="number" name="number">
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
if($_POST)
{
$number = $_POST['number'];
A.1
Web Technologies - I Additional Programs
Output:
A.3
Web Technologies - I Additional Programs
Program 5: Program shows a form through which you can calculate factorial of number
given by user.
<html>
<head>
<title>Factorial Program using loop in PHP</title>
</head>
<body>
<form method="post">
Enter the Number:<br>
<input type="number" name="number" id="number">
<input type="submit" name="submit" value="Submit" />
</form>
<?php
if($_POST)
{
$fact = 1;
//getting value from input text box 'number'
$number = $_POST['number'];
echo "Factorial of $number:<br><br>";
//start loop
for($i = 1; $i <= $number; $i++)
{
$fact = $fact * $i;
}
echo $fact . "<br>";
}
?>
</body>
</html>
Output:
<form method="post">
Enter the Number:<br>
<input type="number" name="number" id="number">
<input type="submit" name="submit" value="Submit" />
</form>
<?php
function fact ($n)
{
if($n <= 1)
{
return 1;
}
else
{
return $n * fact($n - 1);
}
}
$number = $_POST['number'];
echo "<br><br>";
echo "Factorial of $number is " .fact($number);
?>
</body>
</html>
Output:
if($num==$total)
{
echo "Given no is an Armstrong number";
}
else
{
echo "Given no is Not an armstrong number";
}
?>
Output:
Program 8: Program to check whether the enter number is Palindrome or not (input from
the user).
<html>
<head>
<title>Factorial Program using loop in PHP</title>
</head>
<body>
<form method="post">
Enter the Number:<br>
<input type="number" name="number" id="number">
<input type="submit" name="submit" value="Submit" />
</form>
<?php
$input = $_POST['number'];
function palindrome($n)
{
$number = $n;
$sum = 0;
while(floor($number))
{
$rem = $number % 10;
$sum = $sum * 10 + $rem;
$number = $number/10;
}
return $sum;
}
$num = palindrome($input);
A.6
Web Technologies - I Additional Programs
if($input==$num)
{
echo "$input is a Palindrome number";
} else
{
echo "$input is not a Palindrome";
}
?>
</body>
</html>
Output:
Output:
{
echo $k." ";
$k++;
}
echo "<br>";
}
?>
Output:
Program 13: Program to count the number of words in the string with string function.
<?php
$my_str = 'PHP is use for WebProgramming';
echo str_word_count($my_str);
?>
Output:
5
Program 14: Program using nested for loop that creates a chess board as shown below.
Use table width="270px" and take 30px as cell height and width.
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h3>Chess Board using Nested For Loop</h3>
<table width="270px" cellspacing="0px" cellpadding="0px"
border="1px">
<!-- cell 270px wide (8 columns x 60px) -->
<?php
A.9
Web Technologies - I Additional Programs
for($row=1;$row<=8;$row++)
{
echo "<tr>";
for($col=1;$col<=8;$col++)
{
$total=$row+$col;
if($total%2==0)
{
echo "<td height=30px width=30px bgcolor= #FFFFFF></td>";
}
else
{
echo "<td height=30px width=30px bgcolor=#000000></td>";
}
}
echo "</tr>";
}
?>
</table>
</body>
</html>
Program 15: Program to develop a web page for the form validation.
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
}else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
}else {
$email = test_input($_POST["email"]);
A.10
Web Technologies - I Additional Programs
if (empty($_POST["website"])) {
$website = "";
}else {
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
}else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
}else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Absolute classes registration</h2>
<p><span class = "error">* required field.</span></p>
<form method = "post" action = "<?php
echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>Name:</td>
<td><input type = "text" name = "name">
<span class = "error">* <?php echo $nameErr;?></span>
</td>
</tr>
A.11
Web Technologies - I Additional Programs
<tr>
<td>E-mail: </td>
<td><input type = "text" name = "email">
<span class = "error">* <?php echo $emailErr;?></span>
</td>
</tr>
<tr>
<td>Time:</td>
<td> <input type = "text" name = "website">
<span class = "error"><?php echo $websiteErr;?></span>
</td>
</tr>
<tr>
<td>Classes:</td>
<td> <textarea name = "comment" rows = "5" cols =
"40"></textarea></td>
</tr>
<tr>
<td>Gender:</td>
<td>
<input type = "radio" name = "gender"
value = "female">Female
<input type = "radio" name = "gender"
value = "male">Male
<span class = "error">* <?php echo $genderErr;?></span>
</td>
</tr>
<td>
<input type = "submit" name = "submit" value = "Submit">
</td>
</table>
</form>
<?php
echo "<h2>Your given values are as:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
A.12
Web Technologies - I Additional Programs
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
Output:
A.13
Web Technologies - I Additional Programs
}else {
echo "Message could not be sent...";
}
?>
</body>
</html>
Output:
Message sent successfully...
Program 17: Program to check that emails are valid.
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if(!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if(empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
A.14
Web Technologies - I Additional Programs
A.15
Web Technologies - I Additional Programs
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
Output:
A.16
CHAPTER
1
Introduction to HTML,
HTTP and PHP
Objectives…
To understand Basic Concepts in HTML
To learn Basics of HTTP
To study Basic Concepts of PHP
To learn Language Basics and Lexical Structure of PHP
1.0 INTRODUCTION
• Web technologies refer to techniques and tools that are used to produce fully-featured
Websites and Web applications.
• A Website is a collection of web pages. A document on the Web is called a Web page
and is identified by a unique address called the Uniform Resource Locator (URL).
• A Web application (Web app) is an application program that is stored on a Web server
and delivered over the Internet through a Browser.
• The two types of Web pages are static web page and dynamic web page. The content
(data and information) in static web pages does not get changed until someone
changed it manually while the content in dynamic web pages changes dynamically
(runtime).
• The two distinct parts of a website are the frontend (refers to all those parts of a
website that a user can see on their screen and interact with) and the backend
(involves the hidden mechanisms where functions, methods, and data manipulation
happens).
• The World Wide Web (WWW) consists of files, called pages or web pages, which
contain information and links to resources throughout the Internet.
• In simple word, all publicly accessible websites collectively constitute the World Wide
Web.
• A web page is an electronic document written in a computer language called HTML
(HyperText Markup Language). HTML is the standard markup language for creating
Web pages and Web applications.
• Web design is the process of creating websites. Website is a collection of related web
pages that may contain text, images, audio and video.
1.1
Web Technologies - I Introduction to HTML, HTTP and PHP
• A web browser or a browser (client) is application software for accessing the World
Wide Web. Some popular web browsers are Opera, Mozilla Firefox, Google Chrome,
and Safari.
• When a user requests a web page from a particular website, the web browser
retrieves the necessary content from a Web server (server) and then displays the page
on the user's device like desktops, laptops, tablets, and smart phones.
• Web development, or web programming, refers to the design of software applications
for a Web site. Web publishing or Online publishing, is the process of publishing
content on the Internet.
• Web technology is a collective name for technologies primarily for the World Wide
Web (WWW) or Web. These technologies includes Markup Language (HTML),
Programming languages (JavaScript, Python, PHP etc.), Frameworks (Node.js,
Angular.js, .NET, Drupal etc.), Databases (MongoDB, PostgreSQL, MySQL etc.) CSS
(Cascading Style Sheet), Libraries (JQuery), Data formats (XML (Extensible Markup
Language), JSON (JavaScript Object Notation)) and so on.
• In this chapter we will study HTML, CSS, HTTP and PHP technologies related to web
technologies.
• An HTML file is a text file with extension .htm or .html. To create the HTML source
document, we need an HTML Editor. An HTML editor is a program for editing HTML,
the markup of a web page.
• An HTML editor is a computer program used for creating and editing Web pages.
There are two main varieties of HTML editors i.e. text and WYSIWYG (What You See Is
What You Get) editors.
• A text editor is a type of program used for editing plain text files. A text-based HTML
editor includes Notepad on Windows, GNU Emacs on UNIX/Linux, or SimpleText on
the Macintosh.
• The WYSIWYG editors provide an editing interface which resembles how the page will
be displayed in a web browser like Adobe Dreamweaver, KomodoIDE, EditPlus etc.
• Other professional text editors for HTML include Notepad++, Sublime Text, Vim, Atom,
and Visual Studio Code and so on.
HTML Page Structure:
• Fig. 1.1 shows page structure of HTML. A web page is also known as HTML page or
HTML document.
• A basic HTML page starts with the Document Type Declaration also called DOCTYPE
declaration before the <html> tag. The <!DOCTYPE> declaration represents the
document type.
• The Document Type Declaration is not an HTML tag; it is an instruction to the web
browser about what version of HTML the page is written in.
• The current version of HTML is HTML5 and it makes use of the only one declaration
<!DOCTYPE html>.
<!DOCTYPE>
<html>
<head>
</head>
<body>
</body>
</html>
• The entire HTML document is contained within an opening <html> tag and a closing
</html> tag.
• Within the <html> tag, the document is divided into a head and a body. The <head> tag
contains descriptive information about the document itself, such as its title, the style
sheet(s) it uses and so on.
• The <body> tag contains the entire information or content about the web page and its
behavior. It also contains the information that we want to display on a Web page.
Example for creating an html document:
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<body>
<h1>Nirali Prakashan</h1>
<p>Textbook Publication Firm.</p>
</body>
</head>
</html>
Output:
element
Fig. 1.2: Element in HTML
• Fig. 1.3 shows an example of HTML element. In this example, the HTML element is a
paragraph <p> opening and closing tags with “My paragraph...” content that will
display on the web page.
1.4
Web Technologies - I Introduction to HTML, HTTP and PHP
HTML element
2. Singular Tags: The singular tag is also known as a stand-alone tag or empty tag.
The stand-alone tag does not have companion tag or closing tag. For example <br>
tag will insert a line break. This tag does not require any companion tag or a
closing tag.
Basic HTML Tags:
• HTML contains following basic tags:
1. <html> Tag: The <html> tag represents the root of an HTML document. The <html>
tag is the container that contains all other HTML elements (except for the
<!DOCTYPE> declaration which is located before the opening HTML tag). The
<html> tag tells the browser that this is an HTML document.
Syntax: <html>…………</html>
Attribute Description
1. Manifest This attribute specifies the address of the document's
application cache manifest and the value must be a valid URL.
2. <title> Tag: The <title> tag is used for declaring the title, or name, of the HTML
document. The title is usually displayed in the browser's title bar (at the top) or the
<title> tag defines a title in the browser toolbar. It is also displayed in browser
bookmarks and search results.
Syntax: <title>…………</title>
3. <head> Tag: The <head> tag is a container for all the head elements and must
include a title for the document, and can include scripts, styles, meta information,
and so on.
Syntax: <head>…………</head>
4. <body> Tag: The <body> tag defines the document's body. The body tag is placed
between the </head> and the </html> tags. The <body> tags contains all the
contents of an HTML document, such as text, hyperlinks, images, tables, lists, etc.
Syntax: <body>………</body>
Attributes of <body> Tag:
Attribute Value Description
1. alink color This attribute specifies the color of an active link
in a document.
2. background URL This attribute specifies a background image for a
document.
3. bgcolor color This attribute specifies the background color of a
document.
contd. …
1.6
Web Technologies - I Introduction to HTML, HTTP and PHP
1.7
Web Technologies - I Introduction to HTML, HTTP and PHP
5. <strong> The <strong> tag is used for indicating strong importance for its
contents. The strong tag surrounds the emphasized word/phrase.
Syntax: <strong>……</strong>
6. <sub> The <sub> tag defines subscript text. Subscript text appears half a
character below the baseline. Subscript text can be used for chemical
formulas, like H2O.
Syntax: <sub>……</sub>
7. <sup> The <sup> tag defines superscript text. Superscript text appears half a
5
character above the baseline like 10 .
Syntax: <sup>……</sup>
8. <ins> The <ins> tag defines a text that has been inserted into a document.
Syntax: <ins>……</ins>
9. <del> The <del> tag defines text that has been deleted from a document.
Syntax: <del>……</del>
10. <u> The <u> tag usually results in the text being underlined. Anything that
appears in a <u>...</u> element is displayed with underline,
Syntax: <u>……</u>
11. <strike> Anything that appears in a <strike> tag is displayed with strikethrough,
which is a thin line through the text like, strikethrough.
Syntax: <strike>……</strike>
12. <big> The content of the <big> element is displayed one font size larger than
the rest of the text surrounding it.
Syntax: <big>……</big>
Example for text formatting tags:
<!DOCTYPE html>
<html>
<head>
<title> Example of HTML Text Formatting Tags </title>
</head>
<body>
<p>Nirali Prakashan</p>
<font size="4">Wecome to <b>Nirali Prakashan.</b> <br/></font>
<font size="2"><i>Nirali Prakashan</i> is a textbook publication
firm.<br/></font>
<font face="verdana" color="black">Nirali Prakashan <u>publised
more than 3500 book titles.</u></font>
</body>
</html>
Output:
1.8
Web Technologies - I Introduction to HTML, HTTP and PHP
3. <p> Tag: HTML documents are divided into paragraphs. The HTML <p> tag is used
for defining a paragraph.
Syntax: <p>…………</p>
Attributes for Paragraph Tag:
4. <br> Tag: The HTML <br> tag is used for specifying a line break. The <br> tag is an
empty tag. In other words, it has no end tag. Syntax: <br/>
5. <center> Tag: The <center> tag is used to center-align text.
1.9
Web Technologies - I Introduction to HTML, HTTP and PHP
6. Non breaking Spaces: Suppose we were to use the phrase "14 Angry Men." Here
we would not want a browser to split the "14" and "Angry" across two lines. A good
example of this technique appears in the movie "14 Angry Men." In cases where
we do not want the client browser to break text, we should use a non-breaking
space entity ( ) instead of a normal space. For example, when coding the "14
Angry Men" paragraph, we would use something similar to the following code:
<p>A good example of this technique appears in the movie
"14 Angry Men."</p>
7. <div> Tag: The <div> tag defines a division or a section in an HTML document. The
<div> tag is used to group block-elements to format them with CSS.
Syntax: <div>…………</div>
Attribute Value Description
1. align left Align attribute specifies the alignment of the content inside
right a <div> element
center
justify
Example for <div> tag:
<!DOCTYPE html>
<html>
<head>
<title> Example of HTML div Tag </title>
</head>
<body>
<div style="background-color:orange;text-align:center">
<p>Nirali Prakashan</p>
</div>
<div style="background-color:pink;text-align:center">
<p>Pragati Group</p>
</div>
</body>
</html>
Output:
8. <span> Tag: The <span> tag is used for grouping and applying styles to inline
elements.
Syntax: <span>…………</span>
1.10
Web Technologies - I Introduction to HTML, HTTP and PHP
9. <hr> Tag: The HTML <hr> tag is used for specifying a horizontal rule in an HTML
document. The <hr> tag is used for creating a horizontal line which separate
content (or define a change) in an HTML page.
Syntax: <hr/>
Attributes for <hr> Tag:
Attribute Value Description
1. align left This attribute specifies the alignment of a <hr>
center element.
right
2. noshade noshade This attribute specifies that a <hr> element should
render in one solid color (no-shaded), instead of a
shaded color.
3. size pixels This attribute specifies the height of a <hr> element.
4. width pixels % This attribute specifies the width of a <hr> element.
1.11
Web Technologies - I Introduction to HTML, HTTP and PHP
10. <font> Tag: Fonts play very important role in making a website more user friendly
and increasing content readability. The <font> tag specifies the font face, font size,
and font color of text.
Syntax: <font>…………</font>
Attributes for <font> tag:
Attribute Value Description
1. color rgb(x,x,x) This attribute specifies the color of text.
#xxxxxx
colorname
2. face font_family This attribute specifies the font of text.
3. size number This attribute specifies the size of text.
Example for <font> tag:
<!DOCTYPE html>
<html>
<head>
<title> Example for HTML font Tag </title>
</head>
<body>
<p><h2>Nirali Prakashan</h2></p>
<font size="4" color="red">Wecome to Nirali Prakashan. <br/></font>
<font size="2" color="blue">Nirali Prakashan is a textbook
publication firm.<br/></font>
<font face="verdana" color="black">Nirali Prakashan publised more
than 3500 book titles.</font>
</body>
</html>
1.12
Web Technologies - I Introduction to HTML, HTTP and PHP
Output:
1.13
Web Technologies - I Introduction to HTML, HTTP and PHP
Concept of URL:
• Each and every web page has a unique address, called a Uniform Resource Locator
(URL) that identifies its location on the Internet.
Parts of URL:
• URL has several parts i.e., the protocol, the domain name, the directory or folder, and
the filename and its extension. Below is an example of URL and the corresponding
parts.
https://www.niraliprakashan.com/html/index.htm
2. Relative: A relative URL indicates where the resource is in relation to the current
page. Given URL is added with the <base> element to form a complete URL. For
example, /html/html_text_links.htm. There are two types of relative URLs:
(i) In Document Relative URLs, the document address is given in relation with
the originating document.
(ii) In Server Relative URLs, the document address is given in relation with the
server on which the document is present.
Lists in HTML:
• In HTML, we can list out the items, subjects or menu in the form of a list. HTML gives
us three different types of lists as explained below:
1. Unordered Lists: An unordered list is a collection of related items that have no
special order or sequence. Unordered list is created by using <ul> tag. Each item in
the list is marked with a bullet. The bullet itself comes in three flavors: squares,
discs, and circles.
2. Ordered Lists: The Ordered list is created by using <ol> tag. Each item in the list is
marked with a number. The numbering starts at one and is incremented by one
for each successive ordered list element tagged with <li> tag.
3. Definition Lists: The definition list is the ideal way to present a glossary, list of
terms, or other name/value list. Definition List makes use of <dl>, <dt> and
<dd>tags.
• Metadata is data (information) about data. Meta elements are typically used to specify
page description, keywords, author of the document, last modified and other
metadata.
• The <meta> tag is used for declaring metadata for the HTML document. The <meta>
tag always goes inside the head element.
Syntax: <meta name = string content = string>
1. <li> List Tag: The <li> tag defines a list item. The <li> tag is used in ordered lists
(<ol>), unordered lists (<ul>), and in menu lists (<menu>).
Syntax: <li>………</li>
Attributes Value Description
1. type 1 This attribute specifies which kind of bullet point
A will be used.
a
I
i
disc
square
circle
2. value number This attribute specifies the value of a list item.
1.16
Web Technologies - I Introduction to HTML, HTTP and PHP
2. <ul> Unordered List Tag: An unordered list starts with the <ul> tag. Each list item
starts with the <li> tag. The <ul> tag defines an unordered (bulleted) list.
Syntax: <ul>………</ul>
Attributes Value Description
1. compact compact This attribute specifies that the list should render
smaller than normal.
2. type disc This attribute specifies the kind of marker to use in
square the list.
circle
Example for <ul> tag:
<!DOCTYPE html>
<html>
<head>
<h3>An Unordered List Example</h3>
<body>
<h4>Disc bullets list:</h4>
<ul type="disc">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ul>
<h4>Circle bullets list:</h4>
<ul type="circle">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ul>
<h4>Square bullets list:</h4>
<ul type="square">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ul>
</body>
</head>
</html>
1.17
Web Technologies - I Introduction to HTML, HTTP and PHP
Output:
• Nested List: One list inside another list is known as nesting of list or nested list. We
can nested unordered list as follows:
<!DOCTYPE html>
<html>
<body>
<h4>A nested List:</h4>
<ul>
<li>Coffee</li>
<li>Tea
<ul>
<li>Black tea</li>
<li>Green tea
<ul>
<li>China</li>
<li>Africa</li>
</ul>
</li>
</ul>
</li>
<li>Milk</li>
</ul>
</body>
</html>
1.18
Web Technologies - I Introduction to HTML, HTTP and PHP
Output:
3. <ol> Ordered List Tag: An ordered list starts with the <ol> tag. Each list item starts
with the <li> tag. Each item in the list is marked with a number.
Syntax: <ol>…………</ol>
Attributes Value Description
1. compact compact This attribute specifies that the list should render
smaller than normal.
2. reversed reversed This attribute specifies that the list order should be
descending like 9,8,7...
3. start number This attribute specifies the start value of an
ordered list.
4. type 1 This attribute specifies the kind of marker to use in
A the list.
a
I
i
1.19
Web Technologies - I Introduction to HTML, HTTP and PHP
<h4>Letters list:</h4>
<ol type="A">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
</ol>
<h4>Lowercase letters list:</h4>
<ol type="a">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
</ol>
<h4>Roman numbers list:</h4>
<ol type="I">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
</ol>
<h4>Lowercase Roman numbers list:</h4>
<ol type="i">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
</ol>
</body>
</head>
</html>
Output:
1.20
Web Technologies - I Introduction to HTML, HTTP and PHP
4. Definition Lists: A definition list is a list of items, with a description of each item.
The <dl> tag defines a definition list. The <dl> tag is used to provide a list of items
with associated definitions.
Syntax: <dl>…………</dl>
Definition list makes use of following two tags:
(i) <dt>: The <dt> tag is used inside dl. It marks up a term whose definition is
provided by the next dd. The dt tag may only contain text-level markup.
(ii) <dd>: The <dd> tag is used inside a dl definition list to provide the definition of
the text in the dt tag. It may contain block elements but also plain text and
markup.
Example for definition list:
<!DOCTYPE html>
<html>
<body>
<h4>A Definition List:</h4>
<dl>
<dt>Coffee</dt>
<dd>Black hot drink</dd>
<dt>Milk</dt>
<dd>White cold drink</dd>
</dl>
</body>
</html>
Output:
Images in HTML:
• It is true that one single image is worth than thousands of words. So as a web
developer we should have clear understanding on how to use images in the web
pages.
• Images are used in many ways to enhance the look of a Web page and make it more
interesting and colorful.
• There are basically following two types of graphic programs for images:
1. Bitmap (or Raster) images are stored as a series of tiny dots called pixels. Each
pixel is actually a very small square that is assigned a color, and then arranged in a
pattern to form the image. Bitmap graphics can be edited by erasing or changing
the color of individual pixels using a program such as Adobe Photoshop.
1.21
Web Technologies - I Introduction to HTML, HTTP and PHP
2. Vector images are not based on pixel patterns, but instead use mathematical
formulas to draw lines and curves that can be combined to create an image from
geometric objects such as circles and polygons. Vector images are edited by
manipulating the lines and curves that make up the image using a program such
as Adobe Illustrator.
1.22
Web Technologies - I Introduction to HTML, HTTP and PHP
• We will insert any image in our web page by using <img> tag.
Syntax:
<img src="image URL" attr_name="attr_value"... more attributes />
Attributes Value Description
1. alt text This attribute specifies an alternate text for an
image.
2. src URL This attribute specifies the URL of an image.
3. align top This attribute specifies the alignment of an
bottom image according to surrounding elements.
middle
left
right
4. border pixels This attribute specifies the width of the
border around an image.
5. crossoriginNew anonymous This attribute allow images from third-party
use- sites that allow cross-origin access to be used
credentials with canvas.
6. height pixels This attribute specifies the height of an image.
7. hspace pixels This attribute specifies the whitespace on left
and right side of an image.
8. ismap ismap This attribute specifies an image as a server-
side image-map.
9. longdesc URL This attribute specifies the URL to a document
that contains a long description of an image.
10. src URL This attribute specifies the URL of an image.
11. usemap #mapname This attribute specifies an image as a client-
side image-map.
12. vspace pixels This attribute specifies the whitespace on top
and bottom of an image.
13. width pixels This attribute specifies the width of an image.
Example for image:
<!DOCTYPE html>
<html>
<head>
<meta name="GENERATOR" content="MICROSOFT FRONTPAGE 4.0">
<meta name="PROGID" content="FRONTPAGE.EDITOR.DOCUMENT">
<title>IMAGE SPACING</title>
</head>
<body>
<p>
1.23
Web Technologies - I Introduction to HTML, HTTP and PHP
Image as a Link:
• Anything can be a link i.e., text or images. To make an image into a link we simply put
the image tag inside the tag for a link. The tag would look like this:
<a href="http://www.anycartoonsite.com"><img src="z:\book\mikey.jpg"></a>
1.24
Web Technologies - I Introduction to HTML, HTTP and PHP
<body>
IMAGE LINK EXAMPLE
<p>
<a href = "HTTP://WWW.YAHOO.COM" ><img src = "http://images4.wikia.
nocookie.net/__cb20120710211159/cartoons/images/8/80/Mickey_Mouse.jpg"
border = "0" width ="90" height = "80"> </a>
</p>
</body>
</html>
Output:
Frames in HTML:
• With frames, we can display more than one HTML document in the same browser
window. Each HTML document is called a frame, and each frame is independent of the
others. A collection of frames in the browser window is known as a frameset.
• The frameset, frame, and noframes tags are supported in previous versions of HTML
such as HTML 4.01 and not supported in HTML5.
1.25
Web Technologies - I Introduction to HTML, HTTP and PHP
• The <iframe> tag specifies an inline frame. An inline frame is used to embed another
document within the current HTML document.
• The <iframe> tag defines a rectangular region within the document in which the
browser displays a separate document, including scrollbars and borders.
• HTML5 has added some new attributes, and several HTML 4.01 attributes are removed
from HTML5.
Syntax: <iframe> … </iframe>
Attributes for <iframe> tag:
Attributes Value Description
1. height pixels This attribute specifies the height of an
<iframe>.
2. name text This attribute specifies the name of an
<iframe>.
3. sandbox allow-forms This attribute enables an extra set of
allow-pointer-lock restrictions for the content in an <iframe>.
allow-popups
allow-same-origin
allow-scripts
allow-top-navigation
4. src URL This attribute specifies the address of the
document to embed in the <iframe>.
5. srcdoc HTML_code This attribute specifies the HTML content of
the page to show in the <iframe>
6. width pixels This attribute specifies the width of an
<iframe>.
1.26
Web Technologies - I Introduction to HTML, HTTP and PHP
• Table heading can be defined using <th> tag or the <th> tag defines a header cell in an
HTML table. An HTML table has two kinds of cells:
(i) Header Cells: Contains header information (created with the <th> element), and
(ii) Standard Cells: Contains data (created with the <td> element).
1.29
Web Technologies - I Introduction to HTML, HTTP and PHP
• The <tr> tag defines a row in an HTML table. A <tr> element contains one or more <th>
or <td> elements.
• The <td> tag defines a standard cell in an HTML table. The <td> tag is used to mark up
individual cells inside a table row.
• The <caption> tag defines a table caption. The <caption> tag is used to provide a
caption for a table. This caption can either appear above or below the table.
• Tables can be divided into three portions namely a header, a body, and a foot. The
head and foot are rather similar to headers and footers in a word-processed document
that remain the same for every page, while the body is the main content of the table.
1.30
Web Technologies - I Introduction to HTML, HTTP and PHP
• The three elements for separating the head, body, and foot of a table are:
o <thead>: To create a separate table header.
o <tbody>: To indicate the main body of the table.
o <tfoot>: To create a separate table footer.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Practice HTML table footer, header and body</title>
</head>
<body>
<p>Try with different footer, heard and body parts</p>
<table border="1" width="100%">
<thead>
<tr>
<td colspan="4">This is the head of the table</td>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="4">This is the foot of the table</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
<td>Cell 4</td>
</tr>
<tr>
...more rows here containing four cells...
</tr>
</tbody>
1.31
Web Technologies - I Introduction to HTML, HTTP and PHP
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
<td>Cell 4</td>
</tr>
<tr>
...more rows here containing four cells...
</tr>
</tbody>
</table>
</body>
</html>
Output:
• Cellspacing attribute defines the width of the border, while cellpadding attribute
represents the distance between cell borders and the content within.
Example for cellspacing and cellpadding:
<!DOCTYPE html>
<html>
<head>
<title>HTML Table Cellpadding</title>
</head>
<body>
<table border = "1" cellpadding = "10" cellspacing = "10">
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
1.32
Web Technologies - I Introduction to HTML, HTTP and PHP
<td>Ramesh Salvi</td>
<td>5000</td>
</tr>
<tr>
<td>Amar Dube</td>
<td>7000</td>
</tr>
</table>
</body>
</html>
Output:
• We will use colspan attribute if we want to merge two or more columns into a single
column. Similar way we will use rowspan if we want to merge two or more rows.
Example for colspan amd rowspan attributes:
<!DOCTYPE html>
<html>
<head>
<title>Practice HTML table spans</title>
</head>
<body>
<p>Merge two or more rows or columns and then see the result:</p>
<table border="1">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr><td rowspan="2">Row 1 Cell 1</td>
<td>Row 1 Cell 2</td><td>Row 1 Cell 3</td></tr>
<tr><td>Row 2 Cell 2</td><td>Row 2 Cell 3</td></tr>
<tr><td colspan="3">Row 3 Cell 1</td></tr>
</table>
</body>
</html>
1.33
Web Technologies - I Introduction to HTML, HTTP and PHP
Output:
Nested Tables:
• We can use one table inside another table is called as nesting of tables (or nested
tables). Not only tables we can use almost all the tags inside table data tag <td>.
Example for nested tables:
<!DOCTYPE html>
<html>
<head>
<title>HTML Nested table</title>
</head>
<body>
<table border="1">
<tr>
<td>
<table border="1">
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td>Ramesh Salvi</td>
<td>5,700</td>
</tr>
<tr>
<td>Amar Dube</td>
<td>7,500</td>
</tr>
</table>
</td>
<td>
<ul>
<li>This is another cell</li>
<li>Using list inside this cell</li>
</ul>
1.34
Web Technologies - I Introduction to HTML, HTTP and PHP
</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>
</body>
</html>
Output:
1.35
Web Technologies - I Introduction to HTML, HTTP and PHP
Attributes:
Attributes Value Description
1. accept file_type This attribute specifies a comma-separated
list of file types that the server accepts (that
can be submitted through the file upload).
2. accept-charset character_set This attribute specifies the character
encodings that are to be used for the form
submission.
3. action URL This attribute specifies where to send the
form-data when a form is submitted.
4. autocomplete on This attribute specifies whether a form
off should have autocomplete on or off.
5. enctype application/x- This attribute specifies how the form-data
www-form- should be encoded when submitting it to
urlencoded the server (only for method="post").
multipart/form-
data
text/plain
6. method get This attribute specifies the HTTP method to
post use when sending form-data.
7. name text This attribute specifies the name of a form.
8. novalidate novalidate This attribute specifies that the form should
not be validated when submitted.
9. target _blank This attribute specifies where to display the
_self response that is received after submitting
_parent the form.
_top Target to open the given URL:
_blank : The target URL will open in a new
window.
_self : The target URL will open in the
same frame as it was clicked.
_parent : The target URL will open in the
parent frameset.
_top : The target URL will open in the
full body of the window.
1.36
Web Technologies - I Introduction to HTML, HTTP and PHP
• Users interact with forms through named controls. A control's "control name" is given
by its name attribute. The <form> element can contain one or more of the form
elements: <input>, <textarea>, <button>, <select>, <option>, <fieldset>, <label> etc.
HTML <input> Tag:
• The most important form element is the <input> tag which defines an input control.
• The <input> tag are used within a <form> element to declare input controls that allow
users to input data. An input field can vary in many ways, depending on the type
attribute.
Syntax: <input type= " ">
Attributes:
Attributes Value Description
1. accept audio/* This attribute specifies the types of files that the
video/* server accepts (only for type="file").
image/*
MIME_type
2. align left This attribute specifies the alignment of an image
right input (only for type="image").
top
middle
bottom
3. alt text This attribute specifies an alternate text for an
image (only for type="image").
4. checked checked This attribute specifies that an <input> element
should be preselected when the page loads (for
type="checkbox" or type="radio").
5. disabled disabled This attribute specifies that an <input> element
should be disabled.
6. maxlength number This attribute specifies the maximum number of
characters allowed in an <input> element.
7. name name This attribute specifies the name of an <input>
element.
8. readonly readonly This attribute specifies that an input field should
be read-only.
9. size number This attribute specifies the width, in characters, of
an <input> element.
contd. …
1.37
Web Technologies - I Introduction to HTML, HTTP and PHP
10. src URL This attribute specifies the URL of the image to use
as a submit button (only for type="image").
11. type button This attribute specifies the type of <input> element.
checkbox
file
hidden
image
password
radio
reset
submit
text
2. Password Field: Password fields are similar to text fields. The difference is that what
is entered into a password field shows up a dot on the screen. This is, of course, to
prevent others from reading the password on the screen.
Syntax: <input type = "password">
Attribute Explanation
1. size= Characters shown.
2. maxlength= Max characters allowed.
3. name= Name of the field.
4. value= Initial value in the field.
5. align= Alignment of the field.
6. tabindex= Tab order of the field.
<div align="center">
Enter Password: <input type="password" size="25">
<br><br>
</div>
</form>
</body>
</html>
Output:
3. <label> Tag: The <label> tag defines a label for an <input> element.
4. <fieldset> Tag: <fieldset> tag defines a border around elements in a form. The
<fieldset> tag is used to group related elements in a form. The <fieldset> tag draws a
box around the related elements.
Attributes:
Attribute Value Description
1. disabled disabled This attribute specifies that a group of related form
elements should be disabled.
2. form form_id This attribute specifies one or more forms the field
set belongs to.
3. name text This attribute specifies a name for the field set.
Example for <fieldset> tag: The <legend> tag defines a caption for a <fieldset> element.
<!DOCTYPE html>
<html>
<body>
<form>
<fieldset>
<legend><b>User Information:</b></legend>
Name: <input type="text"><br>
Email: <input type="text"><br>
Date of birth: <input type="text">
</fieldset>
</form>
</body>
</html>
1.40
Web Technologies - I Introduction to HTML, HTTP and PHP
Output:
5. Hidden Field: Hidden fields are similar to text fields. The difference is that the hidden
field does not show on the page. Therefore the visitor cannot type anything into a
hidden field, which leads to the purpose of the field.
Syntax: <input typ = "hidden">
Attribute Explanation
6. <textarea> Tag: It defines a multi-line text input control. The size of a text area is
specified by the cols and rows attributes.
Syntax: <textarea>………</textarea>
1.41
Web Technologies - I Introduction to HTML, HTTP and PHP
7. Radio Buttons: Radio buttons are used when only one option is required to be
selected. They are created using <input> tag.
Syntax: <input type="radio">
Following is the list of important radiobox attributes:
(i) type: Indicates that you want to create a radiobox.
(ii) name: Name of the control.
(iii) value: Used to indicate the value that will be sent to the server if this option is
selected.
(iv) checked: Indicates that this option should be selected by default when the page
loads.
1.42
Web Technologies - I Introduction to HTML, HTTP and PHP
8. Checkbox Control: Checkboxes are used when more than one option is required to be
selected. They are created using <input> tag.
Syntax: <input type="checkbox">
Following is the list of important checkbox attributes:
(i) type: Indicates that you want to create a checkbox.
(ii) name: Name of the control.
(iii) value: The value that will be used if the checkbox is selected. More than one
checkbox should share the same name only if you want to allow users to select
several items from the same list.
(iv) checked: Indicates that when the page loads, the checkbox should be selected.
Example for checkboxes:
<!DOCTYPE html>
<html>
<head>
<title>Practice HTML input checkbox tag</title>
</head>
<body>
1.43
Web Technologies - I Introduction to HTML, HTTP and PHP
9. <select>Tag: The <select> tag is used to create a drop-down list. Drop-down list is used
when we have many options available to be selected but only one or two will be
selected. The <option> tags inside the <select> element define the available options in
the list.
Syntax: <select>…………</select>
Attributes Value Description
1. disabled disabled This attribute specifies that a drop-down list should
be disabled.
2. multiple multiple This attribute specifies that multiple options can be
selected at once.
3. name name This attribute defines a name for the drop-down
list.
4. size number This attribute specifies defines the number of
visible options in a drop-down list.
10. Creating Button: The <button> tag defines a push button. We can create clickable
button using <input> tag.
Syntax: <button>……………</button>
Attributes Value Description
1. disabled disabled This attribute specifies that a button should be
disabled.
2. name name This attribute specifies the name for a button.
3. type button This a3ttribute specifies the type of button. The
reset submit value creates a button that automatically
submit submits a form. The reset value creates a button
that automatically resets form controls to their
initial values. The button value creates a button that
is used to trigger a client-side script when the user
clicks that button.
4. value text This attribute specifies the initial value for a button.
Example for <button> tag:
<!DOCTYPE html>
<html>
<body>
<form name="input" action="html_form_action.asp" method="get">
First name: <input type="text" name="FirstName"
value="Mickey" /><br />
Last name: <input type="text" name="LastName" value="Mouse" /><br />
<input type="submit" value="Submit" />
</form>
<p>If you click the "Submit" button, the form-data will be sent
to a page called "html_form_action.asp".</p>
</body>
</html>
1.45
Web Technologies - I Introduction to HTML, HTTP and PHP
Output:
Example:
<!DOCTYPE html>
<html>
<body>
<form action="/cgi-bin/hello_get.cgi" method="get">
First name:
<input type="text" name="first_name" /><br>
Last name:
<input type="text" name="last_name" />
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</form>
</body>
</html>
Output:
11. <option> Tag: It defines an option in a select list. The <option> tag go inside a <select>
element.
Syntax: <option>……………</option>
Attributes Value Description
1. disabled disabled This attribute specifies that an option should be
disabled.
2. label text This attribute specifies a shorter label for an
option.
3. selected selected This attribute specifies that an option should be
pre-selected when the page loads.
4. value text This attribute specifies the value to be sent to a
server.
Example for <option> tag:
<!DOCTYPE html>
<html>
<body>
<form name="myform" action="nextpage.html" method="post" >
1.46
Web Technologies - I Introduction to HTML, HTTP and PHP
</select><br><br>
<input type="submit" name="button" value="Submit data">
</form>
</body>
</html>
Output:
Fig. 1.6
• Various semantic elements in HTML5 are explained below:
1. HTML5 <article> Element:
• The <article> element is used to represent an article. The <article> element specifies
independent, self-contained content.
1.48
Web Technologies - I Introduction to HTML, HTTP and PHP
• Examples of article content could include a forum post, a newspaper article, a blog
entry, or a user-submitted comment.
Syntax: <article>…..</article>
1.49
Web Technologies - I Introduction to HTML, HTTP and PHP
<a href="/html/">Dreamweaver</a> |
<a href="/html/">Ajax</a> |
<a href="/jquery/">jQuery</a>
</nav>
<p><strong>Note:</strong> The nav tag is not supported in
Internet Explorer 8 and earlier versions.</p>
</body>
</html>
Output:
1.50
Web Technologies - I Introduction to HTML, HTTP and PHP
1.52
Web Technologies - I Introduction to HTML, HTTP and PHP
1.53
Web Technologies - I Introduction to HTML, HTTP and PHP
1.54
Web Technologies - I Introduction to HTML, HTTP and PHP
nav {
float: left;
width: 20%;
height: 200px;
background: #282828;
padding: 60px 10px;
}
nav ul {
list-style-type: none;
padding: 0;
}
nav ul li a {
text-decoration: none;
color: #fff;
}
article {
float: left;
padding: 80px 10px;
width: 80%;
background-color: #fff;
height: 200px;
text-align: center;
}
section:after {
content: "";
display: table;
clear: both;
}
footer {
background-color: #000;
padding: 20px;
text-align: center;
color: white;
}
</style>
<body>
<h1>HTML Semantics Demo</h1>
<header>This is Header</header>
1.55
Web Technologies - I Introduction to HTML, HTTP and PHP
<section>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<article>This is an article element.</article>
</section>
<footer>This is Footer</footer>
</body>
</html>
Output:
1.57
Web Technologies - I Introduction to HTML, HTTP and PHP
• The HTML <source> tag is used to specify multiple media resources on media elements
such as <audio> and <video>.
• The <object> tag defines an embedded object within an HTML document. Use this
element to embed multimedia (like audio, video, Java Aapplets, ActiveX, PDF, and
Flash) in the web pages.
• The HTML <audio> tag is used to specify audio on an HTML document.
Syntax: <audio>…</audio>
Attribute Value Description
1. autoplay autoplay This attribute specifies that the audio will start
playing as soon as it is ready.
2. controls controls This attribute specifies that audio controls should
be displayed (such as a play/pause button etc).
3. loop loop This attribute specifies that the audio will start over
again, every time it is finished.
4. muted muted This attribute specifies that the audio output should
be muted.
5. preload auto This attribute specifies if and how the author
metadata thinks the audio should be loaded when the page
none loads.
6. src URL This attribute specifies the URL of the audio file.
1.58
Web Technologies - I Introduction to HTML, HTTP and PHP
• The <video> tag is used to specify video on an HTML document. The <video> tag
specifies video, such as a movie clip or other video streams.
Syntax: <video>…</video>
Attributes:
Attribute Value Description
1. autoplay autoplay This attribute specifies that the video will start
playing as soon as it is ready.
2. controls controls This attribute specifies that video controls
should be displayed (such as a play/pause
button etc).
3. height pixels This attribute sets the height of the video
player.
4. loop loop This attribute specifies that the video will start
over again, every time it is finished.
5. muted muted This attribute specifies that the audio output of
the video should be muted.
6. poster URL This attribute specifies an image to be shown
while the video is downloading, or until the
user hits the play button.
7. preload auto This attribute specifies if and how the author
metadata thinks the video should be loaded when the
none page loads.
8. src URL This attribute specifies the URL of the video
file.
9. width pixels This attribute sets the width of the video
player.
Example for <video> tag:
<!DOCTYPE html>
<html>
<body>
<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
<p><strong>Note:</strong> The video tag is not supported in Internet
Explorer 8 and earlier versions.</p>
</body>
</html>
1.59
Web Technologies - I Introduction to HTML, HTTP and PHP
Output:
1.60
Web Technologies - I Introduction to HTML, HTTP and PHP
Fig. 1.7
Syntax of CSS: selector { property: value }
Example: We can define a table border as follows:
table{ border:1px solid #C00; }
Here, table is a selector and border is a property and given value 1px solid #C00 is the
value of that property. We can define selectors in various simple ways based on our
comfort.
• CSS selectors are used to "find" (or select) the HTML elements we want to style. Let us
see these selectors one by one.
1. Type Selectors: A type selector sometimes referred to as an element selector
selects HTML elements based on the element name such as <p>, <h1>, <div> and so
on. The example to give a color to all level 1 headings like this:
h1 {
color: #36CFFF;
}
1.61
Web Technologies - I Introduction to HTML, HTTP and PHP
This rule renders the content in black for every element with id attribute set to
black in our document. You can make it a bit more particular. For example:
h1#black {
color: #000000;
}
This rule renders the content in black for only <h1> elements with id attribute set
to black.
The true power of id selectors is when they are used as the foundation for
descendant selectors, For example:
#black h2 {
color: #000000;
}
In above example all level 2 headings will be displayed in black color only when
those headings will lie within tags having id attribute set to black.
6. Child Selectors: The child selector selects all elements that are the children of a
specified element. Consider the following example:
body > p {
color: #000000;
}
This rule will render all the paragraphs in black if they are direct child of <body>
element. Other paragraphs put inside other elements like <div> or <td> etc. would
not have any effect of this rule.
7. Attribute Selectors: We can also apply styles to HTML elements with particular
attributes. The attribute selector is used to select elements with a specified
attribute or attribute value. The style rule below will match all input elements that
have a type attribute with a value of text:
input[type="text"]{
color: #000000;
}
The advantage to this method is that the <input type="submit" /> element is
unaffected, and the color applied only to the desired text fields.
There are following rules applied to attribute selector.
o p[lang]: Selects all paragraph elements with a lang attribute.
o p[lang="fr"]: Selects all paragraph elements whose lang attribute has a value
of exactly "fr".
o p[lang~="fr"]: Selects all paragraph elements whose lang attribute contains
the word "fr".
o p[lang|="en"]: Selects all paragraph elements whose lang attribute contains
values that are exactly "en", or begin with "en-".
1.63
Web Technologies - I Introduction to HTML, HTTP and PHP
Multiple Style Rules: We may need to define multiple style rules for a single
element. We can define these rules to combine multiple properties and
corresponding values into a single block as defined in the following example:
h1
{
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}
Here, all the property and value pairs are separated by a semi colon (;). We can
keep them in a single line or multiple lines.
For better readability we keep them into separate lines. For a while do not bother
about the properties mentioned in the above block.
8. Grouping Selectors: The grouping selector selects all the HTML elements with the
same style definitions. We can apply a style to many selectors if we like. Just
separate the selectors with a comma as given in the following example:
h1, h2, h3 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}
This define style rule will be applicable to h1, h2 and h3 element as well. The order
of the list is irrelevant. All the elements in the selector will have the corresponding
declarations applied to them.
We can combine various class selectors together as shown below:
#content, #footer, #supplement {
position: absolute;
left: 510px;
width: 200px;
}
1.64
Web Technologies - I Introduction to HTML, HTTP and PHP
3. External CSS:
• An external style sheet is ideal when the style is applied to many pages. With an
external style sheet, we change the look of an entire web site by changing one file.
1.66
Web Technologies - I Introduction to HTML, HTTP and PHP
• External CSS contains only CSS code and is saved with a ".css" file extension. This CSS
file is referred from HTML file using the <link> tag.
• To use an external style sheet, add a <link> tag in the <head> section of each HTML
page.
CSS Code:
p {
text-align: center;
color: white;
}
body {
background-color: green;
}
• Save the above file as sample.css
HTML Code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="sample.css" />
</head>
<body>
<p> This is an example for inserting CSS externally. </p>
</body>
</html>
Output:
o Padding is the second inner most box, sits outside of the content area. The padding
is the space between the content area box and the border box of the HTML
element. The size of padding box can be controlled using padding and related
properties.
o Border is the second outer most box sits inside the margin, and surrounds the
padding and content of the HTML element. The border box wraps the content and
any padding. Its size and style can be controlled using border and related
properties.
o Margin is the outermost box that consists of transparent space outside of the
border of an element. The margin box wrapping the content, padding and border
as whitespace between this box and other elements. Its size can be controlled
using margin and related properties.
Margin
Border
Padding
Content
CSS Text Properties: Defines how to manipulate text using CSS properties.
1. The color property is used to set the color of a text.
2. The direction property is used to set the text direction.
3. The letter-spacing property is used to add or subtract space between the letters
that make up a word.
4. The word-spacing property is used to add or subtract space between the words of
a sentence.
5. The text-indent property is used to indent the text of a paragraph.
6. The text-align property is used to align the text of a document.
7. The text-decoration property is used to underline, overline, and strikethrough
text.
8. The text-transform property is used to capitalize text or convert text to uppercase
or lowercase letters.
9. The white-space property is used to control the flow and formatting of text.
10. The text-shadow property is used to set the text shadow around a text.
CSS Font Properties: Defines how to set fonts of a content, available in an HTML element.
1. The font-family property is used to change the face of a font.
2. The font-style property is used to make a font italic or oblique.
3. The font-variant property is used to create a small-caps effect.
4. The font-weight property is used to increase or decrease how bold or light a font
appears.
5. The font-size property is used to increase or decrease the size of a font.
6. The font property is used as shorthand to specify a number of other font
properties.
CSS Background Properties: Defines how to set backgrounds of various HTML elements.
1. The background-color property is used to set the background color of an element.
2. The background-image property is used to set the background image of an
element.
3. The background-repeat property is used to control the repetition of an image in
the background.
4. The background-position property is used to control the position of an image in
the background.
5. The background-attachment property is used to control the scrolling of an image
in the background.
6. The background property is used as a shorthand to specify a number of other
background properties.
1.69
Web Technologies - I Introduction to HTML, HTTP and PHP
CSS Border Properties: The border properties allow you to specify how the border of the
box representing an element should look.
1. The border-color specifies the color of a border.
2. The border-style specifies whether a border should be solid, dashed line, double
line, or one of the other possible values.
3. The border-width specifies the width of a border.
CSS Margin Properties: Defines the space around an HTML element.
1. The margin specifies a shorthand property for setting the margin properties in
one declaration.
2. The margin-bottom specifies the bottom margin of an element.
3. The margin-top specifies the top margin of an element.
4. The margin-left specifies the left margin of an element.
5. The margin-right specifies the right margin of an element.
CSS Link Properties: Defines how to set different properties of a hyper link using CSS.
1. The :link signifies unvisited hyperlinks.
2. The :visited signifies visited hyperlinks.
3. The :hover signifies an element that currently has the user's mouse pointer
hovering over it.
4. The :active signifies an element on which the user is currently clicking.
CSS List Properties: Defines how to control list type, position, style, etc., using CSS.
1. The list-style-type allows us to control the shape or appearance of the marker.
2. The list-style-position specifies whether a long point that wraps to a second line
should align with the first line or start underneath the start of the marker.
3. The list-style-image specifies an image for the marker rather than a bullet point
or number.
4. The list-style serves as shorthand for the preceding properties.
5. The marker-offset specifies the distance between a marker and the text in the list.
CSS Table Properties: Defines how to set different properties of an HTML table using
CSS.
1. The border-collapse specifies whether the browser should control the
appearance of the adjacent borders that touch each other or whether each cell
should maintain its style.
2. The border-spacing specifies the width that should appear between table cells.
3. The caption-side captions are presented in the <caption> element. By default,
these are rendered above the table in the document. We use the caption-
side property to control the placement of the table caption.
4. The empty-cells specifies whether the border should be shown if a cell is empty.
5. The table-layout allows browsers to speed up layout of a table by using the first
width properties it comes across for the rest of a column rather than having to
load the whole table before rendering it.
1.70
Web Technologies - I Introduction to HTML, HTTP and PHP
li {
float: left;
}
li a {
display: block;
padding: 8px;
background-color: #dddddd;
}
</style>
</head>
<body>
<ul>
1.71
Web Technologies - I Introduction to HTML, HTTP and PHP
<li><a href="d:\Ty\home.html">Home</a></li>
<li><a href="d:\Ty\news.html">News</a></li>
<li><a href="d:\Ty\contact.html">Contact</a></li>
<li><a href=""d:\Ty\About.html">About</a></li>
</ul>
<p> PDEAs A.M. College </p>
<p>A background color is added to the links to show the link
area. The whole link area is clickable, not just the text.</p>
</body>
</html>
Output:
• In above example the, list-style-type: none; - Removes the bullets. A navigation bar
does not need list markers. Set margin: 0; and padding: 0; to remove browser default
settings.
• The web is a collection of files known as web pages. These web pages (or web site)
reside on a computer known as a web server.
• A web server interacts with the client through the web browser and processes
requests, sent by the client.
• The primary function of a web server is to store, process and deliver web pages to
clients.
1.72
Web Technologies - I Introduction to HTML, HTTP and PHP
• The function of a typical Web server is shown in Fig. 1.9. The communication between
client and server takes place using the HyperText Transfer Protocol (HTTP).
• To view a website, the browser sends a request to the server. On receiving the request,
the server sends (response) the appropriate web page to the client's machine.
• The client's machine (browser) receives the web page and displays onto the user's
computer screen.
• To view Web pages, we need a Web browser which is a software program that
requests, downloads and displays Web pages stored on a Web server.
• Web browser used to access the Internet and the WWW. It is basically used to access
and view the web pages of the various websites available on the Internet.
• A Web browser (a browser) is application software for retrieving, presenting, and
traversing information resources on the Internet and World Wide Web (WWW).
1.73
Web Technologies - I Introduction to HTML, HTTP and PHP
• A browser can be defined as, "a software used to locate, retrieve and display content
on the Internet and World Wide Web, including web pages, images, audio, video and
other files".
• Browsers are of two types as explained below:
1. Graphical Browsers: These browsers allow retrieval of text, images, audio, and
video. Navigation is accomplished by pointing and clicking with a mouse on
highlighted words and graphics. Both Netscape Navigator and Internet Explorer
are graphical browsers.
2. Text Browsers: These browsers provide access to the web in text-only mode.
Navigation is accomplished by highlighting emphasized words on the screen with
the arrow up and down keys, and then pressing the Enter key to follow the link.
Lynx is an example of text-based browser.
• Web browser is application software that allows us to view and explore information
on the web. Common and popular Web Browsers are explained below:
1. Opera ( ): Opera is a web browser developed by Opera Software. The latest
version is available for Windows, macOS, and Linux operating systems. Opera is a
fast and secure browser.
2. Internet Explorer ( ): Internet Explorer (IE) is a web browser from Microsoft. IE
was released as the default browser with Windows 95 (1995). Internet Explorer
connects your computer to the Web through an Internet connection. The browser
lets you view, print, and search for information on the Web.
3. Mozilla Firefox ( ): Firefox is a free and open source web browser developed
for Microsoft Windows, Mac OS X, and Linux (with its mobile versions available
for Android, and Firefox OS) co-ordinated by Mozilla Corporation and Mozilla
Foundation.
4. Safari ( ): Safari is web browser that was produced and developed by Apple
Inc. which functions on a Mac OX, iOS, and Windows operating system.
5. Google Chrome ( ): Google Chrome is a freeware browser developed by Google
using the WebKit layout engine.
Differences between Web Browser and Web Server:
Sr.
Web Browser Web Server
No.
1. Web browser is software which is Web server is a software which
used to browse and display web pages provides the documents when
available over the internet. requested by web browsers.
2. A web browser sends request to Web server sees and approves those
server for web based documents. requests made by web browsers and
sends the document in response.
contd. …
1.74
Web Technologies - I Introduction to HTML, HTTP and PHP
Client Server
Time Client Request
Method URI HTTP-version
General-header
Request-header
Entity-header
Entity-body
Server Response
HTTP-version Status-code Reason-Phrase
General-header
Respons-header
Entity-header
Entity-body
1.75
Web Technologies - I Introduction to HTML, HTTP and PHP
• The HTTP protocol is based on the client-server based architecture where Web
browsers act as clients and the Web server acts as a server.
• The Client (also called as HTTP client) and server (also called as HTTP server)
communicate by sending messages.
• The client sends a request message (also called as HTTP Request) to the server. The
server, in turn, returns a response message (also called as HTTP Response).
• Fig. 1.10 shows the HTTP transaction (request and response) between the client and
server.
HTTP Messages:
• HTTP message is used to show how data is exchanged between the client and the
server. It is based on client-server architecture.
• An HTTP client is a program that establishes a connection to a server to send one or
more HTTP request messages.
• An HTTP server is a program that accepts connections to serve HTTP requests by
sending an HTTP response messages.
• HTTP messages are simple, line-oriented sequences of characters. There are two types
of HTTP messages i.e. request message and response message.
• The HTTP messages sent from web clients to web servers are called request messages
while the messages from servers to clients are called response messages.
• The formats of the request and response messages are shown in Fig. 1.11.
Headers Headers
Body Body
(present only in (present only in
some messages) some messages)
Request Headers: The HTTP Request Header contains optional header information
sent by the client like MIME type the browser accepts, information about the web
browser etc.
For example: Accept: image/gif, image/jpeg, text/*, */*
Accept-Language: en-us
Host: www.example.com
User-Agent: Mozilla (x11; I; Linux 2.0.32 i586)
After header the HTTP request contains a blank line which indicates the end of the
header section.
Request Body: In case of GET method the HTTP request body is empty, and with the
POST method it contains additional data. Message body is optimal in HTTP request.
2. HTTP Response Message: The web server receives the request from client, processes
it and sends a response back to the client browser through Response message.
Status Line: The first line is called status line which looks like this:
HTTP/1.1 200 OK
This line specifies the protocol version, a status code, and a description of that code. In
this case, the status code is “200”, meaning that the request was successful (hence the
description “OK”).
Response Headers: The response header gives client additional information about
the response like information about the web server software, MIME type of the data
included in the response etc.
For example: Date: Sat, 26 Jan 2002 20:25:12 GMT
Server: Apache 1.3.22 (Unix) mod_perl/1.26 PHP/4.1.0
Content-Type: text/html
Content-Length: 141
After header the HTTP request contains a blank line which indicates the end of the
header section.
Response Body: If the response was successful, the HTTP response body contains the
HTML code, ready for the browser interpretation. If unsuccessful, a failure code is
sent.
Example for HTTP Request Message and HTTP Response Message: HTTP request to
fetch hello.htm page from the web server running on niraliprakashan.com. The HTML
code given below:
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
1.77
Web Technologies - I Introduction to HTML, HTTP and PHP
Client Request:
GET /hello.htm HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.niraliprakashan.com
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Server Response:
HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT
Content-Length: 88
Content-Type: text/html
Connection: Closed
• PHP is a server side scripting language which is used to create dynamic and
interactive web pages.
• A script is a set of programming instructions that is interpreted at runtime. A scripting
language is a language that interprets scripts at runtime.
• Server side scripts are interpreted on the server while client side scripts are
interpreted by the client.
• PHP is a server side script that is interpreted on the server while JavaScript is an
example of a client side script that is interpreted by the client browser.
• PHP is a recursive acronym for "PHP: Hypertext Preprocessor". PHP is an open-source,
interpreted, and object-oriented scripting language that can be executed at the
server-side.
• PHP files can contain text, HTML, CSS, JavaScript, and PHP code. PHP codes are
executed on the server, and the result is returned to the browser as plain HTML. PHP
files have extension ".php".
• PHP 7 is a major release of PHP programming language in 2015 and is touted to be a
revolution in the way web applications can be developed and delivered for mobile to
enterprises and the cloud.
• The latest version of PHP is PHP 8 was released on November 26, 2020. Facebook,
Flickr and Yahoo are the examples of PHP applications.
• PHP is a server side scripting language that is embedded in HTML. It is used to manage
dynamic content, databases, session tracking, even build entire e-commerce sites.
1.78
Web Technologies - I Introduction to HTML, HTTP and PHP
File
Yes contains
PHP
scripts?
3. Existing Libraries Support: Lot of functions for common web development task
e.g. Sending E-mail, XML parsing etc.
4. Portability: PHP support on all major operating system like Windows, Mac OS,
Linux etc. A PHP application developed in one operating system can be easily
executed in other operating system also.
5. Simplicity: In PHP there is no need to include libraries, special compilation
directives, or anything of the sort.
6. Efficiency: PHP is efficient in a multiuser environment such as the WWW. PHP
also support object-oriented programming with similar syntax and feature as C++
and Java.
7. Flexibility: Because PHP is an embedded language, it is extremely flexible towards
meeting the needs of the developer. PHP code can be easily embedded within
HTML tags and script.
8. Familiarity: In PHP many of the language’s constructs are borrowed from C and
Perl. PHP has easily understandable syntax. Programmers are comfortable coding
with it.
9. Security: PHP is a secure scripting language to develop the website. It consists of
multiple layers of security to prevent threads and malicious attacks.
10. Open Source: PHP source code and software are freely available on the web.
Anyone can develop all the versions of PHP according to his/her requirement
without paying any cost.
<?php
echo "Hello PHP";
?>
</body>
</html>
Output:
1.6.4 Comments
• Comments give information to people who read the code, but they are not interpreted
by PHP engine.
• Comments in PHP programming language is used to describe code and make simple to
understand other programmer/users and it is ignore by compiler or interpreter.
• PHP supports 'C', 'C++' and Unix shell-style (Perl style) comments.
1.83
Web Technologies - I Introduction to HTML, HTTP and PHP
For example:
<?php
echo 'This is a test'; // This is a one-line C++ style comment
# Shell-style comment
/* This is a multi line comment.
This is a C style comment.
Yet another line of comment */
echo 'This is yet another test';
echo 'One Final Test'; # This is a one-line shell-style comment
?>
• When PHP encounters two slash characters (//) within the code, everything from the
slashes to the end of the line or the end of the section of code, whichever comes first, is
considered a comment. This method of commenting is derived from C++. The result is
the same as the shell comment style.
• PHP supports block comments, whose syntax comes from the C programming
language.
• When PHP encounters a slash followed by an asterisk (/*), everything after that until it
encounters an asterisk followed by a slash (*/) is considered a comment.
• When PHP encounters a hash mark (#) within the code, everything from the hash
mark to the end of the line or the end of the section of PHP code (whichever comes
first) is considered a shell-style comment.
• The shell-style comment is found in Unix shell scripting languages and is useful for
annotating single lines of code or making short notes.
1.6.5 Literals
• A literal is a data value in PHP that appears directly in a program.
• For example:
“Hello”
100
true
null
1.6.6 Identifiers
• An identifier is simply a name. In PHP, identifiers are used to name variables,
functions, constants, and classes.
• The first character of an identifier must be an ASCII letter (a-z, A-Z), the underscore
character (_) or any character between ASCII Ox7F and ASCII OxFF. After the initial
character, combinations of these previous characters and the digits 0-9 are valid.
1.84
Web Technologies - I Introduction to HTML, HTTP and PHP
1. Variable Names: Variables in PHP starts with a dollar sign ($). The variable name
is case sensitive.
Valid Variable Names:
$bill
$bill_amt
$GrossSal
$_underscore
Invalid Variable Names:
$not valid
$7X
Following valid variables are all different:
$Net_sal
$net_sal
$net_sal
$NET_SAL
2. Function Names: Function names are not case sensitive. And so following
function names refer to the same function:
For example: howdy(), Howdy(), HOWDY(), HOWdy()
3. Class Names: Class names follow the standard rules for PHP identifiers and are
not case sensitive.
For example,
person or Person is same
Account or Account is same
1.6.7 Constants [April 18]
• A constant is a name or an identifier for a simple value. A constant value cannot
change during the execution of the PHP script.
• A constant is case-sensitive by default. By convention, constant identifiers are always
uppercase. Only single values i.e. scalars can be constants, like Boolean, integer,
double, string etc.
• In PHP we use the define() function to create a constant. It defines constant at run
time.
Syntax: define("constant_Name", Value)
For example,
define(‘PI’, 3.14);
echo PI;
• In PHP the const keyword also defines constants at compile time. It is a language
construct not a function. It is always case sensitive.
1.85
Web Technologies - I Introduction to HTML, HTTP and PHP
For example,
<?php
const MESSAGE="Hello const by PHP";
echo MESSAGE;
?>
• Words reserved by the language for its core functionality are called as keyword or
reserved word.
• In PHP, keywords are case insensitive. A keyword is a word reserved by the language
for its core functionality - we cannot give a variable, function, class, or constant the
same name as a keyword.
• Some examples of keywords in PHP are given below:
break exception new
case while or
catch endwhile public
class exit( ) static
do function switch
for if throw
endfor else try
extends elseif var
• A data type is defined as "a set of values and the allowable operations on those values".
The data type determines the operations that we can perform on it.
• PHP data types are used to hold different types of data or values. PHP data types
define the type of data a variable can store.
1.86
Web Technologies - I Introduction to HTML, HTTP and PHP
• PHP supports eight primitive types as shown in Fig. 1.13 and given below:
o Four scalar data types: integer, float (floating-point number, aka double), string,
and Boolean.
o Two compound data types: array and object.
o Two special data types: resource and NULL.
Data Types
String
Boolean
1.87
Web Technologies - I Introduction to HTML, HTTP and PHP
1.88
Web Technologies - I Introduction to HTML, HTTP and PHP
1.89
Web Technologies - I Introduction to HTML, HTTP and PHP
For example:
class Person
{
public $name = ‘ ‘;
function name ($newname)
{
$this → name = $newname;
}
}
$p = new Person();
$p->name(“Amar”);
echo “Hello $p->name”;
Output:
Hello Amar
• Use is_object() to test whether a value is an object.
if(is_object($x))
{
// $x is an object
}
7. Resource: [April 16]
• The resource is a special PHP data type that refers to external resource (e.g. file, image
etc.) which is not part of the PHP native language.
• It is basically used for dealing with the outside world. Resources are created and used
by special functions.
• For example, database connection function returns a resource which is used to
identify that connection when we call the query and close functions.
• Their main benefit is that they’re garbage collected when no longer in use. When the
last reference to a resource value goes away, the extension that created the resource is
called to free any memory, close any connection, etc. for that resource.
For example,
$result = database_connect( );
database_query ($result);
$result=”something”; // connection is closed.
• Use the is_resource( ) function to test whether a value is a resource:
if (is_resource($x))
{
// $x is a resource
}
1.90
Web Technologies - I Introduction to HTML, HTTP and PHP
8. NULL:
• This data type is having only one value and denoted by the keyword NULL. The NULL
value represents a variable that has no value.
• A variable is considered to be null if:
(i) it has been assigned the constant NULL.
(ii) it has not been set to any value yet.
(iii) it has been unset().
• The is_null() function is used to test whether a value is NULL.
1.7.2 Variables
• PHP variables are nothing but a named storage locations in the memory. A variable is
a named container in a PHP script in which a data value can be stored.
• The stored value can be referenced using the variable's name and changed (varied) as
the script proceeds/executes.
• Variables in PHP are identifiers prefixed with a dollar sign ($). For example:
$name
$Age
$_debugging
$MAXIMUM_IMPACT
• A variable may hold any type of value. There is no compile-time or runtime type
checking on variables. You can store any type of value in the same variable.
For example,
$a = "Hello";
$a = 12;
$a = array(10, 20, 30);
Variable Declaration:
• Variables are "containers" for storing information. In PHP, a variable is declared using
a $ sign followed by the name of the variable.
Syntax: $variable_name;
For example: $sum;
Rules for Variable Declaration:
1. A PHP variable must start with ($) dollar sign.
2. A variable name must start with an alphabet letter or the underscore (_).
3. A variable name cannot start with a number like $10RollNo.
4. PHP variable can be of any length.
5. Variable names are case-sensitive, ($RollNo and $rollNo are two different
variables).
6. PHP variable does not contain spaces.
1.91
Web Technologies - I Introduction to HTML, HTTP and PHP
Defining Variables:
• A variable stores a value of any type such as string, number, array, object or resource.
In PHP, defining variables means assigning values to the variables.
• Assigning a value to a variable in PHP is accomplished with the assignment operator
(=), with the variable on the left-hand side and the value to be evaluated on the right.
• Syntax to define a variable in PHP is $variable_name=value;
For example: $EmpId=10;
$StudentName=“Vedant”;
• A variable whose value has not been assign or set behaves like the NULL value.
Following example shows example of variables in PHP.
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "String is: $str <br/>";
echo "Integer is: $x <br/>";
echo "Float is: $y <br/>";
?>
Output:
String is: Hello world!
Integer is: 5
Float is: 10.5
1.7.2.1 Variable Variables [Oct. 16]
• PHP allows us to use dynamic variable names called as variable variables. Variable
variables are simply variables whose names are dynamically created by another
variable's value.
• In variable variables the value of existing variable is used as a name of new variable.
For example,
$a = ‘hello’; //hello is value of variable $a
$$a = ‘PHP’; //$($a) is equals to $(hello)
echo $hello; //$hello is PHP i.e. #hello is new variable with value 'PHP'
• In above example, $b is the reference variable or $b is an alias for the variable $a. $b
is now another name for the value that is stored in $a.
• Now, same value can be used by both the names.
echo $b; // Output: 5
$b = $b + 2;
echo $a; //
Output:
7 ($b is alias of $q i.e. $q and $b are same variable).
• We can unset the variable by using unset function but the reference is still set.
unset($a);
echo $b; // Output: 5
1.93
Web Technologies - I Introduction to HTML, HTTP and PHP
2. Global Scope:
• Variables declared outside function are by default global variables and can accessed
from any part of program.
• A global variable can be accessed in any part of the program except inside the
functions. Inside the function, these variables are accessed using the ‘global’ keyword.
Example for global scope:
<?php
$x = 15;
$y = 20;
function addit()
{
GLOBAL $x; // global variable;
$y = 10; // global variable;
$x++;
$y++;
printf "x = $x & y = $y";
} addit();
?>
Output:
x = 16 and y = 11
3 Static Variable:
• We know that, when function ends then all the variables declared inside the function
are destroyed. Static variables are those variables which can hold value when function
called again.
• Static variables are used only with the functions. These variables retain their values
between different calls to a function.
• We can declare a variable to be static simply by placing the keyword STATIC in front
of the variable name.
• The initialization of STATIC variable is done only for the first call to function and not
after that.
Example for static scope or variable:
<?php
function keep_track()
{
STATIC $count = 0;
$count++;
print $count;
print "<br>";
}
1.94
Web Technologies - I Introduction to HTML, HTTP and PHP
keep_track();
keep_track();
keep_track();
?>
Output:
1
2
3
4. Function Parameter:
• Function parameters are local, i.e. they are available only inside the function.
• Function parameters are declared after the function name and inside parentheses.
They are declared much like a typical variable.
Example for function parameter:
<?php
// multiply a value by and return it to the caller
function multiply ($value)
{
$value = $value * 4;
return $value;
}
$retval = multiply (10);
Print "Return value is $retval\n";
?>
Output:
Return value is 40
• An operator is a symbol that manipulates one or more values usually producing a new
value. Operators in PHP are used to performing operations on variables and values.
• Operators are special symbols that perform some specific operations using the
operands and operator as shown in Fig. 1.14.
Operands
Z=X+Y
Operator
Fig. 1.14: Concept of operator and operand
• In Fig. 1.14 operators indicate the operation to be carried out on operands, while
operands are the values going to be operated.
• Categories of operators in PHP are as follows:
1. Unary Operators operate on single operand.
2. Binary Operators which take two operands and produces output/result value.
3. Conditional Operator (Ternary Operator) which takes three operands and
evaluates either the second or third expression, depending on the evaluation of the
first expression.
• Let see various operators in PHP in detail:
1. Arithmetic Operators:
• The PHP arithmetic operators are used to perform common arithmetical operations,
such as addition, subtraction, multiplication etc.
• The arithmetic operators require numeric values and non-numeric values are
converted automatically to numeric values.
• There are following arithmetic operators supported by PHP language:
Example Name Result
-$a Negation Opposite of $a.
$a + $b Addition Sum of $a and $b.
$a - $b Subtraction Difference of $a and $b.
$a * $b Multiplication Product of $a and $b.
$a / $b Division Quotient of $a and $b..
$a % $b Modulus Remainder of $a divided by $b.
$a ** $b Exponentiation Result of raising $a to the $b'th power. Introduced
in PHP 5.6.
• The division operator ("/") returns a float value unless the two operands are integers
(or strings that get converted to integers).
1.96
Web Technologies - I Introduction to HTML, HTTP and PHP
• These assignment operators are Plus-equals (+=), Minus-equals (–=), Divide-equals (/=),
Multiply-equals (*=), Modulus-equals (%=), Bitwise-XOR-equals (^=), Bitwise-AND-
equals (&=), Bitwise-OR-equals (|=) and Concatenate-equals (.=).
6. Bitwise Operators:
• Bitwise operators perform operations on the binary representation of the operands.
These operators allow the evaluation and manipulation of specific bits within the
integer.
• The following illustrates bitwise operators in PHP:
Example Name Result
$a and $b and If both bits are 1, the corresponding bit in the
result is 1; otherwise, the corresponding bit is 0.
$a | $b or (inclusive or) If both bits are 0, the resulting bit is 0;
otherwise, the resulting bit is 1.
$a ^ $b xor (exclusive or) If either of the bits in the pair, but not both, is 1,
the resulting bit is 1; otherwise, the resulting bit
is 0.
~ $a not changes 1s to 0s and 0s to 1s in the binary
representations of the operands
$a << $b shift left Shift the bits of $a $b steps to the left (each step
means "multiply by two")
$a >> $b shift right Shift the bits of $a $b steps to the right (each
step means "divide by two")
7. Casting Operators:
• Casting operator changes type of its operand by force. PHP casting operators are (int),
(float), (string), (bool), (array), and (object).
For example:
$a = “5”; // type of $a is string
$b = (int) $a; // type of $b is integer
8. Miscellaneous Operators:
(i) Error suppression (@): This operator is also called as error control operator,
works only on expression. When the operator is used with expression then any
error messages that might be generated by that expression will be ignored.
(ii) Execution (‘…’): PHP supports one execution operator: backticks (‘ ’). Note that
these are not single-quotes! PHP will attempt to execute the contents of the
backticks as a shell command
$output = ‘ls -l’; // shell command for long list of files.
echo $output; // Displays long list of files from present directory
1.99
Web Technologies - I Introduction to HTML, HTTP and PHP
(iii) Conditional (?:) OPerator: It is also called as ternary operator which first
evaluates an expression for a true or false value and then executes one of the two
given statements depending upon the result of the evaluation.
Syntax: expr1? expr2: expr 3
Meaning is, if expr1 is true, execute expr2 otherwise expr3.
For example:
<?
$a = 10;
$b = 15;
$max = $a > $b? $a: $b;
$min = $a < $b? $a: $b;
echo "max = $max";
echo "min = $min";
?>
Output:
max = 15
min = 10
• Operators of equal precedence that are non-associative cannot be used next to each
other, for example 1 < 2 > 1 is illegal in PHP. The expression 1 <= 1 == 1 on the other
hand is legal, because the == operator has lesser precedence than the <= operator.
• The following table shows the operators with the highest precedence appear at the top
of the table; those with the lowest appear at the bottom. Within an expression, higher
precedence operators will be evaluated first.
Category Operator Associativity
Unary ! ++ -- Right to left
Multiplicative */% Left to right
Additive +- Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Logical AND &and Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= Right to left
• We can use a string anywhere PHP expects a number. The string is presumed to start
with an integer or floating-point number.
• If no number is found at the start of the string, the numeric value of that string is 0. If
the string contains a period (.) or uppercase or lowercase e, evaluating it numerically
produces a floating-point number.
For example:
"9 Lives" - 1; // 8 (int)
"3.14 Pies" * 2; // 6.28 (float)
"9 Lives." - 1; // 8 (float)
"1E3 Points of Light" + 1; // 1001 (float)
1.102
Web Technologies - I Introduction to HTML, HTTP and PHP
if ($a==$b)
echo "Both string are equal";
echo "if block not executed";
?>
Output:
if block not executed
2. if else Statement:
• The if else statement allows us to execute one block of code if the specified condition is
evaluated to True and another block of code, if it is, evaluated to False.
• The syntax of the if else statement:
if(expression)
Statement
else
Statement
• The alternative syntax for if else statement:
if (condition)
{
// execute if condition evaluates to True…
}
else
{
// execute if condition evaluates to False…
}
• We can enhance the if statement by adding else statement to run an alternative code
block if the condition evaluates to false.
For example 1:
<?php
$var1="php";
$var2="java";
if ($var1 == $var2)
echo "Both the strings are equal";
else
echo "Both the strings are not equal";
?>
Output:
Both the strings are not equal
1.103
Web Technologies - I Introduction to HTML, HTTP and PHP
For example 2:
<?php
$marks=80;
if ($marks >= 60 )
{
echo "You are passed"."<br>";
echo "Your marks= ".$marks."<br>";
echo "First division";
}
else
{
echo "Failed";
}
?>
Output:
You are passed
Your marks= 80
First division
• If we have more than one Boolean condition to test, we can use the if elseif statement.
If we want to execute some code if one of the several conditions are True use the if
elseif else statement.
• The syntax if elseif else statement is given below:
if(condition)
// code to be executed if condition is True;
elseif (condition)
// code to be executed if condition is True;
else
// code to be executed if condition is False;
• The alternative syntax if elseif else statement:
if(condition)
{
// code to be executed if condition is True;
}
elseif(condition)
{
// code to be executed if condition is True;
}
else
{
// code to be executed if condition is True;
}
1.104
Web Technologies - I Introduction to HTML, HTTP and PHP
For example:
<? php
$x = 20;
if($x > 0)
{
echo "$x is greater than zero"
}
else if($x == 0)
{
echo "$x is zero";
}
else
{
echo "$x is less than zero";
}
?>
Output:
20 is greater than zero
• PHP also provide an alternative for conditional and looping control structure. In place
of opening brace colon (:) is used and to close the block endif keyword is used (in this
case).
Syntax:
if(condition);
//code block to be executed if condition is true
//…
else
// code block to be executed if condition is false
// …
endif;
For example:
<?php
$a=7
if ($a == 5):
echo "a equals 5";
echo "...";
elseif ($a == 6):
echo "a equals 6";
echo "!!!";
1.105
Web Technologies - I Introduction to HTML, HTTP and PHP
else:
echo "$a is neither 5 nor 6";
endif;
?>
Output:
a is neither 5 nor 6
Nested if Statement:
• When one if statement contains another if statement then such type of structure is
known as nested if. Nested if structure also helps in multi-way decision making where
one condition depends on other.
• The nested if statement has the following form/syntax:
if(condition 1)
{
if(condition 2) / * nested if */
{
Statement(s);
}
else
{
Statement(s);
}
}
else
{
Statement(s);
}
Example for nested if statement:
<!DOCTYPE html>
<html>
<body>
<?php
$a=10;
$b=20;
if($a==10)
{
if($b==20)
1.106
Web Technologies - I Introduction to HTML, HTTP and PHP
{
echo "The addition is: ".($a+$b);
}
}
?>
</body>
</html>
Output:
The addition is: 30
3. switch Statement: [April 19]
• Consider the case where value of a single variable may determine one of a number of
different choices (e.g., the variable holds the username and we want to do something
different for each user). The switch statement is designed for this situation.
• Switch statement is used to compare the value with multiple cases or values. All
statements in a matching case are executed up to the first break keyword.
• If none match and ‘default’ is given, all statements following the default keyword are
executed up to the first break keyword.
• The syntax for switch statement:
switch(variable)
{
case value1:
// code block 1
break;
case value2:
// code block 2
break;
default:
// default code block
}
• The alternative syntax for switch statement is:
switch(variable):
case value1:
// code block 1
break;
case value2:
// code block 2
break;
default:
// default code block
endswitch;
1.107
Web Technologies - I Introduction to HTML, HTTP and PHP
For example:
<?php
$var=date("D");
switch($var)
{
case "Sun":
echo "It is Sunday.";
break;
case "Mon":
echo "It is Monday.";
break;
case "Tue":
echo "It is Tuesday.";
break;
case "Wed":
echo "It is Wednesday.";
break;
case "Thu":
echo "It is Thursday.";
break;
case "Fri":
echo "It is Friday.";
break;
case "Sat":
echo "It is Saturday.";
break;
default:
echo "Something wrong";
?>
Output:
It is monday
1.7.6 Loops
• Loop in PHP is used to execute a statement or a block of statements, multiple times
until and unless a specific condition is met.
• Loops in PHP help the user to save both time and effort of writing the same code
multiple times.
1.108
Web Technologies - I Introduction to HTML, HTTP and PHP
• In short, loops in PHP are used to execute the same block of code a specified number
of times. PHP supports the following four loop types:
1. while loop loops through a block of code if and as long as a specified condition is
true.
2. do while loop loops through a block of code once and then repeats the loop as long
as special condition is true.
3. for loop loops through a block of code a specified number of times.
4. for each loop loops through a block of code for each element in an array.
• Let us see above loops in detail.
1. while Loop: [April 19]
• The while loop is the simplest loop in PHP. He while loop will execute block of code
until certain condition is met.
• The while loop statement checks the expression at the beginning of each iteration. If
the expression evaluates to true, the code block inside the curly braces is executed. If
the expression evaluates to false, the loop exits.
Syntax:
while(expression)
{
//code block to be executed
}
• The following program displays number from 1 to 10.
<?php
$i=1;
while($i<=10)
{
echo $i . " ";
$i++;
}
?>
Output:
1 2 3 4 5 6 7 8 9 10
• The alternative syntax for while statement is:
while(expression):
// Statement;
...;
endwhile;
1.109
Web Technologies - I Introduction to HTML, HTTP and PHP
For example:
<?php
$i=1;
while($i<=10):
echo $i . " ";
$i++;
endwhile;
?>
Output:
1 2 3 4 5 6 7 8 9 10
2. do while Loop:
• A do while loop in PHP works same as while, except that the expression is evaluated at
the end of each iteration.
• The syntax for do while loop:
do{
//code block to be executed
}while(expression);
• Use a do while loop to ensure that the loop body is executed at least once - it then will
repeat the loop as long as a condition is true.
• The following program displays number from 1 to 10 using do while loop:
<?php
$i=1;
do {
echo $i . " ";
$i++;
} while($i<=10);
?>
3. for Loop:
• The for loop is used when we know how many times we want to execute a statement
or a block of statements.
Syntax:
for(init_expr; condition_expr;increment_expr)
{
//code block to be executed
}
• At the beginning, the counter initialization occurs only once. Each time through the
loop, the expression condition is tested.
• If it is true, the body of the loop is executed; if it is false, the loop ends. The expression
increment/decrement is evaluated after the loop body runs.
1.110
Web Technologies - I Introduction to HTML, HTTP and PHP
• The first form loops over the array given by array_expression. On each iteration, the
value of the current element is assigned to $value and the internal array pointer is
advanced by one (so on the next iteration, you'll be looking at the next element).
• The second form will additionally assign the current element's key to the $key variable
on each iteration.
For example:
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $value)
{
echo $value . “ ”;
}
?>
Output:
1 2 3 4
• The alternative syntax for foreach loop:
foreach (array_expression as $value):
// ...
endforeach;
• Just like other programming languages, PHP also have two statements break and
continue to control the loop. These statements are known as jumping statement or
flow of transfer in the program.
1. break Statement: [April 17]
• The PHP break keyword is used to terminate the execution of a loop prematurely.
• As the break statement encountered inside a loop, it immediately terminated the loop
statement and transferred the control to the next statement, followed by a loop to
resume the execution.
Syntax:
for(…)
{
// Statements;
if(condition)
{
break;
}
// Statements; /* Never executed after executing break statement*/
}
1.112
Web Technologies - I Introduction to HTML, HTTP and PHP
• If the condition is true, the break statement will be executed and the loop will be
break. It will skip all the remaining statement of the loop.
• In the following code, $i never reach a value of 6, because the loop is stopped once it
reaches 5:
<?php
$i=1;
while($i<=10)
{
echo $i . " ";
if($i == 5)
break;
$i++;
}
?>
Output:
1 2 3 4 5
• Optionally, we can put a number after the break keyword, indicating how many levels
of loop structures to break out of. In this way, a statement buried deep in nested loops
can break out of the outermost loop. For example:
<?php
$i = 1;
while ($i <= 10)
{
$j = 1;
while ($j <= 10)
{
if ($j == 5)
break 2; // breaks out of two while loops
$j++;
}
$i++;
}
echo $i;
echo “<br>”;
echo $j;
?>
Output:
1
5
1.113
Web Technologies - I Introduction to HTML, HTTP and PHP
1.114
Web Technologies - I Introduction to HTML, HTTP and PHP
1.115
Web Technologies - I Introduction to HTML, HTTP and PHP
PRACTICE QUESTIONS
Q.I Multiple Choice Questions:
1. HTML stands for,
(a) HTTP Markup Language (b) Hypertext Middle Language
(c) HyperText Markup Language (d) Hidden Middle Language
2. Which HTML5 documents may contains an element, which is used to set the
header section of a document?
(a) header (b) footer
(c) section (d) drive
3. Which contains the navigation menu or other navigation functionality for the
page?
(a) section (b) header
(c) nav (d) aside
4. Which tag is used to encapsulate navigation and then style the elements
appropriately as menu items?
(a) ul (b) li
(c) nav (d) both ul and li
5. Which is use to merge two or more columns into a single column?
(a) rowspan (b) colspan
(c) columnspan (d) Column
6. Text fields are one line areas that allow the user to input text,
(a) Text (b) TextField
(c) Fieldset (d) Textarea
7. Which specifies the width that should appear between table cells?
(a) table-layout (b) border-collapse
(c) caption-side (d) border-spacing
8. Find output of following code:
<?php
$a= “9 Lives.” –1;
var_dump($a);
?>
(a) int (8) (b) 8 Lives
(c) Error (d) 9 Lives
9. PHP was written in the which programming language by Rasmus Lerdorf in 1994.
(a) Unix (b) C
(c) C++ (d) QBASIC
1.116
Web Technologies - I Introduction to HTML, HTTP and PHP
1.118
Web Technologies - I Introduction to HTML, HTTP and PHP
1.120
Web Technologies - I Introduction to HTML, HTTP and PHP
37. The CSS font-family property defines the ______ to be used for the HTML element.
38. In CSS, the term ______ is used when talking about design and layout.
Answers
1. Canvas 2. anchor <a> tag 3. Manifest 4. <ol> 5. global
6. <br> 7. semicolons (;) 8. lexical 9. White space 10. variable
11. server 12. HTML 13. semantics 14. open 15. .php
16. browser 17. client-server 18. .css 19. Scope 20. link
21. comment 22. <nav> 23. request 24. assignment 25. $
26. <article> 27. CSS 28. increment 29. HTTP 30. true
31. constant 32. <aside> 33. <style> 34. color 35. operations
36. Identifiers 37. font 38. box model
Q.III State True or False:
1. HTML is a platform-dependent language.
2. The singular tag is also known as a stand-alone tag or empty tag.
3. The vlink attribute specifies the color of visited links in a document.
4. The <sub> tag defines smaller text.
5. In ordered list<ol>tag, each list item starts with the <li> tag.
6. PHP is a server side scripting language which is used to create dynamic and
interactive web pages.
7. PHP script is executed much slower than other scripting languages such as JSP and
ASP.
8. A PHP program consists of tokens.
9. A constant value cannot change during the execution of the script.
10. The bool() function is used to test whether value is Boolean or not.
11. A constant is case-sensitive by default.
12. In PHP the const keyword also defines constants at compile time.
13. Web applications are usually based on the client-server architecture.
14. PHP support unsigned integers.
15. Objects are the special instances of the classes that are created by user.
16. A PHP script starts with <? php and ends with ?>.
17. PHP is a server side scripting language that is embedded in HTML.
18. PHP is a not case sensitive language.
19. The <article> element represents an independent article in a web page.
20. Semantic elements mean elements with a meaning. Semantic elements have a
simple and clear meaning for both, the browser and the developer.
1.123
Web Technologies - I Introduction to HTML, HTTP and PHP
21. CSS is used to control the style of a web document in a simple and easy way.
22. An external style sheet is used to define the style for many pages.
23. The Web server requests for the web document then the Web browser (clients)
accepts and response to the request made by a Web browser for a web document.
24. The <section> element defines a section in a document. A section is a thematic
grouping of content, typically with a heading.
25. An HTTP "server" is a program ( Web server) that accepts connections in order to
serve HTTP requests by sending HTTP response messages.
26. By default, a constant is case-sensitive.
27. In PHP, a variable starts with the $ sign, followed by the name of the variable.
28. You can put your CSS rules into an HTML document using the <style> element. This
tag is placed inside the <head>...</head> tags. "
29. The <section> element specifies independent, self-contained content.
30. The CSS box model is essentially a box that wraps around every HTML element.
31. PHP is a server side scripting language.
Answers
1. (F) 2. (T) 3. (T) 4. (F) 5. (T) 6. (T) 7. (F) 8. (T) 9. (T) 10. (F)
11. (T) 12. (T) 13. (T) 14. (F) 15. (T) 16. (T) 17. (T) 18. (F) 19. (T) 20. (T)
21. (T) 22. (T) 23. (F) 24. (T) 25. (T) 26. (T) 27. (T) 28. (T) 29. (F) 30. (T)
31. (T)
Q.IV Answer the following Questions:
(A) Short Answer Questions:
1. What is HTML?
2. What is PHP?
3. Define Web browser.
4. Define Web server.
5. Give any two features of HTML?
6. What is the use of PHP?
7. What is CSS?
8. Give the purpose of HTML?
9. Which HTML tag is used to add video in page?
10. What is HTTP?
11. HTTP uses client-server architecture. Justify trey or false.
12. Which semantic elements used by HTML5 in web page.
13. Explain the role of web browser and web server.
14. Give the ways to add CSS in
15. How to add PHP in HTML page?
1.124
Web Technologies - I Introduction to HTML, HTTP and PHP
1.125
Web Technologies - I Introduction to HTML, HTTP and PHP
October 2016
1. Discuss the scope of a variable in PHP with an example. [5 M]
Ans. Refer to Section 1.7.2.3.
2. What is the role of web browser and web server? [3M]
Ans. Refer to Section 1.3.1 and 1.3.2.
3. Explain the concept of variable variables with an example. [2 M]
Ans. Refer to Section 1.7.2.1.
April 2017
1.127
Web Technologies - I Introduction to HTML, HTTP and PHP
April 2019
1.128
CHAPTER
2
Function and String
Objectives…
To understand Basic Concepts of Function and String in PHP
To learn Function Declaration, Types, Definition, Arguments etc.
To learn Basic Concepts of Strings like Declaration, String Functions, etc.
2.0 INTRODUCTION
• A function in PHP is a block of statements that can be used repeatedly in a program. A
string in PHP is a collection of characters.
• A function in PHP is a reusable block of code that performs a specific action or task. It
takes input from the user in the form of parameters, performs certain actions, and
gives the output.
• Functions can either return values when called or can simply perform an operation
without returning any value.
2.1
Web Technologies - I Function and String
For example:
<?php
function welcome()
{
echo “Hi, welcome to Schools of Web.”;
}
welcome(); // Function welcome() is called here.
?>
Output:
Hi, welcome to Schools of Web.
• Explanation of above Program: The function welcome() is defined. In this stage
nothing happens. When the function is called, the interpreter finds it and enters into
it, executes the statement(s) inside it. Here it prints the sentence “Hi, welcome to
Schools of Web.”.
2.1.3 Function Parameters [Oct. 18, April 19]
• Information can be passed to functions through arguments. Arguments (or
parameters) are specified after the function name, inside the parentheses ().
• If a function accepts more than one parameter, each parameter has to be separated by
a comma (,). The arguments are evaluated from left to right.
2.3
Web Technologies - I Function and String
For example:
function strcat($left, $right)
{
$combined_string = $left . $right;
echo $combined_string;
}
• PHP supports passing arguments by value (the default), passing by reference, and
default argument values. Variable-length argument lists are also supported.
• By default, function arguments are passed by value (so that if the value of the
argument within the function is changed, it does not get changed outside of the
function).
• To allow a function to modify its arguments, they must be passed by reference. When
a function argument is passed by reference, changes to the argument also change the
variable that was passed in.
• We can pass an argument by reference by adding an ampersand (&) to the variable
name in either the function call or the function definition.
For example:
<?php
function doubler(&$value)
{
$value = $value * 2;
}
$a = 3;
doubler($a);
echo $a; // Outputs 6
?>
• A function cannot return multiple values, but similar results can be obtained by
returning an array.
<?php
function day_name()
{
$day1 = ”Monday”;
$day2 = ”Tuesday”;
$day3 = ”Wednesday”;
return array($day1, $day2, $day3);
}
$days = day_name();
echo $days[0] . ” ” . $days[1] . ” ” . $days[2];
?>
Output:
Monday Tuesday Wednesday
• Function day_name() creates an array that has three elements in it and returns to its
caller.
• When the function is called, the function returns the array to the caller assigns it in
the $days variable. The next line prints the values of the array elements.
Example:
<?php
function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>
Output:
Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.
• The default value must be a constant expression, not (for example) a variable, a class
member or a function calls.
• Note that when using default arguments, any defaults should be on the right side of
any non-default arguments; otherwise, things will not work as expected.
• We can pass any number of arguments to the function. If we do not pass any value to
the parameter, the parameter remains unset and a warning is displayed for each of
them.
Example:
<?php
function xyz($a, $b, $c)
{
if (isset ($a))
echo “a is set <br>”;
2.7
Web Technologies - I Function and String
if (isset ($b))
echo “$b is set <br>”;
if (isset ($c))
echo “c is set <br>”;
}
echo “with 3 arguments <br>”;
xyz(1, 2, 3);
echo “with 2 arguments<br>”;
xyz(1, 2);
echo “with 1 argument<br>”;
xyz(1);
?>
Output:
with 3 arguments
1 is set
2 is set
3 is set
with 2 arguments
1 is set
2 is set
Warning: Missing argument 3 for xyz()
with 1 argument.
1 is set.
Warning: Missing argument 2 for xyz()
Warning: Missing argument 3 for xyz()
• In above program:
1. To check if parameter is missing or not, we can use built in function isset().
2. The isset() functions returns true if the value is set to the argument passed to it,
otherwise it returns result as false. [April 16]
• PHP supports the concept of variable functions. This means that we can call function
based on value of a variable.
• If a variable name has round parentheses appended to it, PHP will look for a function
with the same name as whatever the variable evaluates to, and will attempt to execute
it.
• The variable function does not work with echo(), print(), unset(), isset() language
constructs.
• PHP allows us to store a name of a function in a string variable and use the variable to
call the function. Variable functions are useful in cases that we want to execute
functions dynamically at run-time.
• The following example demonstrates how to use variable functions:
<?php
function find_max($a,$b)
{
return $a > $b? $a: $b;
}
function find_min($a,$b)
{
return $a < $b? $a: $b;
}
$f = 'find_max';
echo $f(10,20); // Outputs 20
$f = 'find_min';
echo $f(10,20); // Outputs 10
?>
• First, we defined two functions namely, find_min() and find_max() . Then, we called
those function based on the value of string variable $f.
• Notice that we need to put parentheses after the variable in order to call the function
specified by the value of the variable.
2.5.2 Anonymous Function [Oct. 17, 18, April 18]
• In PHP we can define a function that has no specified name called as an anonymous
function or a closure.
• An anonymous function also called as lambda function. We often use anonymous
functions as values of callback parameters.
• The anonymous function is created using the create_function(). It takes following two
parameters:
o First parameter is the parameter list for anonymous functions
o Second parameter contains the actual code of the function. The function name is
randomly generated and returned.
2.9
Web Technologies - I Function and String
• The syntax for anonymous function (or lambda function) using reate_function():
$f_name = create_function(args_string, code_string);
For example:
<?php
$add = create_function('$a,$b', 'return($a+$b);');
$r = $add(2,3);
echo $r;
?>
Output:
5
2.6 TYPES OF STRINGS IN PHP [April 16, 17, 18, Oct. 16, 18]
• PHP string is a sequence of characters and used to store and manipulate text.
• A “string” of text can be stored in a variable in much the same way as a numeric value
but the assignment must surround the string with quote marks (“…” or ‘….’) to denote
its beginning and end like "Hello world!" or ‘Hello world!’.
• Strings are very useful to store names, passwords, address, and credit-card number
and so on. For that reason, PHP has large number of functions for working with
strings.
• There are three different ways to write string in PHP as explained below:
1. Single-Quoted String:
• In this method, string is enclosed with single quotation mark (‘…’). It is the easiest way
to specify string in PHP.
For Example: ‘Hello PHP’ ‘Computer Basics’ ‘Pune’ etc.
• The limitation of single-quoted string is that variables are not interpolated.
For example:
<?php
$name = ‘Amar;
$str = ‘Hello $name’; // Single-quoted string
echo $str;
?>
Output:
Hello $name
• In the above output the value of variable $name is not printed.
2. Double-Quoted String:
• It is the most commonly used quote to express string. In this method, characters are
enclosed with double quotation marks (“…”).
• PHP interpreter interprets variables and special characters inside double quotes.
2.10
Web Technologies - I Function and String
• In the following example, the above example is re-written using double quotes.
For example:
<?php
$name = ‘PHP’;
$str = “Hello $name”; // Double-quoted string
echo $str;
?>
Output:
Hello PHP
3. Here Documents:
• Single-quoted and double-quoted strings allow string in single line. To write multiline
string into a program heredoc is used.
Rules of using heredoc Syntax:
(i) Heredoc syntax begins with three less than signs (<<<) followed by identifier
(a user defined name). The identifier can be any combination of letters, numbers,
underscores but the first character must be a letter or an underscore.
(ii) The string begins in the next line and goes as long as it requires.
(iii) After the string, the same identifier that is defined after the (<<<) signs in the first
line should be placed at the end. Nothing can be added in this last line except a
semicolon after the identifier and it is optional.
(iv) Space before and after <<< is essential.
Syntax:
$var_name = <<< identifier
// String statement
// String statements
identifier;
For example:
<?php
$str = <<< EOD
PHP is suited for web development and can be embedded into HTML.\n
PHP is server-side scripting language
EOD;
echo $str;
?>
Output:
PHP is suited for web development and can be embedded into HTML. PHP is
server-side scripting language.
4. Nowdoc syntax:
• If heredoc syntax works similar to double quote, then nowdoc syntax works similar to
single quote.
• Like single quote, no variable inside the nowdoc is interpreted.
2.11
Web Technologies - I Function and String
2. Complex Syntax:
• In this way, variable is wrapped with { and }.
For example:
<?php
$a=1;
echo “You are the {$a}st employee”;
?>
Output:
You are the 1st employee.
• Without { } the PHP parser consider $ast as a variable and displays Noticed undefined
variable: $ast on line 3.
Character Escaping:
• Escape sequences are used for escaping a character during the string parsing. In PHP,
an escape sequence starts with a backslash \ followed by the character which may be
an alphanumeric or a special character.
• A single-quoted string only uses the escape sequences for a single quote (‘…’). All the
escape sequences like \r or \n, will be output as specified instead of having any special
meaning.
• Single quotes are used in the special case is that if we to display a literal single-quote,
escape it with a backslash (\) and if we want to display a backslash, we can escape it
with another backslash (\\).
• Escape sequences also apply to double-quoted strings. Escape sequences for double-
quoted strings are given below:
Escape Sequence Character Represented
\″ double quotes
\n newline
\r carriage return
\t tab
\\ Backslash
\$ Dollar sign
\{ left brace
\} right brace
\[ left square bracket
\] right square bracket
\o through \777 ASCII character represented by octal value.
\xo through \XFF ASCII character represented by hex value.
2.13
Web Technologies - I Function and String
For example:
if(! print("Hello, world"))
{
die("you're not listening to me!");
}
Output:
Hello, world
3. printf() Function:
• The printf() function outputs a formatted string. The first argument to printf() is the
format string. The remaining arguments are the values to be substituted in.
Format Modifiers:
• Each substitution marker in the template consists of a % sign, followed by modifiers
and ends with a type specifier.
• Following sequence of modifiers is necessary.
(i) A padding specifier denoting the character to use to pad the result to the
appropriate string size. Padding with spaces is the default.
(ii) A sign minus (−) forces the string to be left justified. Default is right justified.
(iii) The minimum length of the element. If the result is less than this number of
characters, then padded with some value.
(iv) For floating point numbers, it gives or dictates how many decimal digits will be
displayed.
Type Specifiers:
• The type specifier tells printf() what type of data is being substituted. There are
different types as shown below:
Specifier Meaning
B The argument is integer and is displayed as a binary number.
C The argument is integer and is displayed as a character with that
value.
d or I The argument is integer and is displayed as a decimal number.
e, E or f Argument is double, displayed as a floating point number.
g or G Argument is double with precision, displayed as floating point
number.
O Argument is integer and displayed as a floating point number.
S Argument is string and displayed as such.
U Argument is an unsigned integer and is displayed as decimal.
x Argument is integer, displayed in hexadecimal with lowercase letters
X Argument is an integer and displayed as a hexadecimal with
uppercase letter.
2.15
Web Technologies - I Function and String
Some examples:
printf(‘%2f’, 27.452);
Output: 27.45
printf('The hex value of %d is %x', 214, 214);
Output: The hex value of 214 is d6
printf('Bond. James Bond. %03d.', 7);
Output: Bond. James Bond. 007.
$month = 2; $day = 15; $year = 2002;
printf('%02d/%02d/%04d', $month, $day, $year);
Output: 02/15/2002
printf('%.2f%% Complete', 2.1);
Output: 2.10% Complete
printf('You\'ve spent $%5.2f so far', 4.1);
Output: You've spent $ 4.10 so far
4. print_r() Function:
• The print_r() is useful for debugging purpose. It prints the contents of array, objects
and other things in more or less human-readable form.
For example:
$a = array('name' => 'Amar', 'age' => 35);
print_r($a);
Output:
Array
(
[name] => Amar
[age] => 35
)
5. var_dump() Function:
• The var_dump() function is used to display structured information (type and value)
about one or more variables.
For example:
<?php
var_dump(14) . “<br>”; // <br> is used for line change
var_dump(“Hello”) . “<br>”;
var_dump(25, “ty1”);
?>
2.16
Web Technologies - I Function and String
Output:
Int(14)
String(5) “Hello”
Int(25)string(3) “ty1”
• Boolean values and NULL are not meaningfully displayed by print_r().
For example:
print_r(true); // Outputs 1
print_r(false); // Nothing is displayed
print_r(null); // Nothing is displayed
• For this reason, var_dump() is preferable to print_r() for debugging. The var_dump()
function displays any PHP value in more human-readable format.
For example:
var_dump(true);
Output: bool(true)
var_dump(false);
Output: bool(false);
var_dump(null);
Output: bool(null);
var_dump(array('name' => Amar, 'age' => 35));
Output:
array(2)
{
["name"]=>string(4) "Amar"
["age"]=>int(35)
}
• In recursive structures, print_r() loops infinitely while var_dump() cuts off after
visiting the same element three times.
Accessing Individual Characters:
• We can access the individual character of a string using [].
For example:
<?php
$str = "Hello";
echo $str[0]; // H
?>
2.17
Web Technologies - I Function and String
Changing Case:
• PHP has several functions for changing the case of strings. Each function takes a string
as an argument and returns a copy of that string, appropriately changed.
• PHP has following functions for changing the case of strings:
1. strtolower() and strtoupper() operate on entire string.
2. ucfirst() operates only on first character of the string.
3. ucwords() operates on first character of each word of the string. [April 19]
For example:
$S1 = strtolower (“Hello World”); // $S1 = “hello world”
$S2 = strtoupper (“Hello World”); // $S2 = “hello WORLD”
$S3 = ucfirst (“hello world”); // $S3 = “Hello world”
$S4 = ucwords (“hello world”); // $S4 = “Hello World”
For example:
$input = <<< end
"Programming PHP" by Nirali
end;
echo htmlentities($input);
// "Programming PHP" by Nirali
echo htmlentities($input, ENT_QUOTES);
// "Programming PHP" by O'Nirali
echo htmlentities($input, ENT_NOQUOTES);
// “Programming PHP” by Nirali
• Charset is optional. It is a string that specifies which character-set to use. The default is
UTF-8.
(ii) htmlspecialchars() Function:
• The htmlspecialchars() function converts special characters to HTML entities.
• Certain characters have special significance in HTML, and should be represented by
HTML entities if they are to preserve their meanings. This function returns a string
with these conversions made.
• If we require all input substrings that have associated named entities to be translated,
use htmlentities() instead.
• The translations performed are:
o & (ampersand) becomes &
o " (double quote) becomes "
o ' (single quote) becomes '
o < (less than) becomes <
o > (greater than) becomes >
• If we have an application that displays data that a user has entered in a form, we need
to run that data through htmlspecialchars( ) before displaying or saving it.
• For example, if user enters a string like "angle < 30", the browser will think the special
characters are HTML, and we will have a garbled page.
Syntax:
string htmlspecialchars(string str[, int quote_style][, String charset])
• The syntax and meaning of quote_style and charset are same as htmlentities().
For example:
<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // <a href='test'>Test</a>
?>
2.20
Web Technologies - I Function and String
• The similar_text() function calculates the similarity between two strings in percent. It
returns the number of characters that its two string arguments have in common.
[April 18]
Syntax: int similar_text (string $first, string $second [, float &$percent])
• First and second parameter contains first and second string. Third optional parameter
specifies a variable name for storing the similarity in percent.
• The similar_text() function returns the number of characters that its two string
arguments have in common. Hence, third parameter stores the value in percentage.
For example:
<?php
$s1="There";
$s2="Their";
$c=similar_text($s1, $s2, $p);
printf("%d characters in common. Strings are %f percent same", $c, $p);
?>
Output:
4 characters in common. Strings are 80.000000 percent same
• Then levenshtein() function gives how many characters you must add, substitute, or
remove to make them the same.
• The levenshtein() function returns the Levenshtein distance between two strings.
• The Levenshtein distance is the number of characters we have to replace, insert or
delete to transform string1 into string2.
Syntax: int levenshtein(string $str1, string $str2)
For example:
$similarity = levenshtein(“cat”, “cot”);
// $similarity is 1
For example:
<?php
echo substr('abcdef', 1); // bcdef
echo substr('abcdef', 1, 3); // bcd
echo substr('abcdef', 0, 4); // abcd
echo substr('abcdef', 0, 8); // abcdef
echo substr('abcdef', -1, 1); // f
?>
2. substr_replace() Function:
• This function replaces text within a portion of a string.
Syntax: string substr_replace (string $original, string $replacement,
int $start [, int $length])
• The function replaces the part of ‘original’ indicated by the ‘start’ (0 means the start of
the string) and ‘length’ values with the string ‘replacement’.
• If no fourth argument is given, substr_replace( ) removes the text from ‘start’ to the
end of the string.
For example:
<?php
$greeting = "good morning Nirali";
$farewell = substr_replace($greeting, "bye", 5, 7);
echo $farewell;
?>
Output:
good bye Nirali
3. substr_count() Function:
• This function count the number of substring occurrences.
Syntax:
int substr_count(string $big_str, string $small_str
[, int $offset = 0 [int $length]])
• Returns the number of times the small_str substring occurs in the big_str string. Please
note that small_str is case sensitive. ‘offset’ is from where to start counting.
For example:
<?php
$n = 'This is a test';
echo substr_count($n, 'is'); // 2
?>
2.25
Web Technologies - I Function and String
4. substr_compare() Function:
• Comparison of two strings from an offset, up to length characters.
Syntax:
int substr_compare(string $main_str, string $str, int $offset
[, int $length[, bool $case_insensitivity = false ]])
• The substr_compare() compares ‘main_str’ from position ‘offset’ with ’str’ upto ‘length’
characters.
• Returns < 0 if ‘main_str’ from position ‘offset’ is less than ‘str’, > 0 if it is greater than
‘str’, and 0 if they are equal.
For example:
<?php
echo substr_compare("abcde", "bc", 1, 2); // 0
echo substr_compare("abcde", "de", -2, 2); // 0
echo substr_compare("abcde", "bcg", 1, 2); // 0
echo substr_compare("abcde", "BC", 1, 2, true); // 0
echo substr_compare("abcde", "bc", 1, 3); // 1
echo substr_compare("abcde", "cd", 1, 2); // -1
echo substr_compare("abcde", "abc", 5, 1); // warning
?>
5. strrev() Function: [April 18]
• This function takes a string and returns a reversed copy of it.
Syntax: string strrev(string $string)
For example:
<?php
echo strrev("Hello World!");
?>
Output:
!dlroW olleH
6. str_repeat() Function:
• This function takes a string and count and after it, repeats the string that many times.
Syntax: string str_repeat(string $input , int $multiplier)
Returns ‘input’ repeated ‘multiplier’ times.
2.26
Web Technologies - I Function and String
For example:
<?php
$string = "Hello ";
$x = 5;
$result = str_repeat($string, $x);
echo $result;
?>
Output:
Hello Hello Hello Hello Hello
7. str_pad() Function: [April 19]
• The str_pad() function pads a string to a new length.
Syntax:
string str_pad (string $input , int $pad_length
[, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT]])
• This function returns the ‘input’ string padded on the left, the right, or both sides to the
specified padding length.
• If the optional argument ‘pad_string’ is not supplied, the ‘input’ is padded with spaces,
otherwise it is padded with characters from ‘pad_string’ up to the limit.
• Optional argument ‘pad_type’ can be STR_PAD_RIGHT, STR_PAD_LEFT, or
STR_PAD_BOTH. If ‘pad_type’ is not specified it is assumed to be STR_PAD_RIGHT.
For example:
<?php
$input = "PHP";
echo str_pad($input, 10); // "PHP "
echo str_pad($input, 10, "=", STR_PAD_LEFT); // "=======PHP"
echo str_pad($input, 10, "=", STR_PAD_BOTH); // "===PHP===="
echo str_pad($input, 10 , "="); // "PHP======="
?>
• PHP provides several functions to break a string into smaller components. These
functions are explode(), implode(), strtok() and sscanf().
1. explode() Function: [April 19]
• It breaks a string into smaller parts and stores it in an array.
Syntax: array explode (string $delimiter, string $str [, int $limit])
2.27
Web Technologies - I Function and String
3. strtok() Function:
• The strtok() function splits a string into smaller strings (tokens). It gives us new token
each time.
Syntax: string strtok (string $str, string $separator)
• The strtok() function splits a string ‘str’ into smaller strings (tokens), with each token
being delimited by any character from ‘separator’.
• That is, if we have a string like "This is an example string" we could tokenize this string
into its individual words by using the space character as the separator.
• Note that only the first call to strtok() uses the string argument. Every subsequent call
to strtok() only needs the separator to use, as it keeps track of where it is in the current
string.
For example:
<?php
$string = "lastname,email,phone";
$token = strtok($string, ",");
while ($token !== false)
{
echo "$token <br>";
$token = strtok(",");
}
?>
Output:
lastname
email
phone
• In the above program, the character ‘,’ we use as the separator, because we want to
break the string by ‘,’. Inside while loop we display each token of the string. When
there are no more tokens to be return this function returns false.
4. sscanf() Function: [April 16]
• This function in PHP decomposes a string.
• The sscanf() function parses a string into variables based on the format string.
Syntax: sscanf(string,format,arg1,arg2,arg++)
For example:
<?php
$str = "If you divide 4 by 2 you'll get 2";
$format = sscanf($str,"%s %s %s %d %s %d %s %s %c");
print_r($format);
?>
Output:
Array ( [0] => If [1] => you [2] => divide [3] => 4 [4]
=> by [5] => 2 [6] => you'll [7] => get [8] => 2 )
2.29
Web Technologies - I Function and String
3. strstr() Function:
• This function finds the first occurrence of a small string and returns from that small
string onwards.
Syntax: string strstr (string $str, mixed $find)
• Returns part of ‘str’ string the matching point and including the first occurrence of
‘find’ word to the end of ‘str’.
For example:
<?php
$str="w3resource.com";
$newstring = strstr($str,".");
echo $newstring;
?>
Output:
.com
• Few more searching functions are:
1. stristr() : Case-insensitive version of strstr() function.
2. strchr() : Alias of strstr().
3. strrchr() : Find last occurrence of a character in a string.
Decomposing URLs:
• The parse_url() function returns an array of components of a URL:
Syntax: $array = parse_url(url);
For example:
<?php
$bits = parse_url('http://me:[email protected]:8080/
php/test?user=Amar#res');
print_r($bits);
?>
Output:
Array ( [scheme] => http
[host] => example.com
[port] => 8080
[user] => me
[pass] => secret
[path] => /php/test
[query] => user=Amar
[fragment] => res
)
2.31
Web Technologies - I Function and String
• Regular expression is string that represents a pattern. PHP provides two different
types of regular expressions:
1. POSIX Regular Expression and
2. Perl compatible Regular Expression.
• POSIX regular expressions are less powerful, and sometimes slower, than the Perl-
compatible functions, but can be easier to read.
• There are following three uses of the regular expressions:
1. matching: To match the given pattern.
2. substituting: Substitution of new text for the matching text.
3. splitting: Splitting a string into an array of smaller chunks.
• Regular expression functions accept two parameters. First is pattern and second is
string to be matched with pattern.
For example:
ereg(‘students’, ‘Hello students’);
// returns true
• Some special characters are also used to perform the matching like ∧ (start of string), $
(end of string), · (matches any single character).
• Regular expressions are case-sensitive by default. If we want case-insensitive then use
eregi().
1. For matching : The ereg() and eregi() functions are useful.
2. For replacing : The ereg_replace() is used. This function takes the pattern and
replacement string and a string in which to search and returns
replace string.
3. For splitting : The split() is use to divide a string into smaller chunks, which
are returned as an array.
• Let us see some functions in detail.
1. ereg() Function: [Oct. 17]
• The ereg() function is used for regular expression match.
Syntax: int ereg (string $pattern , string $input_str [, array &$regs])
• The first parameter ‘pattern’ is a regular expression. The function searches an
‘input_str’ for matches to the regular expression given in ‘pattern’ in a case-sensitive
way.
• If matches are found for parenthesized substrings of ‘pattern’ and the function is
called with the third argument ‘regs’, the matches will be stored in the elements of the
array ‘regs’.
2.32
Web Technologies - I Function and String
• $regs[1] will contain the substring which starts at the first left parenthesis; $regs[2]
will contain the substring starting at the second, and so on. The $regs[0] will contain a
copy of the complete string matched.
• Returns the length of the matched string if a match for ‘pattern’ was found in input_str
or false if no matches were found or an error occurred.
• If the optional parameter ‘regs’ was not passed or the length of the matched string is 0,
this function returns 1.
• The following example takes a date in ISO format (YYYY-MM-DD) and prints it in
DD.MM.YYYY format:
For example:
<?php
$date = "2015-04-12";
if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs))
{
echo "$regs[3].$regs[2].$regs[1]";
}
else
{
echo "Invalid date format: $date";
}
?>
Output:
12.04.2015
• To specify a set of acceptable characters in your pattern, we can either build a
character class yourself or use a predefined one.
• In PHP we can create our own character class by enclosing the acceptable characters
in square brackets.
For example:
ereg(‘C[aeiou]t’, ‘cut) // returns true
ereg(‘c[aeiou]t’, ‘crt’) // returns false
ereg('[0-9]%', 'we are 25% complete'); // returns true
• In character classes ‘∧
∧’ is used for negation.
For example:
ereg(‘c[∧aeiou]t’, ‘cut’) // returns false
• In regular expressions a caret (^) at the beginning of a regular expression indicates
that it must match the beginning of the string.
2.33
Web Technologies - I Function and String
For example:
ereg(‘^PHP’, ‘I am a PHP programmer’) // returns false
ereg(‘^PHP’, ‘PHP programmer’) // returns true
• Similarly, a dollar sign ($) at the end of a regular expression means that it must match
the end of the string
For example:
ereg(‘PHP$’, ‘Programming in PHP’) // returns true
• We can define a range of characters with a hypen (−)
For example:
ereg(‘c[a-z]t’, ‘cat’); // returns true
‘/’ (pipe) character is used to specify alternatives in a regular expression.
ereg(‘A|B’, ‘A’) // returns true
• To specify a repeating pattern, we can use quantifiers. Following table lists qualifiers:
Quantifier Meaning
? 0 or 1
* 0 or more
+ 1 or more
{n} exactly n times
{n, m} atleast n, no more than m times
{n, } atleast n times.
For example:
ereg(‘ca+t’, ‘caaat’); // true
ereg(‘ca*t’, ‘ct’); // true
ereg(‘ca+t’, ‘ct’); // false
2. ereg_replace() Function:
• The ereg_replace() function takes a ‘pattern’, a ‘replacement’ string, and a ‘string’ in
which to search.
• If ‘pattern’ found in the string ‘string’ then it is replaced by the string ‘replacement’.
This function returns the modified string.
Syntax:
string ereg_replace(string $pattern, string $replacement, string $string)
For example:
<?php
$num = "7";
$str = ereg_replace("seven", $num, "There are seven days in a week");
echo $str;
?>
Output:
There are 7 days in a week
• The eregi_replace() function is a case-insensitive form of ereg_replace().
2.34
Web Technologies - I Function and String
For example:
preg_match('#PHP#', 'I am a PHP programmer'); // returns true
echo preg_replace('/,/', '+', 'a,b,c'); // Displays a+b+c
print_r(preg_split('/-/', '12-04-2015'));
Output:
Array ( [0] => 12 [1] => 04 [2] => 2015 )
PRACTICE QUESTIONS
Q.I Multiple Choice Questions:
1. The [:alpha:] can also be specified as,
(a) [A-Za-z0-9] (b) [A-za-z]
(c) [A-z] (d) [a-z]
2. A function in PHP which starts with double underscore is known as,
(a) Magic Function (b) Inbuilt Function
(c) Default function (d) User Defined Function
3. A function name always begins with the keyword,
(a) fun (b) def
(c) function (d) None of mentioned
4. A variable $str is set to "HELLO WORLD", which of the following script returns it
title case,
(a) echo ucwords($str) (b) echo ucwords(strtolower($str)
(c) echo ucfirst($str) (d) echo ucfirst(strtolower($str)
5. How many types of functions are available in PHP?
(a) 5 (b) 4
(c) 3 (d) 2
6. POSIX stands for,
(a) Portable Operating System Interface for Unix
(b) Portable Operating System Interface for Linux
(c) Portative Operating System Interface for Unix
(d) Portative Operating System Interface for Linux
7. The strstr [egg] function selects a substring by its,
(a) Numerical value (b) Content
(c) Position (d) zero
8. Which function compares the two strings s1 and s2, ignoring the case of the
characters?
(a) strtolower() (b) toLowerCase()
(c) strcasecmp() (d) lc()
9. Which function can be used to compare two strings using a case-insensitive binary
algorithm?
(a) strcmp() (b) strcmp()
(c) strcasecmp() (d) stristr()
2.36
Web Technologies - I Function and String
10. Which PHP function searches for a specific text within a string?
(a) strpos() (b) strposition()
(c) strrev( (d) str_replace()
11. What will be the output of PHP code? <?php echo str_pad("Salad", 5)." is good."; ?>
(a) SaladSaladSaladSaladSalad is good (b) is good SaladSaladSaladSaladSalad
(c) is good Salad (d) Salad is good
12. Which of the following is not a built-in function in PHP?
(a) print_r() (b) fopen()
(c) fclosed() (d) gettype()
13. Which of the following is not a Built-in String functions in PHP?
(a) strlen() (b) str_replace()
(c) strpos() (d) strreverse()
14. Which one of the following functions will convert a string to all uppercase?
(a) strtoupper() (b) uppercase()
(c) str_uppercase() (d) struppercase()
15. Why trim() function is used in PHP?
(a) to remove whitespaces (b) to remove lowercase alphabet
(c) to remove uppercase alphabet (d) to remove underscore
16. The function without a name is called as,
(a) lambda function (b) anonymous function
(c) Both 1 and 2 (d) not of the above
17. In PHP for approximate equality, ________ functions are used.
(a) soundex() (b) metaphone()
(c) levenshtein() (d) Both 1 and 2
(e) All of the above
18. Which function breaks a string into smaller parts and stores it in an array?
(a) implode() (b) explode( )
(c) strtok( ) (d) sscanf( )
19. What is output? Echo strrpos("I am a PHP programmer", "am");
(a) 1 2 (b) 2 3
(c) 3 16 (d) 4 17
20. What is the output? ereg(‘ca+t’, ‘ct’);
(a) True (b) False
(c) Error (d) Exception occurs
21. Which is not string-searching functions in PHP?
(a) strspn() (b) strrpos()
(c) strstr() (d) strev()
2.37
Web Technologies - I Function and String
Answers
1. function 2. passed by value 3. return 4. isset() 5. create_function()
6. heredoc 7. curly { } 8. Anonymous 9. Nowdoc 10. htmlentities()
11. strlen() 12. repeatedly 13. call 14. reference 15. strrev()
16. default 17. variables 18. lambda 19. global 20. regular
21. substr() 22. self-contained
Q.III State True or False:
1. Function names are case-insensitive.
2. A function can return a value using the return statement, may be by returned,
including file and objects.
3. PHP does not support for variable-length argument lists in user-defined functions.
4. The func_get_arg( )returns specific arguments from the parameters.
5. Anonymous function is a function with any user defined name.
6. An anonymous function also called as lambda function.
7. Interpolation is the process of replacing variable names in the string with the
values of those variables.
8. The var_dump() function is used to display information about functions.
9. The ucfirst() operates only on first word of the string.
10. The split() function uses a regular expression to divide a string into smaller
chunks.
11. The code inside a function is not executed until the function is called.
12. After the function execution is completed, the program control returns to the point
where the function was called.
13. The variable functions mean that we can call function based on value of a
variable.
14. The trim() function returns the string with whitespaces removed from the
beginning only.
15. To create a function in PHP its name should start with keyword function and all
the PHP code should be put inside { and } braces.
16. A function can return a value using the return statement.
17. In PHP, arguments are usually passed by value, which means that a copy of the
value is used in the function and the variable that was passed into the function
cannot be changed.
18. The PHP strpos() function searches for a specific text within a string.
19. Information can be passed to functions through arguments.
20. We can create an anonymous function using create_function().
21. To check if parameter is missing or not, we can use PHP built in isset() function.
22. We put multiline strings into the program with a heredoc. The <<< identifier tells
the PHP parser that we are writing a heredoc.
23. As with variable variables, we can call a function based on the value of a variable.
2.40
Web Technologies - I Function and String
24. PHP functions can return only a single value with the return keyword.
25. In PHP, regular expressions are strings composed of delimiters, a pattern and
optional modifiers.
26. To specify a default parameter, assign the parameter value in the function
declaration.
27. 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.
28. As with variable variables, we can call a function based on the value of a variable.
29. A regular expression is a string that represents a pattern.
Answers
1. (T) 2. (F) 3. (F) 4. (T) 5. (F) 6. (T) 7. (T) 8. (F) 9. (F) 10. (T)
11. (T) 12. (T) 13. (T) 14. (F) 15. (T) 16. (T) 17. (T) 18. (T) 19. (T) 20. (T)
21. (T) 22. (T) 23. (T) 24. (T) 25. (T) 26. (T) 27. (T) 28. (T) 29. (T)
Q.IV Answer the following Questions:
(A) Short Answer Questions:
1. What is function?
2. What is string?
3. Which keyword is used for creating a function?
4. How to call a function?
5. How to create string?
6. Which function is used for missing parameters?
7. Give function used for variable parameters.
8. How to assign default argument in PHP?
9. Give purpose of return statement.
10. Define variable function?
11. What is anonymous function?
12. List types of string.
13. Define regular expression.
14. List printing functions for string.
15. Which function is used for comparing two strings?
(B) Long Answer Questions:
1. Define function? How to declare and call it? Explain with example.
2. How to declare a string? Explain with example.
3. With the help of example explain anonymous function.
4. What is default parameter? Describe in detail with example.
5. Write short note on:
(i) Variable parameters (ii) Missing parameters (iii) Variable function.
6. With the help of example explain printing functions.
2.41
Web Technologies - I Function and String
7. What is meant by encoding and escaping? List functions for encoding and
escaping. Also explain with example.
8. Explain comparing two strings with example.
9. How to manipulate and search a string? Explain with example.
10. Define regular expression. How to create it?
11. Write a program using function to calculate factorial of function.
12. With the help of example explain types of strings.
2.44
CHAPTER
3
Arrays
Objectives…
To understand Basic Concepts of Arrays
To study Types of Arrays in PHP
To learn Traversing Arrays and Extracting Data from Arrays
0 1 2 3 4 5 6 7 8 9 Indices
Array length is 10
Fig. 3.1: Element of Array
Creating an Array:
• In PHP, an array can be created using the array() language construct. It takes any
number of comma-separated key => value pairs as arguments.
Syntax:
$array_name = array
{
key1 => value1,
key2 => value2,
key3 => value3,
...
};
3.1
Web Technologies - I Arrays
• The key can either be an integer or a string. The value can be of any type.
For example:
<?php(
$month = array
0 => "January";
1 => "February";
);
?>
• There are two types of arrays in PHP namely, Indexed array (with a numeric index)
and Associative array (with named keys).
• The keys of an indexed array are integers beginning at 0. Indexed arrays are used
when identification of array elements are by their position.
For example:
$city = array( 0 => “Pune”, 1 => “Mumbai”, 2 => “Delhi”);
echo $city[1]; // Mumbai
• Indexed array can also be created without keys. In this case the key will be started
from 0.
For example:
$city = array(“Pune”, “Mumbai”, “Delhi”);
echo $city[3]; // Chennai
• An associative array has strings as keys. Associative array will have their index as
string so that we can establish a strong association between key and values.
For example:
$marks = array(“Maths” => 36, “Physics” => 28, “Chemistry” => 30);
echo $marks[‘Physics’]; // 28
$v = array(“a” => “one”, “b” => “two”, “c” => “three”);
echo $v[‘a’]; // one
• PHP internally stores all arrays as associative arrays, so the only difference between
associative and indexed arrays is what the keys happen to be.
• In both cases, the keys are unique i.e., we can’t have two elements with the same key,
regardless of whether the key is a string or an integer.
3.2
Web Technologies - I Arrays
3.4
Web Technologies - I Arrays
For example:
$a = array(‘one’ ⇒ 1, 2, 3);
then a[‘one’]=1
a[0]=2
a[1]=3
3.3.1 Adding Values to the End of Array [April 17]
• To insert more values at the end of existing array, use [ ] syntax.
For example: Indexed array:
$A=array(1, 2, 3);
$A[ ]=4; // $A[3]=4
For example: Associative array:
$A=array(‘one’ ⇒ 1, ‘two’ ⇒ 2, ‘three’ ⇒ 3);
$A[ ]=4; // $A[0]=4
3.3.2 Assigning a Range of Values
• The range() function creates an array of consecutive integer or character between two
values we pass to it as a parameter.
Syntax: array range(mixed $start, mixed $end [, number $step = 1])
• Returns an array of elements from start to end, inclusive. Step is an optional argument
which indicates the difference between each consecutive element of an array.
$number = range(2, 5); // $number = array(2, 3, 4, 5);
$letter = range(‘a’, ‘d’); // $ letter = array( (‘a’, ‘b’, ‘c’, ‘d’)
$a = range(5, 2); // $a = array( (5, 4, 3, 2)
• Only the first character of the string argument is used to build the range.
range(‘aaa’, ‘zzz’) // same as range (‘a’, ‘z’)
For example:
<?php
$number = range(0,50,10);
$character=range('a','i',2)'
print_r ($number);
print_r ($ characters);
?>
Output:
Array ( [0] => 0 [1] => 10 [2] => 20 [3] => 30 [4] => 40 [5] => 50 )
3.7
Web Technologies - I Arrays
Output:
Marks for Amar in physics: 35
Marks for Kiran in maths: 32
Marks for Deepa in chemistry: 39
3.8
Web Technologies - I Arrays
• First parameter ‘array’ is the input array. If offset is non-negative, the slicing will start
at this point. If offset is negative, the slicing will start that far from the end of the
‘array’.
For example:
$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 2); // returns "c", "d", and "e"
• If the parameter ‘length’ is given and is positive, then the slicing will have up to that
many elements in it. If the array is shorter than the ‘length’, then only the available
array elements will be present.
• If ‘length’ is given and is negative then the sequence will stop that many elements
from the end of the array. If it is omitted, then the sequence will have everything from
‘offset’ up until the end of the ‘array’.
$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"
$output = array_slice($input, -2, 1); // returns "d"
• The array_slice() will reorder and reset the numeric array indices by default. You can
change this behavior by setting ‘preserve_keys’ to True.
For example:
<?php
$input = array("a", "b", "c", "d", "e");
// note the differences in the array keys
print_r(array_slice($input, 2, 2));
print_r(array_slice($input, 2, 2, true));
?>
Output:
Array{
[0] => c
[1] => d
}
Array
{
[2] => c
[3] => d
}
3.9
Web Technologies - I Arrays
3.10
Web Technologies - I Arrays
• The array_keys() function returns an array consisting of only the keys in the array.
Syntax:
array array_keys (array $input [, mixed $search_value [, bool
$strict = false]]);
• First parameter is an array containing keys to return. Second and third parameters
are optional.
For example:
<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
array = array("color" => array("blue", "red", "green"),
"size" => array("small", "medium", "large"));
print_r(array_keys($array));
?>
Output:
Array
{
[0] => 0
[1] => color
}
Array
{
[0] => color
[1] => size
}
3.11
Web Technologies - I Arrays
• In the above program only keys are returned by the array_keys function from both the
arrays.
• If search_value is specified then that value will be searched and keys of that value will
be returned.
For example:
<?php
$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));
?>
Output:
Array
{
[0] => 0
[1] => 3
[2] => 4
}
• The parameter ‘strict’ determines if strict comparison (===) should be used during the
search.
3.5.4 Checking whether an Element Exists
• The array_key_exists() function is used to see if an element exists in the array.
Syntax: bool array_key_exists (mixed $key, array $array)
• This function returns TRUE if the given key is set in the array otherwise False.
For example:
<?php
$a=array(‘one’ ⇒ 1, ‘two’ ⇒ 2);
if(array_key_exists(‘one’, $a))
{
echo “Key ‘one’ exists in the array”;
}
else
{
echo "Key ‘one’ does not exist in the array";
}
?>
Output:
Key ‘one’ exists in the array
3.12
Web Technologies - I Arrays
For example:
$a = array(1, 2, 3, 4);
for($i=0; $i<count($a); $i++)
{
echo $A[i] . “<br>”;
}
Output:
1
2
3
4
Using Iterator Functions:
• Every PHP array keeps track of the current element. The pointer to the current
element is known as the iterator. PHP has functions to set, move, reset this iterator.
• The iterator functions are:
1. current(): Returns the currently pointed element.
2. reset(): Moves the iterator to the first element in the array and returns it.
3. next(): Moves the iterator to the next element in the array and returns it.
4. prev(): Moves the iterator to the previous element in the array and returns it.
5. end(): Moves the iterator to the last element in the array and returns it.
6. each(): Returns the key and value of the current element as an array and moves
the iterator to the next element in the array.
7. key(): Returns the key of the current element.
For example:
<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport); // $mode = 'bike';
$mode = current($transport); // $mode = 'bike';
$mode = prev($transport); // $mode = 'foot';
$mode = end($transport); // $mode = 'plane';
$mode = current($transport); // $mode = 'plane';
?>
3.16
Web Technologies - I Arrays
• In the above program the ‘print_row’ function will be called 4 times i.e. for each
elements of the array $a. The ‘print_row’ function then displays the values along with
the keys.
Reducing an Array:
• The array_reduce() function apply a user defined function to each element of an array,
so as to reduce the array to a single value.
Syntax: mixed array_reduce(array $array, callable $callback
[, mixed $initial = NULL])
• The function takes two arguments: the running total, and the current value being
processed. It should return the new running total.
For example:
<?php
function add($sum, $value)
{
$sum += $value;
return $sum;
}
$n = array(2, 3, 5, 7);
$total = array_reduce($n, 'add');
echo $total;
?>
Output:
17
• The function ‘add’ will be called for each element, i.e. 4 times. The function then finds
the sum and returns it.
• If the optional initial is available, it will be used at the beginning of the process.
$total = array_reduce($n, 'add', 10);
cho $total; // 27 (i.e. 10 + 17)
Searching for Values:
• The in_array() function searches if a value exists in an array or not.
Syntax:
bool in_array(mixed $to_find, array $input [, bool $strict = FALSE])
• The in_array() function returns true or false, depending on whether the element
‘to_find’ is in the array ‘input’ or not.
3.18
Web Technologies - I Arrays
For example:
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os))
{
echo "Got Irix";
}
if(in_array("mac", $os))
{
echo "Got mac";
}
?>
• The second condition is false because in_array() is case-sensitive, so the program
above will display:
Got Irix
• If the third parameter strict is set to TRUE then the in_array() function will also check
the types of the $value.
For example:
<?php
$a = array(2, 3, "4", "5");
if(in_array('3', $a, true))
{
echo "'3' found with strict check\n";
}
if(in_array('4', $a, true))
{
echo "'4' found with strict check\n";
}
?>
Output:
'4' found with strict check
• In the above program the type of ‘3’ which we are searching is string but in the array
‘a’, 3 is integer. Hence first condition is false.
array_search() Function:
• The array_search() function search an array for a value and returns the key.
Syntax:
mixed array_search (mixed $ to_find, array $input [, bool $strict = FALSE])
3.19
Web Technologies - I Arrays
• The in_array() function returns the key of the element ‘to_find’ if it is found in the
array ‘input’, otherwise returns FALSE.
For example:
<?php
$a=array("a"=>"5","b"=>5,"c"=>"5");
echo array_search(5,$a,true);
?>
Output:
b
• The optional second parameter sort_flags may be used to modify the sorting behavior
using these values:
(i) SORT_REGULAR: Compare items normally (don't change types)
(ii) SORT_NUMERIC: Compare items numerically
(iii) SORT_STRING: Compare items as strings
(iv) SORT_NATURAL: Compare items as strings using "natural ordering" like natsort()
2. rsort() Function:
• The syntax of rsort() function is same but it sorts an indexed array in descending
order.
3. usort() Function:
• The usort() function sorts an array using a user-defined comparison function.
Syntax: bool usort(array &$array, callable $value_compare_func)
• The ‘value_compare_func’ is a user defined function where, the first argument is
considered to be less than, equal to, or greater than the second, then the function
return an integer less than, equal to, or greater than zero respectively.
For example:
int callback (mixed $a, mixed $b)
<?php
function my_sort($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
$a=array(4,2,8,6);
usort($a,"my_sort");
print_r($a); // Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 )
?>
4. asort() Function: [Oct. 16, 17, 18]
• This function mainly used to sort associative array.
• The function maintains their key/value association after sorting the array elements.
For example:
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana",
"c" => "apple");
asort($fruits);
print_r($fruits);
?>
Output::
Array ( [c] => apple [b] => banana [d] => lemon [a] => orange )
3.21
Web Technologies - I Arrays
• We can merge arrays, find the difference, calculate the total, and more, all using built-
in functions.
1. array_sum() Function:
• The array_sum() function returns the sum of all the values in the array.
Syntax: array_sum($array);
For example:
<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "<br>";
$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "<br>";
?>
Output:
sum(a) = 20
sum(b) = 6.9
2. array_merge() Function:
• Merges the elements of one or more arrays together so that the values of one are
appended to the end of the previous one.
Syntax:
array array_merge(array $array1 [, array $array2 [, array $array3...]])
• After merging the numeric keys are renumbered.
For example:
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
Output:
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
• If the input arrays have the same string keys, then the later value for that key will
overwrite the previous one.
• If however, the arrays contain numeric keys, the later value will not overwrite the
original value, but will be appended.
For example:
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid",4);
$result = array_merge($array1, $array2);
print_r($result);
?>
3.25
Web Technologies - I Arrays
Output:
Array
{
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
}
3. array_diff() Function:
• The array_diff() function identifies values from one array that are not present in
others.
Syntax:
array array_diff ( array $array1, array $array2 [, array $array3 ...] );
For example:
<?php
$a = array(1, 2, 3, 4);
$b = array(2, 4);
$result=array_diff($a,$b);
print_r($result);
?>
Output:
Array ( [0] => 1 [2] => 3 )
• From array $a the values 1 and 3 is not present in the array $b.
4. array_filter() Function: [April 18, Oct. 18]
• The array_filter() function filters the values of an array using a callback function.
• This function passes each value of the input array to the callback function. If the
callback function returns true, the current value from input is returned into the result
array. Array keys are preserved.
Syntax:
array array_filter ( array $input [, callback $callback] );
For example:
<?php
function is_odd($var)
{
return ($var % 2);
}
3.26
Web Technologies - I Arrays
6. Which function will simply overwrite the preexisting key/value pair, replacing it
with the one found in the current input array?
(a) array_merge() (b) array_combine()
(c) array_merge_recursive() (d) array_merge_all()
7. Which function is useful when you need to perform a particular action based on
each array element?
(a) array_walk() (b) walk()
(c) array_walk_recursive() (d) array_work()
8. Which function is capable to recursively apply a user-defined function to every
element in an array?
(a) array_walk() (b) walk()
(c) array_walk_recursive() (d) array_work()
9. Which function works functionally the same as count()?
(a) size() (b) sizeof()
(c) countof() (d) countall()
10. An array with more than two dimensions called as,
(a) single dimensional array (b) multi dimensional array
(c) Both (a) and (b) (d) None of mentioned
11. As compared to associative arrays vector arrays are much ________.
(a) Faster (b) Slower
(c) Stable (d) None of the above
12. By default, the index of array in PHP starts from,
(a) 0 (b) 1
(c) −1 (d) 2
13. How many types of array are available in PHP?
(a) 1 (b) 2
(c) 3 (d) 4
14. Which stores one or more similar type of values in a single value?
(a) Function (b) Array
(c) String (d) None of mentioned
15. Predict the output of the following code.
<?php
$a=array(1,2,3,5,6);
next($a);
next($a);next($a);
echo current($a);?>
(a) 2 (b) 3
(c) 4 (d) 5
16. Which function reverses the roles of the keys and their corresponding values in an
array?
(a) array_reverse() (b) array_flip()
(c) array_flip_roles() (d) array_reverse_roles()
3.28
Web Technologies - I Arrays
17. Which function will pass each element of an array to the user-defined function?
(a) array_walk() (b) walk()
(c) array_walk_recursive() (d) array_work()
18. Which function produces a new array consisting of a submitted set of keys and
corresponding values?
(a) array_merge() (b) array_combine()
(c) array_merge_recursive() (d) array_merge_all()
19. Which function returns a key-preserved array consisting only of those values
present in the first array that are also present in each of the other input arrays?
(a) array_common() (b) array_intersect()
(c) array_intersect_key() (d) array_intersect_ukey()
20. Which function will return keys located in an array that is located in any of the
other provided arrays?
(a) array_common() (b) array_intersect()
(c) array_intersect_key() (d) array_intersect_ukey()
21. Which function removes all duplicate values found in an array, returning an array
consisting of solely unique values?
(a) array_duplicate() (b) array_unique()
(c) array_remove_duplicate() (d) array_unique_values()
22. The function _______will return a random number of keys found in an array.
(a) rand() (b) array_random()
(c) array_rand() (d) array_rand_key()
23. The function ________ allows us to compare the keys of multiple arrays with the
comparison algorithm determined by a user-defined function.
(a) diff() (b) array_diff()
(c) array_diff_key() (d) array_diff_ukey()
24. Which function returns an array consisting of associative key/value pairs?
(a) array_count() (b) array_count_keys()
(c) count() (d) array_count_values()
25. Which array function returns a section of an array based on a starting and ending
offset value?
(a) array_slice() (b) array_flip()
(c) array_splice() (d) array_reverse()
26. Which function removes all elements of an array found within a specified range,
returning those removed elements in the form of an array?
(a) array_slice() (b) array_remove()
(c) array_remove_all() (d) array_splice()
3.29
Web Technologies - I Arrays
33. Which of the following function is used to set the array pointer to the value of last
key?
(a) last() (b) end()
(c) next() (d) final()
34. What is the output of following PHP:
<?php
function add($sum, $value)
{
$sum += $value;
return $sum;
}
$n = array(-2, 3, 5, 7);
$total = array_reduce($n, 'add');
echo $total;
?>
(a) 15 (b) 13
(c) 17 (d) 18
Answers
1. (c) 2. (d) 3. (a) 4. (a) 5. (c) 6. (a) 7. (a) 8. (c) 9. (b) 10. (b)
11. (a) 12. (a) 13. (c) 14. (b) 15. (d) 16. (b) 17. (a) 18. (b) 19. (b) 20. (c)
21. (b) 22. (c) 23. (d) 24. (d) 25. (a) 26. (d) 27. (b) 28. (b) 29. (d) 30. (d)
31. (d) 32. (c) 33. (b) 34. (b)
Q.II Fill in the Blanks:
1. PHP arrays stores multiple values of different data type in a ______ at a time.
2. There are two types of arrays in PHP namely ______ and ______ arrays.
3. To remove a key/value pair, call the ______ function on it.
4. The ______ function creates an array of consecutive integer or character between
two values we pass to it as a parameter.
5. To divide an array into smaller, evenly sized arrays, use the ______ function.
6. The ______ function is used to traverse the elements in an array in an random
order.
7. In PHP, an array can be created using the______ language construct
8. An ______ array has strings as keys .
9. The ______ functions are used to return the number of elements in the array.
10. The array_key_exists() function is used to see if an element ______ in the array.
11. The ______ function returns the sum of all the values in the array.
12. We can access specific values from an array using the array variable's name,
followed by the element's key (index) within ______ brackets.
3.31
Web Technologies - I Arrays
13. In numeric array the default array index starts from ______.
14. To create an array initialized to the ______ value, use array_pad() function.
15. To copy all of an array's values into variables, use the ______ construct.
16. The array_splice() function can ______ or ______ elements in an array.
17. PHP provides two functions namely, extract() and compact(), that ______ convert
between arrays and variables.
18. There are several ways to traverse arrays in PHP, the most common way to loop
over elements of an array is to use the ______ construct.
19. Every PHP array keeps track of the current element you're working with; the
pointer to the current element is known as the ______ iterator.
20. The array_multisort( ) function sorts multiple indexed arrays at ______.
21. The array_reverse() function reverses the ______ order of elements in an array.
22. The array_merge( ) function intelligently ______ two or more arrays.
Answers
1. single variable 2. Indexed and 3. unset() 4. range() 5. array_chunk()
Associative
6. shuffle() 7. array() 8. Associative 9. count() 10. exists
11. array_sum() 12. square 13. 0 (zero) 14. same 15. list()
16. remove, insert 17. convert 18. foreach 19. iterator 20. once
21. internal 22. merges
Q.III State True or False:
1. PHP arrays stores multiple values of different data type in a single variable at a
time.
2. An associative array has strings as keys.
3. To insert more values at the end of existing array, use () syntax.
4. The range() function creates an array of random integer or character between two
values we pass to it as a parameter.
5. The count() functions are used to return the number of elements in the array.
6. To copy an array’s keys into variables use the list() construct or function.
7. The array_key_exists() function is used to see if an element exists in the array.
8. The array_splice() cannot works on associative arrays.
9. The extract()function automatically creates local variables from an array.
10. The array_flip() function flips/exchanges all keys with another array.
11. Key or index of an array is a unique number or a string that is associated with
each value of an element.
12. To change an existing value of an element, we need to specify the new value in the
array mentioning the key of that element in [] brackets.
13. In an indexed array, index values (starting from 1) are created automatically.
3.32
Web Technologies - I Arrays
14. In a multi-dimensional array each element in the main array can also be an array.
15. The compact() function automatically creates local variables from an array.
16. The array() function is used to create an array.
17. Values in the multi-dimensional array are accessed using single index.
18. To traverse the elements in an array in a random order, use the shuffle().
Answers
1. (T) 2. (T) 3. (F) 4. (F) 5. (T) 6. (F) 7. (T) 8. (F) 9. (T) 10. (F)
11. (T) 12. (T) 13. (F) 14. (T) 15. (F) 16. (T) 17. (F) 18. (T)
3.34
Web Technologies - I Arrays
3. Explain the PHP functions used to convert array into variables and vice
versa. [4 M]
Ans. Refer to Section 3.6.
October 2017
1. How to check if given variable is array or not? [1 M]
Ans. The is_array() function checks whether a variable is an array or not. This function
returns true if the variable is an array, otherwise it returns false.
Syntax: is_array(variable);
2. How to insert and remove the last element of an array. [1 M]
Ans. Refer to Section 3.3.1.
3. What is an associative array? Explain with suitable example how it is different
from indexed array. Explain foreach function(). [5 M]
Ans. Refer to Section 3.1.2.
4. Explain the following functions with respect to array:
(i) extract() (ii) shuffle() (iii) array_splice() (iv) arsort(). [4 M]
Ans. Refer to Sections 3.6, Point (1), 3.8.3, Point (3), 3.5.5 and 3.8, Point (4).
April 2018
1. State the purpose of array_filter() function. [1 M]
Ans. Refer to Section 3.9, Point (4).
2. What is array? Explain different types of Array with an example. [5 M]
Ans. Refer to Sections 3.0 and 3.1.
3. Explain the following functions with respect to Array:
(i) array_slice() (ii) krsort(). [2 M]
Ans. Refer to Sections 3.5.1 and 3.8, Point (5).
October 2018
1. Which function is used to remove duplicate elements from an array? [1 M]
Ans. The array_unique() function removes duplicate values from an array. If two or
more array values are the same, the first appearance will be kept and the other
will be removed.
2. How to get array of keys and array of values from an associative array? Illustrate
with suitable example using built-in functions. [5 M]
Ans. Refer to Section 3.5.3.
3. Write the output of the following PHP script; [2 M]
<?php
$age=array("Peter__35", "Ben__37", "Joe__43");
arsort ($age);
print_r ($age);
?>
Ans. Array ( [0] => Peter__35 [2] => Joe__43 [1] => Ben__37 )
3.35
Web Technologies - I Arrays
3.36
CHAPTER
4
4.0 INTRODUCTION
• PHP is a server side programming language. PHP allows us to work with files and
directories stored on the Web server.
• In computer a file is a resource for storing information, which is available to a
computer program and is usually based on some kind of durable storage.
• File is a collection of data or information that has a name called the
filename. Directory is an organizational unit, which is used to organize files into a
hierarchical structure.
• File handling is an important part of PHP. PHP has several functions for creating,
reading, uploading and editing files. PHP can write or erase files and directories on the
server.
• A database is a collection of information that is organized so that it can easily be
accessed, managed and updated. With PHP, we can connect to and manipulate
databases.
• A database is a collection of related data. A Database Management System (DBMS) is
system software for creating and managing databases.
• The DBMS provides users and programmers with a systematic way to create, retrieve,
update and manage data.
• Nowadays, we use Relational Database Management Systems (RDBMS) to store and
manage huge volume or amount of data.
• PHP works MySQL, PostgreSQL, and Oracle databases are the backbone of most
modern dynamic web sites.
4.1
Web Technologies - I Files and Database Handling
• Although PHP should close all open files automatically when our script terminates.
<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>
Output:
Access time: 1141633430
Modification time: 1141298003
Device number: 0
• The following example retrieves the size of file my.txt if exists.
$my_file_stats = stat(“my.txt”);
$my_file_size = $my_file_stats [7];
For example:
<?php
$fn = './backup/test.bak';
if(unlink($fn))
{
echo sprintf("The file %s deleted successfully",$fn);
}
else
{
echo sprintf("An error occurred deleting the file %s",$fn);
}
4.1.6 Copying Files
• To copy a file, we use the copy() function. First, we need to determine which file to
copy by passing the file path to the first parameter of the copy() function. Second, we
need to specify the file path to copy the file to.
• The copy() function returns true if the file was copied successfully, otherwise it
returns false.
Syntax: bool copy(string $source, string $dest);
For example:
<?php
echo copy("source.txt","nirali.txt");
?>
Output:
1
4.1.7 Reading and Writing Characters in Files
• PHP provides set of functions for reading and writing characters in files i.e. fgetc(),
feof(), fgets(), fgetcsv(), and fputs().
1. fgetc() Function: [April 19]
• The fgetc() function reads a single character from a file. Returns FALSE on end of file.
Syntax: string fgetc(resource $handle);
For example:
<?php
$file = fopen("nirali2.txt","r");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>
Output:
Hello, this is a nirali file.
4.8
Web Technologies - I Files and Database Handling
• The feof() function returns true on reaching the end of a specified file (or if an error
occurs) and returns false otherwise. So, when the file pointer reaches at end of file the
while loop terminates.
• The fgetc() is the same as the fread():
$one_char = fgetc($fp) it is same as
$one_char = fread($fp, 1)
2. fgets() Function: [Oct. 17, April 19]
• This function is used to read sets of characters.
Syntax: string fgets(resource $handle [, int $length]);
• This function takes two arguments, fp and length and returns a string of maximum
length (length-1) in bytes, as read from the file pointed to by fp.
• It stops reading for any one of the three reasons:
(i) The specified number of bytes has been read.
(ii) A new line is encountered.
(iii) The end of the file is reached.
• The difference between fgets() and fread() is that fgets() stops reading when it reaches
end-of-line and reads upto length-1 bytes, while fread() reads past end-of-line and
reads upto length bytes.
For example:
<?php
$file = fopen("nirali.txt","r");
echo fgets($file);
fclose($file);
?>
Output:
Hello, this is a nirali file
3. fgetcsv() Function:
• The fgetcsv() function read the data in files with the assumption that it is properly
formatted in csv (comma separated-value) and puts data into an array.
Syntax:
array fgetcsv (resource $handle [, int $length [, string $delimiter
[, string $enclosure [, string $escape]]]]);
• The fgetcsv() function must be given a valid file handle, a numerical value higher than
the length of each line (including the end-of-line characters) and we can optionally
specify data delimiters (the default is comma) and data enclosures (the default is
double-quotes).
4.9
Web Technologies - I Files and Database Handling
• The following code snippet shows how we might retrieve a line of data values from a
file in csv format:
For example:
<?php
$file = fopen("contacts.csv","r");
while(! feof($file))
{
print_r(fgetcsv($file));
}
fclose($file);
?>
The CSV file (contacts.csv) contains:
Amar Salunkhe, Refsnes, Stavanger, Norway
Hege, Refsnes, Stavanger, Norway
Output:
Array
{
[0] => Amar Salunkhe
[1] => Refsnes
[2] => Stavanger
[3] => Norway
}
Array
{
[0] => Hege
[1] => Refsnes
[2] => Stavanger
[3] => Norway
}
4. fputs() Function: [April 18]
• The fputs() function is an alias of the fwrite() function.
• The fputs() functionwrites to an open file.
Syntax: fputs(file, string, length)
For example:
<?php
$file=fopen("nirali.txt","w");
echo fputs($file,"Hello World.Testing!");
fclose($file);
?>
Output:
20
4.10
Web Technologies - I Files and Database Handling
Output:
Array
(
[0] => Hello World. Testing testing!
[1] => Another day, another line.
[2] => If the array picks up this line,
[3] => then is it a pickup line?
)
2. fpassthru() Function:
• The fpassthru() function prints the entire file to the web browser from the current
position to EOF.
• This function returns the number of characters passed or False on failure.
Syntax: fpassthru(file)
For example:
<?php
$ counter_file = “./count.dat”;
if(!($fp=fopen($counter_file, “r”)))
die(“cannot open $counter_file”);
echo “File is opened”;
fpassthru($fp);
?>
• The file is closed when the function finishes reading, so there is no need to call fclose().
3. readfile() Function: [April 18]
• The readfile() function enables us to print the contents of a file without even having to
call fopen().
• It takes a filename as its single argument, reads the whole file and then writes it to
standard output, returning the number of bytes read.
Syntax: readfile(filename,include_path,context)
For example:
<?php
echo readfile("nirali.txt");
?>
Output:
There are two lines in this file.
This is the last line.
57
4.12
Web Technologies - I Files and Database Handling
4.13
Web Technologies - I Files and Database Handling
else
{
echo $file_x . " does not exist";
}
?>
• We can use file_exists() to check whether the file exists.
2. file_size() Function:
• To get the size of the file, we use the file_size() function.
• The filesize() function returns the size of a given file in bytes, or false in case an error
occurred.
Syntax: filesize(filename)
• The following example shows us how to get the size of the test.txt file that resides in
the same directory as the script file.
<?php
$fn = './nirali.txt';
echo filesize($fn);
?>
4.4.1 Time Related Properties [Oct. 18]
• In this section we will study time related properties for fils in PHP.
1. fileatime() Function: [Oct. 17]
• The function fileatime() returns the last access time for a file in a UNIX timestamp
format.
Syntax: fileatime(filename)
For example:
<?php
echo fileatime("nirali.txt");
echo "<br />";
echo "Last access: ".date("F d Y H:i:s.",fileatime("test.txt"));
?>
Output:
1140684501
Last access: February 23 2006 09:48:21.
2. filectime() Function: [Oct. 18]
• The filectime() function returns the time at which the file was last changed as a Unix
time stamp.
• A file is considered changed if it is created or written or when its permission has been
changed.
Syntax: filectime(filename)
4.15
Web Technologies - I Files and Database Handling
For example:
<?php
echo filectime("nirali.txt");
echo "<br />";
echo "Last change: ".date("F d Y H:i:s.",filectime("test.txt"));
?>
Output:
1138609592
Last change: January 30 2006 09:26:32.
3. filemtime() Function: [April 16, 18, Oct. 16]
• The filemtime() returns the time at which the time was last modified as a Unix time
stamp.
• A file is considered modified if it is created or has its contents changed.
Syntax: filemtime(filename)
For example:
<?php
echo filemtime("nirali.txt");
echo "<br />";
echo "Last modified: ".date("F d Y H:i:s.",filemtime("test.txt"));
?>
Output:
1139919766
Last modified: February 14 2006 13:22:46.
• We can get information on file ownership and permissions. All files are associated
with a specific user and a specific group of users and assigned flags that determine
who has permission to read, write or execute their contents.
• There are three permissions associated with the files which are read, write or execute.
Each of these three permissions (read, write, execute) can be granted to (or withheld
from):
1. File Owner: By default, the user whose account was used to create the file.
2. A Group of Users: By default, the group to which the owner belongs.
3. All Users: Everyone with an account on the system.
4.16
Web Technologies - I Files and Database Handling
• Let us see various functions used in PHP for file ownership and permissions:
1. posix_getpwuid() Function: [April 17]
• When we want to get information of a user by his ID number, we can use the
posix_getpwuid() function, which returns an associative array with the following
references:
Name Explanation
name The username.
2. posix_getgrgid() Function:
• The posix_getgrgid() function return info about a group by group id.
Syntax: array posix_getgrgid(int $gid)
• The function, posix_getgrgid( ), returns, an associative array on a group identified by a
group id. It contains following elements of the group structure.
Name Explanation
name The name of the group.
gid The ID number of the group.
members The number of members belonging to the group.
For example:
<?php
$groupid = posix_getegid();
$groupinfo = posix_getgrgid($groupid);
print_r($groupinfo);
?>
Output:
Array
{
[name] => Pragati
[passwd] => x
[members] => Array
{
[0] => Amar
[1] => Akbar
}
gid] => 42
}
• The chmod() function returns true if the permission was set successfully otherwise it
returns false.
Syntax: chmod(&file, &mode)
• A file permission is represented by an octal number that contains three digits:
o The first digit specifies what the owner of the file can do with file.
o The second digit specifies what the owner group of the file can do with the file.
o The third digit specifies what everyone can do with the file.
For example:
<?php
chmod("/somedir/somefile", 755); // decimal; probably incorrect
chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect
chmod("/somedir/somefile", 0755); // octal; correct value of mode
?>
• We can use following three functions to get information from our PHP scripts.
1. fileowner() Function:
• This function returns the user ID (owner) of the specified file on success or FALSE on
failure.
Syntax: fileowner($filename)
For example:
<?php
echo fileowner("nirali.txt");
?>
2. filegroup() Function:
• The filegroup() function returns the group ID of the specified file, or FALSE on failure.
Syntax: filegroup($filename)
For example:
<?php
echo filegroup("nirali.txt");
?>
3. filetype() Function:
• The filetype() function returns the file type of a specified file or directory.
• This function returns the one of the seven possible values on success or False on
failure.
• Possible return values:
o fifo
o char
o dir
4.20
Web Technologies - I Files and Database Handling
o block
o link
o file
o unknown
Syntax: filetype($filename):
For example:
<?php
echo filetype("images");
?>
Output:
Dir
• Steps taken by PHP to open the database and execute different queries on it.
Step 1: Create a connection to PostgresSQL database.
Step 2: Create a database (can also be done without PHP- in the PostgreSQL terminal).
Step 3: Create a table (can also be done without PHP- in the PostgreSQL terminal).
Step 4: Execute the query.
Step 5: Close the connection.
4.6.1.5 pg_fetch_array()
• The pg_fetch_array() function fetches a row as an array.
Syntax:
array pg_fetch_array(resource $result [, int $row
[, int $result_type = PGSQL_BOTH]])
• This function is same as pg_fetch_row(). But, it stores data in the numeric indices as
well as associative indices. It stores both indices by default.
• An optional parameter $result_type specifies how the returned array is indexed. It
takes the following values: PGSQL_ASSOC, PGSQL_NUM and PGSQL_BOTH.
• Using PGSQL_NUM, pg_fetch_array() will return an array with numerical indices,
using PGSQL_ASSOC it will return only associative indices while PGSQL_BOTH, the
default, will return both numerical and associative indices.
For example:
<?php
$conn = pg_pconnect("dbname=test") or die("An error occurred.");
$result = pg_query($conn, "SELECT name, email FROM student") or
die("An error occurred.");
$arr = pg_fetch_array($result, 0, PGSQL_NUM);
echo $arr[0] . " <- Row 1 Name<br>";
echo $arr[1] . " <- Row 1 E-mail<br>”;
/* to pass a result_type. Successive calls to pg_fetch_array
will return t e next row. */
$arr = pg_fetch_array($result, NULL, PGSQL_ASSOC);
echo $arr["name"] . " <- Row 2 Name<br>";
echo $arr["email"] . " <- Row 2 E-mail<br>";
?>
4.6.1.6 pg_fetch_assoc()
• The pg_fetch_assoc() returns an associative array that corresponds to the fetched row
(records).
• The pg_fetch_assoc() function is equivalent to pg_fetch_array() with PGSQL_ASSOC as
the optional third parameter. It only returns an associative array.
Syntax: array pg_fetch_assoc(resource $result [, int $row])
4.24
Web Technologies - I Files and Database Handling
For example:
<?php
$conn = pg_pconnect("dbname=test") or die("An error occurred.");
$result = pg_query($conn, "SELECT roll_no, name, email FROM student") or
die("An error occurred.");
while ($row = pg_fetch_assoc($result))
{
echo $row['roll_no'];
echo $row['name'];
echo $row['email'];
}
?>
4.6.1.7 pg_fetch_object()
• The pg_fetch_object() function fetches a row as an object.
Syntax: object pg_fetch_object(resource $result [, int $row])
• Both the parameters are same as pg_fetch_row().
• The pg_fetch_object() returns an object with properties that correspond to the fetched
row's field names.
• It can optionally instantiate an object of a specific class and pass parameters to that
class's constructor.
For example:
<?php
$db_conn = pg_pconnect("dbname=test") or die("An error occurred.");
$result = pg_query($db_conn, "SELECT name, email FROM student") or
die("An error occurred.");
while($data = pg_fetch_object($result))
{
echo $data->name . " ";
echo $data->email . "<br>";
}
pg_free_result($result);
pg_close($db_conn);
?>
4.25
Web Technologies - I Files and Database Handling
4.6.1.8 pg_fetch_result()
• The pg_fetch_result() function returns the value of a particular row and column in a
result set.
Syntax:
string pg_fetch_result(resource $result, int $row, mixed $column)
string pg_fetch_result(resource $result, mixed $column)
• The parameters $result and $row are same as pg_fetch_row(). The parameter $column
is a string representing the name of the column to fetch, otherwise an int representing
the column number to fetch. Columns are numbered from 0 upwards.
For example:
<?php
$db = pg_connect("dbname=users user=me") || die();
$res = pg_query($db, "SELECT * FROM student");
$val = pg_fetch_result($res, 1, 0);
echo "Roll no of the second student is: ". $val;
?>
Output:
Roll no of the second student is: 102
4.6.1.9 pg_num_fields()
• The pg_num_fields() function returns the number of columns in a result set.
Syntax: int pg_num_fields(resource $result)
For example:
<?php
$result = pg_query($conn, "SELECT * FROM student");
$num = pg_num_fields($result);
echo $num . "No of columns : $num";
?>
Output:
No of columns : 5
4.6.1.10 pg_num_rows()
• The pg_num_rows() function returns the number of rows in a result set.
Syntax: int pg_num_rows(resource $result)
4.26
Web Technologies - I Files and Database Handling
For example:
<?php
$result = pg_query($conn, "SELECT 1");
$rows = pg_num_rows($result);
echo $rows . " row(s) returned.\n";
?>
Output:
1 row(s) returned.
4.6.1.11 pg_result_error()
• The pg_result_error() function returns any error message associated with result set.
Syntax: string pg_result_error(resource $result)
• This function returns empty string if there is no error. If there is an error associated
with the result parameter, returns false.
For example:
<?php
$dbconn = pg_connect("dbname=test") or die("Could not connect");
if(!pg_connection_busy($dbconn))
{
pg_send_query($dbconn, "select * from doesnotexist;");
}
$res1 = pg_get_result($dbconn);
echo pg_result_error($res1);
?>
Apache/IIS
PHP Engine
PEAR DB
DB extension
pgSQL, MySQL drivers
Database server
• PEAR DB library comes with PHP which is used to connect with the database, issue
queries, check for errors etc.
• The library is object-oriented, where we use class methods (DB:: connect(),
DB::iserror()) and object methods ($db->query(), $q->fetchInto( )) etc.
For example:
<?php
require_once(‘DB.php’);
$db = DB::connect(“pgsql://typhp@localhost/test”);
if(DB::iserror($db))
die($db->getMessage());
$sql = “SELECT * FROM student”;
$q = $db -> querry($sql);
if(DB::iserror($q))
die($db->getMessage());
while($q->fetchInfo($row))
echo $row[0]. “ : ” . $row[1] . “<br>”;
?>
• In above program we connect PHP with the Postgersql database, which is specified in
the string (DSN) passed as a parameter to the connect() method.
• To move from one database to another database system, just change the database type.
The remaining statements are generalized statements which are common for all the
databases.
4.28
Web Technologies - I Files and Database Handling
Option Controls
• The default is 'performance'. Here’s how to enable debugging and optimize for
portability:
$db = DB::connect($dsn, array('debug' => 1, 'optimize' => 'portability'));
3. Error Checking: [April 17]
• The following method is used to check the error:
DB::isError()
• The DB::isError() method returns true if an error occurred while working with the
database object or executing queries.
• If some error occurs and we want to display the error message, then we call the
getMessage() method. We can call getMessage() on any PEAR DB object.
For example:
if(DB::iserror($db))
die($db->getMessage());
Here, $db is the database connection object. So we check whether any error occurs
while connecting with the database. If some error occurs the iserror() method returns
true, hence, die() method will be called, which terminates the program after displaying
the error message.
4. Issuing a Query:
• The query() method is used to execute query. This method sends SQL query to the
database.
• The method is called using a database object:
$result = $db->query(sql);
• In case of INSERT, UPDATE, DELETE query the method returns the DB_OK constant to
indicate success. In case of SELECT query the query() method returns an object that we
can use to access the results.
• We can check whether the query is executed successfully or not as follows:
$q = $db->query($sql);
if(DB::isError($q))
{
die($q->getMessage( ));
}
5. Fetching Results from a Query:
• Consider the following statement:
$result = $db->query($sql);
• If $sql is a SELECT query, in that case the query() method returns a result set. The
result set is nothing but the table.
4.30
Web Technologies - I Files and Database Handling
• To fetch single row (record) from result set PEAR DB provides two methods. One
returns an array corresponding to the next row, and the other stores the row array
into a variable passed as a parameter.
6. Returning the Row:
• The fetchRow() method returns an array of the next row of results:
$row = $result->fetchRow([ mode ]);
• This returns an array of data or NULL if there is no more data. If an error occurs this
method returns DB_ERROR. The mode parameter controls the format of the array
returned.
• Commonly the fetchRow() method is used to process a result, one row at a time, as
follows:
while ($row = $result->fetchRow())
{
if(DB::isError($row))
{
die($row->getMessage( ));
}
// do something with the row
}
7. Storing the Row:
• The fetchInto() method also gets the next row, but stores it into the array variable
passed as a parameter:
$success = $result->fetchInto(array, [mode]);
• Like, fetchRow( ), fetchInto( ) returns NULL if there is no more data, or DB_ERROR if an
error occurs.
• To process all results the fetchInto( ) is used as follows:
while($success = $result->fetchInto($row))
{
if(DB::isError($success))
{
die($success->getMessage( ));
}
// do something with the row
}
• By default, the variable $row contains a one dimensional indexed arrays, where the
positions in the array correspond to the order of the columns in the returned result.
For example:
4.31
Web Technologies - I Files and Database Handling
The column parameter can be either a number (0, the default, is the first
column), or the column name. For example, this fetches the names of all the
student:
$n = $db->getAll("SELECT name FROM student");
foreach ($n as $v)
{
echo "$v\n";
}
(iv) getAll() Method: The getAll() method runs a query and returns all the data as an
array:
$all = $db->getAll(SQL [, values [, fetchmode ]]);
For example, the following code displays the roll_no and name of all the students.
$table = $db->getAll("SELECT roll_no, name FROM student");
foreach ($table as $row)
{
echo $row[0] . “ : " . $row[1] . “\n”;
}
All the get*() methods return DB_ERROR when an error occurs.
4. Details about a Query Response:
• Four PEAR DB methods are used to get information on a query result object i.e.
numRows(), numCols(), affectedRows() and tableInfo().
(i) numRows() and numCols() Methods: The numRows() and numCols() methods tell
you the number of rows and columns returned from a SELECT query:
$howmany = $response->numRows();
$howmany = $response->numCols();
(ii) affectedRows() Methods: The affectedRows() method tells you the number of
rows affected by an INSERT, DELETE, or UPDATE operation:
$howmany = $response->affectedRows();
(iii) tableInfo() Methods: The tableInfo() method returns detailed information on the
type and flags of columns returned from a SELECT operation:
$info = $response->tableInfo();
The following code displays the student table information:
$sql = “SELECT * FROM student”;
$result = $db->query($sql);
$info = $result->tableInfo( );
foreach ($info as $k => $v)
{
echo $k . “ : ” . $v . “<br>”;
}
4.35
Web Technologies - I Files and Database Handling
5. Sequences:
• Sequence is a database object that generates numbers in sequential order.
• Some of the RDBMS supports the feature to assign unique row IDs. PEAR DB sequences
are an alternative to database-specific ID assignment (for instance, MySQL’s
AUTO_INCREMENT).
• The nextID( ) method returns the next ID for the given sequence:
$id = $db->nextID(sequence);
• A sequence is really a table in the database that keeps track of the last-assigned ID.
• We can explicitly create and destroy sequences with the createSequence() and
dropSequence() methods:
$res = $db->createSequence(sequence);
$res = $db->dropSequence(sequence);
• The result will be the result object from the create or drop query, or DB_ERROR if an
error occurred.
6. Metadata:
• The getListOf() method is used to query the database to get information on available
databases, users, views, and functions:
$data = $db->getListOf(what);
• The ‘what’ parameter is a string which may contain "databases", "users", "views", and
"functions".
• For example, this stores a list of available databases in $dbs:
$dbs = $db->getListOf("databases");
7. Transactions:
• Some RDBMSs support transactions, in which a series of database changes can be
committed (all applied at once) or rolled back (discarded, with the changes not applied
to the database).
• For example, when a bank handles a money transfer, the withdrawal from one
account and deposit into another must happen together - neither should happen
without the other, and there should be no time between the two actions.
• PEAR DB offers the commit() and rollback() methods to help with transactions:
$res = $db->commit();
$res = $db->rollback();
• If we call commit() or rollback() on a database that doesn’t support transactions, the
methods return DB_ERROR.
Sample Application (Mini Project):
• This section shows us what we can do with a database driven website. Here, we create
few web pages that manage student information.
4.36
Web Technologies - I Files and Database Handling
• In the first step we create a table using PostgreSQL which stores the student
information as follows:
student(id, name, roll_no, address, email, class)
• This application performs the following task:
o Insert student information,
o View student records,
o Update student records, and
o Delete student records.
• First create a student table as follows:
CREATE TABLE student{
id int(11) NOT NULL auto_increment,
name varchar(20) NOT NULL,
roll_no varchar(6) NOT NULL,
address varchar(50) NOT NULL,
email varchar(20) NOT NULL,
class varchar(20) NOT NULL,
PRIMARY KEY(id)
};
Connecting to Database:
• Create PHP code to connect to an existing database. Call it “conn.inc.php”. This page
will be included in the other pages for PostgreSql connection.
<?php
$host= "host=localhost";
$port = "port=5432";
$dbname = "dbname=testdb";
$credentials = "user=root password=pass123";
$conn = pg_connect("$host $port $dbname $credentials") or
die("Could not connect");
?>
Insert Student Information:
• Here we create a page to insert student record. Call it “insert_student.php”.
• If users do not fill out required fields, or insert already inserted record, the page will
notify them.
• This page also contains a link to view list of records already inserted.
<?php
include "conn.inc.php";
?>
4.37
Web Technologies - I Files and Database Handling
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<h1>Insert Student Information</h1>
<?php
if(isset($_POST['submit']) && $_POST['submit'] == "Insert")
{
if($_POST['name'] != "" &&
$_POST['roll_no'] != "" &&
$_POST['address'] != "" &&
$_POST['email'] != "" &&
$_POST['class'] != "")
{
$query = "SELECT name, email FROM student WHERE
name='".$_POST['name'] . "' and email='".$_POST['email']."';";
$result = pg_query($conn, $query) or
die(pg_last_error($conn));
if(pg_num_rows($result))
{
?>
<p>
<font color="#FF0000"><b>The Student,
<?php echo $_POST['name']; ?>, is already in the database, please
insert another.</b></font>
<form action="insert_student.php" method="post">
Name: <input type="text" name="name" value="<?php echo
$_POST['name']; ?>"><br>
Roll No: <input type="text" name="roll_no" value="<?php echo
$_POST['roll_no']; ?>"><br>
Address: <input type="text" name="address" value="<?php echo
$_POST['address']; ?>"><br>
4.38
Web Technologies - I Files and Database Handling
4.39
Web Technologies - I Files and Database Handling
</p>
<a href="view_student.php">View Records</a>
<?php
}
?>
</body>
</html>
View Student Records:
• Create a page “view_student.php” to display all the records along with the links to
update and delete the record as follows:
<?php
include "conn.inc.php";
$query = "SELECT * FROM student;";
$result = pg_query($conn, $query) or die(pg_last_error($conn));
?>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<h1>Student Information</h1>
<table border = "1" cellspacing = "0">
<tr><th>Name</th><th>Roll
No</th><th>Address</th><th>Email</th><th>Class</th><th></th><th></th>
</th>
<?php
while($row = pg_fetch_array($result, NULL, PGSQL_ASSOC))
{
?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['roll_no']; ?></td>
<td><?php echo $row['address']; ?></td>
4.41
Web Technologies - I Files and Database Handling
4.42
Web Technologies - I Files and Database Handling
<p>
<form action="update_student.php" method="post">
Name: <?php echo $row['name']; ?><br>
Roll No: <input type="text" name="roll_no" value="<?php echo
$row['roll_no']; ?>"><br>
Address: <input type="text" name="address" value="<?php echo
$row['address']; ?>"><br>
Email: <input type="text" name="email" value="<?php echo
$row['email']; ?>"><br>
Class: <input type="text" name="class" value="<?php echo
$row['class']; ?>"><br>
<input type="hidden" name="sid" value="<?php echo $sid; ?>">
<br><br>
<input type="submit" name="submit" value="Update">
<input type="button" value="Cancel" onClick="history.go(-1);">
</form>
</p>
</body>
</html>
update_student.php
<?php
include "conn.inc.php";
$sid = $_POST['sid'];
?>
<html>
<body>
<p>
<?php
$query_update = "UPDATE student SET " .
"roll_no = '" . $_POST['roll_no'] . "', " .
"address = '" . $_POST['address'] . "', " .
"email = '" . $_POST['email'] . "', " .
"class = '" . $_POST['class'] . "' WHERE id = " . $sid;
$result_update = pg_query($conn, $query_update)
or die(pg_last_error($conn));
echo "The record has been updated!";
?>
</p>
<a href="view_student.php">Click Here</a> to return to view records.
</body>
</html>
4.43
Web Technologies - I Files and Database Handling
PRACTICE QUESTIONS
Q.I Multiple Choice Questions:
1. Which function opens the file and returns a file handle?
(a) fopen() (b) open()
(c) file_handle() (d) All of mentioned
2. Which function returns information about a file?
(a) con() (b) open()
(c) stat() (d) read()
3. Which function prints the entire file to the web browser from the current position
to EOF?
(a) file() (b) readfile()
(c) fread() (d) fpassthru()
4. Which function is offered by PHP for connecting to a postgreSQL?
(a) con() (b) pg_connect()
(c) con_pSql() (d) pg_con()
5. Which function is used to fetches one row of data from the resultant set?
(a) row() (b) fetchrow()
(c) pg_fetch_row() (d) None of the mentioned
4.44
Web Technologies - I Files and Database Handling
6. Which function is used to return the value if particular row and column from the
resultant set?
(a) pg_fetch_object() (b) pg_fetch_result()
(c) pg_fetch_row() (d) pg_fetch_assoc()
7. Which function will returns only an associative array?
(a) pg_fetch_object() (b) pg_fetch_result()
(c) pg_fetch_row() (d) pg_fetch_assoc()
8. Which function will return number of columns in a resultant set?
(a) pg_fetch_field() (b) pg_fetch_result()
(c) pg_fetch_row() (d) pg_num_fields()
9. PEAR stands for,
(a) Processor Extension and Application Repository
(b) PHP Extension and Application Repository
(c) Preprocessor Extension and Access Repository
(d) None of mentioned
10. Which method is used in PEAR DB to execute query?
(a) execute() (b) query()
(c) get() (d) fetchrow()
11. Which of the following Not a file opening mode?
(a) a+ (b) x
(c) r (d) e
12. Which of the following is not PHP functions for reading and writing characters in
files.
(a) fgetc() (b) feof()
(c) fgetcsv() (d) fputstr()
13. Which function prints the entire file to the web browser from the current position
to EOF?
(a) file() (b) fpassthru()
(c) readfile() (d) read()
14. What is output of following PHP code ?
<?php
$file = fopen("TyData.txt","r");
echo ftell($file);
fseek($file,"10");
echo "<br />" .ftell($file);
fclose($file);
?>
(a) 1 & 10 (b) 0 & 10
(c) 0 & 9 (d) 1 & 9
4.45
Web Technologies - I Files and Database Handling
15. Which function requires two arguments specifying a file pointer and the string of
data that is to be written?
(a) write() (b) fopen()
(c) close() (d) fread()
16. Which software for creating and managing databases?
(a) Database (b) DBMS
(c) Both (a) and (b) (d) None of mentioned
17. Which is portable and easy to use as compare to database-specific extension?
(a) SQL DB (b) MySQL DB
(c) PEAR DB (d) All of mentioned
18. Which is a powerful, open source object-relational database system?
(a) PostgreSQL (b) MySQL
(c) DB2 (d) SQLServer
19. PostgreSQL runs on all major operating systems, including,
(a) Linux and Unix (b) Solaris and macOS
(c) Windows (d) All of mentioned
20. Which method fills in any placeholders in the query and sends it to the RDBMS?
(a) execute() (b) prepare()
(c) executemultiple() (d) read()
21. Following which functions used by PEAR DB to perform a query and fetch the
results in one step.
(a) getRow() (b) getCol()
(c) getOne() (d) All of mentioned
22. Which in PEAR DB are an alternative to database-specific ID assignment?
(a) sequences (b) metadata
(c) transaction (d) None of mentioned
23. In which a series of database changes can be committed (all applied at once) or
rolled back (discarded, with the changes not applied to the database)?
(a) sequences (b) metadata
(c) transaction (d) None of mentioned
24. Which is a named collection of related information?
(a) File (b) Directory
(c) Database (d) DBMS
25. Following which random access functions moves the file pointer from its current
position to a new position, forward or backward, specified by the number of bytes.
(a) ftell() (b) fseek()
(c) rewind() (d) None of mentioned
4.46
Web Technologies - I Files and Database Handling
26. PHP provides which useful functions for checking and changing the file
permissions.
(a) is_readable() (b) is_writable()
(c) is_executable() (d) All of mentioned
27. For copying, renaming and deleting file functions PHP uses,
(a) copy() (b) rename()
(c) unlink() (d) None of mentioned
Answers
1. (a) 2. (c) 3. (d) 4. (b) 5. (c) 6. (b) 7. (d) 8. (d) 9. (b) 10. (b)
11. (d) 12. (d) 13. (b) 14. (b) 15. (a) 16. (b) 17. (c) 18. (a) 19. (d) 20. (a)
21. (d) 22. (a) 23. (c) 24. (a) 25. (b) 26. (d) 27. (d)
Q.II Fill in the Blanks:
1. The PHP ______ function is used to open a file.
2. ______ mode is used to Opens the file for reading and writing only and Places the
file pointer at the end of the file.
3. The ______ function gives information about file by providing the filename as an
argument.
4. The ______ function writes the contents of string to a file.
5. The ______ function returns the group ID of the specified file.
6. The ______ function is used to open a PostgreSQL connection.
7. The ______ function executes a query on the specified database connection.
8. The ______ method returns true in PEAR DB,if an error occurred while working
with the database object or executing queries.
9. In PEAR DB the______ method returns an array of the next row of results.
10. The ______ function checks if the "end-of-file (eof)" has been reached for an open
file.
11. The set of SQL commands, used to create and modify the database structures that
hold the data, is known as ______.
12. ______ database systems such as MySQL, PostgreSQL, and Oracle are the backbone
of most modern dynamic web sites.
13. PHP communicates with relational databases such as MySQL and Oracle using the
______.
14. We can access database such as Microsoft SQL Server, Microsoft Access, Sybase
from ______ DB on Linux and Unix.
15. The fclose() function is used to ______ an open file.
16. ______ is a collection of related data and data is a collection of facts and figures that
can be processed to produce information.
17. The software which is used to manage database is called as ______.
4.47
Web Technologies - I Files and Database Handling
18. The Structured Query Language (SQL) is used to ______ relational databases.
19. ______ is a powerful, open source object-relational database system.
20. The pg_connect() function is used to ______ a PostgreSQL connection.
21. The ______ method returns the first row of data returned by an SQL query.
22. PEAR DB offers the commit() and rollback() methods to help with ______.
23. To change the file permissions, or mode, we use ______function.
24. To ______ information of a user by his ID number, we can use the posix_getpwuid()
function.
25. The is_readable() returns true if we are allowed to ______ the file, otherwise
returns false.
Answers
1. fopen() 2. a+ 3. stat() 4. fwrite() 5. filegroup()
6. pg_connect() 7. pg_query() 8. DB::isError() 9. fetchRow() 10. feof()
11. DDL 12. Relational 13. SQL 14. PEAR 15. close
16. Database 17. DBMS 18. manipulate 19. PostgreSQL 20. open
21. getRow() 22. transactions 23. chmod() 24. get 25. read
Q.III State True or False:
1. The fileopen() function opens the file and returns a file handle.
2. The stat() function gives information about file by providing the filename as an
argument.
3. The fwrite() function will stop at the end of the file or when it reaches the specified
length, whichever comes first.
4. The rename() function in PHP is an inbuilt function which is used to rename a file
or directory.
5. PHP has an unlink() function that allows us to delete a file.
6. The fcopy() function returns true if the file was copied successfully.
7. The fgetc() function reads a single line from a file.
8. The pg_connect() function is used to open a PostgreSQL connection.
9. The pg_query() function executes a query on the specified database connection.
10. The pg_fetch_assoc() function is equivalent to pg_fetch_array() with PGSQL_ASSOC
as the optional third parameter.
11. Close the file with fclose() function.
12. Once a file is opened using fopen() function it can be read with a function
called fread().
13. The DML, is used to retrieve and modify data in an existing database.
14. A RDBMS is a database that is based on the relational model as introduced by E. F.
Codd.
4.48
Web Technologies - I Files and Database Handling
15. The getCol( ) method returns a single column from the data returned by an SQL
query.
16. The numRows( ) and numCols( ) methods tell you the number of rows and columns
returned from a SELECT query.
17. The nextID( ) method returns the next ID for the given sequence.
18. A data source name (DSN) is a string that specifies where the database is located,
what kind of database it is, the username and password to use when connecting to
the database, and more.
19. A new file can be written or text can be appended to an existing file using the
PHP fread().
20. A file must be opened before we can read from it or write to it.
21. The fgetc() function in PHP is an inbuilt function which is used to return a single
character from an open file.
22. The chmod() function in PHP is used to make a copy of a specified file. It makes a
copy of the source file to the destination file.
23. A Data Source Name (DSN) is a string that specifies where the database is located,
what kind of database it is, the username and password to use when connecting to
the database, and more.
Answers
1. (F) 2. (T) 3. (T) 4. (T) 5. (T) 6. (F) 7. (F) 8. (T) 9. (T) 10. (T)
11. (T) 12. (T) 13. (T) 14. (F) 15. (T) 16. (T) 17. (T) 18. (T) 19. (F) 20. (T)
21. (T) 22. (F) 23. (T)
Q.IV Answer the following Questions:
(A) Short Answer Questions:
1. What is file?
2. Define database?
3. What is directory?
4. Define DBMS.
5. What is RDBMS?
6. Which functions are used for random access to file data?
7. What is the purpose of chmod()?
8. In PHP which function is used to getting information about a file.
9. List functions for reading and writing characters in file.
10. How to read entire file in PHP?
11. Which function is used to delete files in PHP?
12. What is the purpose of pg_query?
13. In PHP which function is used to create a connection to the database.
14. Give the use of feof().
15. ‘PostgreSQL is open source relational database system’. Comment this statement.
4.49
Web Technologies - I Files and Database Handling
4. What are different methods to retrieve data from resultset using PEAR DB
functions? [4 M]
Ans. Refer to Section 4.6.
April 2017
1. State the PEAR DB function to get system error message, if the database connection
fails. [1 M]
Ans. Refer to Section 4.6.
2. How to get the user ID of the owner of the specified file? [1 M]
Ans. Refer to Section 4.5.
3. Assume database empdb is already exists. Write a PHP script using PostgreSQL to
increment salary of the employees by 10%. Consider table emp(no, ename,
salary). [5 M]
Ans. Refer to Sample Example.
4. Write a PHP script to display date and time of a file when it was last accessed.[5 M]
Ans. Refer to Section 4.4.1.
5. Explain the functions used for reading and writing characters in files. [4 M]
Ans. Refer to Section 4.1.3.
October 2017
1. What are the different class methods and object methods available in PEAR DB
library. Explain. [5 M]
Ans. Refer to Section 4.6.
2. Consider the following relational database:
Movie(Movie_no, Movie_name, Year)
Actor(Actor_no, Actor_name, Movie_no)
Write a PHP script which accept Movie_name and display actors acted in same
movie. [5 M]
Ans. Refer to Section 4.6.
3. Explain the following functions with example:
(i) fgets() (ii) flock() (iii) file() (iv) fileatime(). [4 M]
Ans. Refer to Sections 4.1.7, Point (2), The flock() function locks and releases a file, 4.2,
Point (1), 4.4.1, Point (1).
April 2018
1. What is PEAR DB Library? [1 M]
Ans. Refer to 4.6.
2. List and explain (any three) the functions of PEAR. [5 M]
Ans. Refer to Section 4.6.
3. Write a PHP script to accept filename from the user and print total number of
words. [5 M]
Ans. Refer to Section 4.1.
4. Explain the following functions with example:
(i) fputs() (ii) fseek() (iii) readFile() (iv) filemtime(). [4 M]
Ans. Refer to Sections 4.1.7, Point (4), 4.3, Point (1), 4.2, Point (3), 4.4.1, Point (3).
4.51
Web Technologies - I Files and Database Handling
October 2018
1. State the advantage of using PEAR DB functions. [1 M]
Ans. Refer to Section 4.6.
2. Consider a table student (rno, name, class). Assume database stud already exists.
Write a PHP script to accept a student roll no. and display details of that student
using PEAR DB functions. [5 M]
Ans. Refer to Section 4.6.
3. Explain the following functions with example:
(i) filectime() (ii) file() (iii) stat() (iv) unlink() (v) fwrite(). [5 M]
Ans. Refer to Sections 4.4.1, Point (2), 4.2, Point (1), 4.1.2, 4.1.5, Point (2) and 4.1.3,
Point (1).
4. Write a PHP script to accept a file name from user and display last access date and
time of a file. [4 M]
Ans. Refer to Section 4.4.1.
April 2019
1. How to delete file in PHP? [1 M]
Ans. Refer to Section 4.1.5, Point (2).
2. What are the different placeholders used in SQL query? [1 M]
Ans. Refer to Section 4.9, Point (1).
3. Write a PHP script to read a file DNA. TXT where file contains character A, T, C G
and space. Count occurrences of each character and write itto the DNACOUNT. TXT
file. [5 M]
Ans. Refer to Section 4.1.3.
4. Write steps to create connection with PostgreSQL database and display the
data. [5 M]
Ans. Refer to Section 4.6.1.1.
5. Consider the following relational database:
Movie(Movie_no, Movie_name, Year)
Actor(Actor_no, Actor_name, Movie_no)
Write a PHP script which accept Movie_name and display actors acted in same
movie. [5 M]
Ans. Refer to Section 4.6.
6. Explain the following functions with example:
(i) fread() (ii) fwrite() (iii) fgetc() (iv) fgets(). [4 M]
Ans. Refer to Sections 4.1.3, Point (2) and (1), 4.1.7, Points (1) and (2).
4.52
CHAPTER
5
5.0 INTRODUCTION
• By using PHP scripts, emails can be sent directly. Email stands for electronic mail, e-
mail or email.
• A method of exchanging messages instantly from one system to another with the help
of the internet is called an Email.
• The e-mail is a message that may contain text, files, images, audio, video or other
attachments sent through a network (such as Internet) to a specified individual or
group of individuals.
• PHP mail() is the built in PHP function that is used to send emails from PHP scripts.
For sending emails PHP uses SMTP, IMAP and POP3 protocols.
5.1
Web Technologies - I Handling Email with PHP
D E F
5.2
Web Technologies - I Handling Email with PHP
2 SMTP
Intermediate
mail
server
3 SMTP
Intermediate
mail
server
• When using the POP protocol all the email messages will be downloaded from the mail
server to the local computer. We can choose to leave copies of the emails on the server
as well.
• POP3 generally used to support a single client and allows only one mailbox to be
created on server.
• POP3 is the most recent version of a standard protocol for receiving e-mail. POP3 is
a client-server protocol in which e-mail is received and held for client by client
Internet server.
3. IMAP (Internet Message Access Protocol): [April 16, 19, Oct. 17]
• IMAP is a standard protocol for accessing email from the local server. IMAP used to
receive the emails from the mail server and retrieving the emails.
• IMAP allows the client program to manipulate the email message on the server
without downloading them on the local computer.
• In IMAP the e-mail is hold and maintained by the remote server. IMAP enables us to
take any action such as downloading, delete the mail without reading the mail.
• IMAP enables us to create, manipulate and delete remote message folders called mail
boxes. IMAP also enables the users to search the e-mails.
• IMAP allows concurrent access to multiple mailboxes on multiple mail servers.
The IMAP is a used by email clients to retrieve email messages from a mail server over
the Internet.
How Combination of These Protocols Works?
• E-mail is delivered over a TCP connection to port 25 of the destination mail server
using SMTP. An e-mail daemon, whose job it is to monitor this port, transfers incoming
messages from them into the appropriate mailbox.
• If a message cannot be delivered (usually because the named mailbox does not exist
on the server) an error report is generated and sent to the incoming message's point of
origin.
• The protocol used by a recipient to retrieve mail from their mailbox on the server is
POP3, which allows the user to log in and retrieve messages.
• By default, messages that have been downloaded to a recipient's computer are deleted
from the server.
• The IMAP is a more sophisticated mail protocol that stores all incoming and outgoing
mail on the server so that mail clients with mailboxes on the server can access their
e-mail from anywhere.
• Mail is not downloaded to the user's PC, and is only deleted from the client's mailbox if
the client specifies that it is to be deleted.
5.4
Web Technologies - I Handling Email with PHP
Email Client 3
SMTP Server
The SMTP server
The forwards the message
Internet to the recipent's
mailbox
4
6
5
• The structure of Email message consists of Headers followed by Body of the message
and may also include separate files as Attachment.
• RFC 2822 provides definition for the composition of email messages. It defines a
message as being composed of ASCII characters divided into lines of characters with
each line ending with CRLF (\r\n).
• The header fields are lines of characters separated by a special. The Header field
contains field name, a colon, and the field body.
• The fields order is not important. The only required field is from which contains the
origination date and originator address.
• Email Header play an important role in the identification of sender & receiver of the
email and other additional information related to the email message.
• The Header fields are:
1. From: This is required field. It contains the address of the sender.
2. Trace: Includes resent-date, resent-from, resent-to etc. and is used when a message
is resent.
3. Sender: Contains a single address from which mail is being sent.
4. Reply-to: Contains an optional reply-to address.
5. To: Contains comma-separated list of addresses to which the message is sent.
6. Cc: Carbon copy (Cc) comma-separated list of addresses to which copies of the
message are sent.
7. Bcc: Blind carbon copy (Bcc)comma-separated list of addresses to which copies of
the message are sent, while preventing other recipients from seeing or knowing
that any other Bcc recipient received the message.
8. Message-id: Optional, but every message should have one. It contain unique
message ID.
9. In-reply-to: Optional, one or more message identifier.
10. References: Optional, one or more message Id.
11. Subject: Optional, contains a short string identifying the subject of the message.
12. Comments: Optional, comment about the body of the message.
13. Keywords: Optional, keywords, comma-separated that the user might find
important.
14. Optional: Optional, its content is unspecified.
• Email body is the field that is commonly used by the email users to
communicate. Email attachments are the computer files which contain the data that
are not included in main body of the email file.
• Attachments are usually used to simplify the sharing of large amount textual and non
textual data across the internet.
5.6
Web Technologies - I Handling Email with PHP
5.4 SENDING EMAIL WITH PHP [April 16, 18, 19, Oct. 16]
• To send email using PHP we must configure the php.ini file with the details of how the
system sends email.
• Open the file php.ini and go to the section entitled [mail function].
• To set the SMTP setting:
smtp = smtp.my.server.net
• Set the sendmail_from seting to reflect your email address:
sendmail_from = [email protected]
• Linux users simply need to let PHP know the location of their sendmail application.
The path and any desired switches should be specified to the sendmail_path directive.
• The configuration for Linux should look something like this:
smtp =
sendmail_from =
; for unix only
sendmail_path = /usr/sbin/sendmail -t -i
Return Values:
• Returns True if the mail was successfully accepted for delivery, False otherwise.
• Following example will send an email message to [email protected].
<?php
$to = "[email protected]";
$subject = "This is subject";
$message = "This is simple text message.";
$header = "From:[email protected] \r\n";
if(mail ($to,$subject,$message,$header))
{
echo "Message sent successfully...";
}
else
{
echo "Message could not be sent...";
}
?>
Sending HTML Email:
• When we send a text message using PHP then all the content will be treated as simple
text.
• Even if we will include HTML tags in a text message, it will be displayed as simple text
and HTML tags will not be formatted according to HTML syntax. But PHP provides
option to send an HTML message as actual HTML message.
• While sending an email message you can specify a Mime version, content type and
character set to send an HTML email.
• Following example will send an HTML email message to [email protected]
copying it to [email protected].
• We can code this program in such a way that it should receive all content from the
user and then it should send an email.
<?php
$to = "[email protected]";
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
$message .= "<h1>This is headline.</h1>";
$header = "From:abc@ example.com \r\n";
$header .= "Cc:afgh@ example.com \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
5.8
Web Technologies - I Handling Email with PHP
if(mail ($to,$subject,$message,$header))
{
echo "Message sent successfully...";
}
else
{
echo "Message could not be sent...";
}
?>
Example: Sending HTML message to multiple recipients.
<?php
// multiple recipients
$to = '[email protected]' . ', '; // note the comma
$to .= '[email protected]';
// subject
$subject = 'Birthday Reminders for August';
// message
$message = '
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</th>
</tr>
<tr>
<td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973</td>
</tr>
</table>
</body>
</html>
';
5.9
Web Technologies - I Handling Email with PHP
• After that use the regular expression functions ereg() to verify that the email address
is in proper format.
<?php
$email_id = “[email protected]”;
//parse unnecessary characters to prevent exploits
$email=htmlspecialchars(stripslashes(strip_tags($email_id)));
//checks to make sure the email address is in a valid format
if (ereg("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9]+(\.[a-z0-9]+)*
(\.[a-z]{2,3})$", $email))
{
echo “Email is valid”;
}
}
?>
Example: A PHP script to validate given email ID. Design necessary screen layouts.
<html>
<head>
<title>Enter E-mail Data</title>
</head>
<body>
<form action="test.php" method="post">
<table>
<tr><td>To:</td>
<td><input type="text" name="to" size="50"></td>
</tr>
<tr>
<td>From:</td>
<td><input type="text" name="from" size="50"></td>
</tr>
<tr>
<td>Subject:</td><td><input type="text" name="subject" size="50"></td>
</tr>
<tr>
<td valign="top">Message:</td>
<td>
<textarea cols="60" rows="10" name="message">
Enter your message here</textarea>
</td>
</tr>
<tr><td></td>
<td>
5.11
Web Technologies - I Handling Email with PHP
Output:
PRACTICE QUESTIONS
Q.I Multiple Choice Questions:
1. Which of the following is not a component of SMTP?
(a) MUA (b) MDA
(c) MTA (d) MPA
2. Which of the option is correct in Simple Mail Transfer Protocol (SMTP)?
(a) reliable (b) connection oriented
(c) text based protocol (d) All of mentioned
3. POP3 generally used to support a single client and allows ________ to be created on
server.
(a) one mailbox (b) two mailboxes
(c) three mailboxes (d) multiple mailboxes
4. IMAP allows concurrent access to _______ on multiple mail servers.
(a) one mailbox (b) two mailboxes
(c) three mailboxes (d) multiple mailboxes
5. Which PHP function is used to create a 32 digit hexadecimal number to create
unique number?
(a) SHA12() (b) md5
(c) md10() (d) RFC()
6. Which method of transferring of messages over computer networks like the
Internet?
(a) email (b) sms
(c) mms (d) Chat (RCS)
7. Email system is based on _______ architecture.
(a) peer-to-peer (b) client-server
(c) server-internet (d) None of mentioned
5.13
Web Technologies - I Handling Email with PHP
Answers
1. HTTP 2. mail() 3. IMAP 4. POP 5. RFC 2822
6. sending 7. POP3 8. local
Q.III State True or False:
1. For sending emails PHP uses SMTP, IMAP and POP3 protocols.
2. Email system is based on client-server architecture.
3. To send an email message in PHP, we use the mail() function.
4. MDA is a computer software component that is responsible for the accepting of
e-mail messages from remote recipient’s mailbox.
5. IMAP used to receive the emails from theClient.
6. Sending email not requires validation and verification of email address.
5.14
Web Technologies - I Handling Email with PHP
7. POP3 is a standard mail protocol used to receive emails from a remote server to a
local email client.
8. The email address must follow the RFC 2826 standard.
Answers
1. (T) 2. (T) 3. (T) 4. (F) 5. (F) 6. (F) 7. (T) 8. (F)
Q.IV Answer the following Questions:
(A) Short Answer Questions:
1. What is email?
2. What is SMTP?
3. What is POP3?
4. What is HTTP?
5. What is MIME?
6. What is the function of MTA?
7. Which protocols are used to retrieve the mail from server?
(B) Long Answer Questions:
1. What is protocol? Which protocol is used for Internet email?
2. With the help of diagram describe working of mail system.
3. Compare IMAP and SMTP.
4. How the SMTP, POP3 and IMAP work? Explain diagrammatically.
5. Explain structure of email message.
6. Describe mail() in detail.
7. Explain header fields in email message.
8. Explain in brief how to send an email.
9. Write a PHP function to validate the email.
10. Write a complete PHP script to accept email from user and check it is valid or not.
11. ‘SMTP protocol is used to send email’. Justify True/False.
12. Explain the structure of an email message.
13. Which are the internet protocols used for mail handling? Explain any one in brief.
14. Explain how message can be send on email server?
15. Write a PHP script to accept email address and validate it. Also print domain name
of the email and result of validation.
UNIVERSITY QUESTIONS AND ANSWERS
April 2016
1. Write the protocols used to retrieve email from server. [1 M]
Ans. Refer to Section 5.2.
2. When IMAP4 protocol is used in email handling? [1 M]
Ans. Refer to Section 5.2, Point (3).
October 2016
1. List protocols used in email. [1 M]
Ans. Refer to Section 5.2.
5.15
Web Technologies - I Handling Email with PHP
5.16