[go: up one dir, main page]

0% found this document useful (0 votes)
231 views42 pages

QB Solution PDF

The document contains answers to questions about HTML tags, CSS, DOM, and other web development topics. It lists five HTML tags, provides code to generate a table, explains CSS types like inline, internal, and external, describes DOM objects like document and elements, defines common acronyms, explains HTML lists and the difference between GET and POST methods. It also includes a form to register for a new semester using attributes like action and method.

Uploaded by

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

QB Solution PDF

The document contains answers to questions about HTML tags, CSS, DOM, and other web development topics. It lists five HTML tags, provides code to generate a table, explains CSS types like inline, internal, and external, describes DOM objects like document and elements, defines common acronyms, explains HTML lists and the difference between GET and POST methods. It also includes a form to register for a new semester using attributes like action and method.

Uploaded by

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

Q1. List five tags in HTML.

Write HTML code to generate following table:

Answer :
<!DOCTYPE html>
<html>
<head>
<title>Table</title>
</head>
<body>
<table border="1" width="100%">
<tr>
<td colspan="4">A</td>
</tr>
<tr>
<td rowspan="2">B</td>
<td colspan="2">C</td>
<td>D</td>
</tr>
<tr>
<td>E</td>
<td>F</td>
<td>G</td>
</tr>
<tr>
<td>H</td>
<td>I</td>
<td colspan="2">J</td>
</tr>
</table>
</body>
</html>
Q2.Explain CSS and its type with example.
-CSS Stands for cascading Style sheet
-CSS describe how HTML elements are to be displayed on the screen.
-CSS can control the layout of multiple web pages all at once.
-Using CSS we can decorate web sites with different fonts,color,graphics,etc.
Advantages :
- Saves time
-Easy to change
-Keep consistency
-Give you more control over layout
-Use styles with JavaScript => DHTML
-Make it easy to create a common format for all the Web pages

Types of CSS:
1.Inline CSS
2. Embedded or internal CSS
3.External CSS

1.Inline CSS :
-Add styles to each tag within the HTML file
-Use it when you need to format just a single section in a web page

Example :
<h1 style=“color:red; font-family: sanssarif”>IU</h1>

2. Embedded or internal CSS


-A style is applied to the entire HTML file
- Use it when you need to modify all instances of particular element (e.g., h1) in a web page
Example :
<style>
h1 {color:red; font-family:sans-serif}
</style>
3. External CSS
-An external style sheet is a text file containing the style definition (declaration)
- Use it when you need to control the style for an entire web site
Example

-h1, h2, h3, h4, h5, h6 {color:red; fontfamily:sans-serif} 


-Save this in a new document using a .css extension
<link href=URL rel=“relation_type”
type=“link_type”>
-URL is the file.css
-Relation_type=“stylesheet”
-Link_type=“text/css”

<link href=“mystyle.css”
rel=“stylesheet”
type=“text/css” />
Q3. What is Document Object Model? Explain the various objects in Document Object
Model.
The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows
programs and scripts to dynamically access and update the content, structure, and style of a
document."
The W3C DOM standard is separated into 3 different parts: Core DOM - standard model for all
document types .
XML DOM - standard model for XML documents .
HTML DOM - standard model for HTML documents .
When a web page is loaded, the browser creates a Document Object Model of the page.
Document Object:
If you want to access any element in an HTML page, you always start with accessing the document
object.
Method Description :
document.getElementById(): Finding an element by element id document.getElementsByTagNam
e(): Finding elements by tag name document.getElementsByClassNa me(): Finding elements by class
name .
document.forms[]: Finding elements by HTML element objects.

Changing HTML Elements:


element.innerHTML = new html content Change the inner HTML of an element.
element.attribute = new value Change the attribute value of an HTML element.
element.setAttribute(attribute, value): Change the attribute value of an HTML element.
element.style.property = new style Change the style of an HTML element.

Adding and Deleting Elements:


document.createElement(element) :Create an HTML element
document.removeChild(element) :R Adding and Deleting Elemen
document.appendChild(element) :Add an HTML element.
document.replaceChild(element) :Replace an HTML element.
document.write(text): Write into the HTML output stream.

For example,
document.getElementById() :
document.getElementById()- Finding an element by element id
<html>
<body><p id="intro">Hello World!</p>
<script>
txt=document.getElementById("intro").innerHTML; alert(txt);
</script>
</body>
</html>
Q4.Give the full names of the following acronym:
(1) WML (2) DOM (3) DHTML (4) ISP (5) XML
(6) HTTP (7) XSL (8) FTP (9) CGI (10) WAP
(11) DTD (12) RSS (13) TCP (14) SOAP

1.WML : Wireless Markup language


2.DOM : Document Object Model
3.DHTML : Dynamic Hypertext Markup Language
4.ISP : Internet Service Provider
5.XML:Extensiblemarkup language
6.HTTP:Hypertext transfer protocol
7.XSL: Extensible Stylesheet language
8.FTP:File Transfer Protocol
9.CGI:Common Gateway Interface
10.WAP : Wireless Application Protocol
11.DTD : Document Type Defination
12.RSS: Rich Site Summary
13.TCP : Transmission Control Protocol
14.SOAP : Simple Object Access Protocol
Q5. Explain different type of HTML list with suitable example.

Types of list
1.Ordered List
2.Unordered List
3.Description List

1.Ordered List :
- Used to display information in a numeric order.
-Using type attribute we can set different numbers.
- The syntax for creating an ordered list is:
<ol>
<li>Item 1</li>
<li>Item 2</li>
</ol>

Where ol = orederlist
Li = list item

2.Unordered List :
- list items are not listed in a particular order.
-The syntax for creating an unordered list is:
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
Where ul = onordered list
Li=list item

3.Description List :
-Description list is used to describe various terms
-The tag is supported in all major browsers.
- Definition and Usage
-The <dl> tag defines a description list.
-The <dl>tag is used in conjunction with <dt>(defines terms/names) and <dd>
(describes each term/name).

Syntax :
<dl>
<dt>Coffee</dt>
<dd>Black hot drink</dd>
<dt>Milk</dt>
<dd>White cold drink</dd>
</dl>
Q6. Differentiate following.
a.HTML and XHTML
b.GET and POST

a.HTMLvs XHTML

HTML XHTML
1.HTML is main markup language for creating 1.XHTML is a family of XML markup language
web pages and other information that can be that mirror or extend versions of the widly used
displayed in a web browser. HTML language in which web pages are
written.
2.Extension : .html, .html 2.Extension : .xhtml , .xml , .html, .htm
3.Internet Media Type : text/html 3.Internet Media Type :application/xhtml+xml
4.Type of Format: Markup language
4.Type of Format : Document file format 5. Stands for: Extensible HyperTextMarkup
5. Stands for: HyperTextMarkup Language Language
6. Function: Web pages are written in HTML. 6. Function: Extended version of HTML that is
7. Versions: HTML 2, HTML 3.2, HTML 4.0, stricter and XML-based
HTML 5 7. Versions: XHTML 1, XHTML 1.1, XHTML
2, XHTML 5

b.GETvs POST

GET POST
1.Parameter remain in browser history because 1.Parameter are nit saved in browser history.
they are part of the URL.
2.Can be bookmarked. 2.Cannot be bookmarked.
3.Easier to hack. 3.Difficult to hack
4.Only ASCII Characters allowed. 4.Norestriction.Binary Data is also allowed.
5.GET is less secure compared to the post 5.POST is a little secure than GET because the
because data sent is part of the URL. parameter are not stored ib browser history.
Q.7 what is an HTML form? Discuss the different form attributes and design a simple
form to register for a new semester.

Ans:

An HTML form is a section of a document which contains controls such as text fields, password
fields, checkboxes, radio buttons, submit button, menus etc.
An HTML form facilitates the user to enter data that is to be sent to the server for processing.

HTML forms are required if you want to collect some data from of the site visitor.

HTML forms are required if you want to collect some data from of the site visitor.

For example,If a user want to purchase some items on internet, he/she must fill the form such as
shipping address and credit/debit card details so that item can be sent to the given address.

Html form syntax


<form action="server_url" method="get/post">
//input controls e.g. textfield, textarea, radiobutton, button
</form>

Attributes:
Here are few attributes that’s use in form.
 Action
 Method
 Name

Action: After submit the form, details should be go to server side. Action is an attribute through which
we can transfer the control to the server side.
action=”server_url”

method: details go to the server side. Method is an attribute through which method details should go
to the server side. It has two values get & post.

Name: name attribute gives a name to form which we can use future in javascript.

Register.html:

<!DOCTYPE html>
<html>
<head>
<title>Register</title>

</head>
<body>
<form name="myform">
Name :
<br />
<input type="text" name="name" >
<br />
<br />
semester :
<br />
<br />
<input type="text" name="semester">
<br />
<br />
Email :
<br />
<br />
<input type="text" name="email">
<br />
<br />
Phone Number :
<br />
<br />
<input type="text" name="number" >
<br />
<br />
Pin Code :
<br />
<br />
<input type= "text" name="pin" >
<br />
<br />
Gender:
<input type= "radio" name="radio" >male
<input type= "radio" name="radio" >female<br/>
<button type="button" value="Submit">Submit</button>
</form>

</body>
</html>

Output:
Q.8 what do you mean by meta tag? Explain with example.

Ans:

Metadata is data (information) about data.

The <meta> tag provides metadata about the HTML document. Metadata will not be displayed on the
page, but will be machine parsable.

Meta elements are typically used to specify page description, keywords, author of the document, last
modified, and other metadata.

The metadata can be used by browsers (how to display content or reload page), search engines
(keywords), or other web services.

<meta> tags always go inside the <head> element.

Metadata is always passed as name/value pairs.

The content attribute MUST be defined if the name or the http-equiv attribute is defined. If none of
these are defined, the content attribute CANNOT be defined.

Meta.html

<html>

<head>

<meta charset="UTF-8">

<meta name="description" content="Free Web tutorials">

<meta name="keywords" content="HTML,CSS,XML,JavaScript">

<meta name="author" content="HegeRefsnes">

</head>

<body>

<h1>Hello,User</h1>

</body>
</html>

Output:
Q-9)What is the role of cache and cookies in the browser?

ANS:
Cache:
Web browsers a can cache (store) pages for quick reviewing without having to request them again.
Each page has a Time to Live ( TTL), the time it is kept in the cache without going back and
reloading it.
A browser can be stopped from caching a page, if it support the „http-equiv‟ attribute.
To do this value „pragma‟ is assigned to http-equiv attribute.
Example –Force browser to ignore the cache page
<meta http-equiv=“pragma" content=“no-cache“/>

Example -Refresh document every 30 seconds:


<meta http-equiv="refresh" content="30“ />
Cookie
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's
computer. Each time the same computer requests a page with a browser, it will send the cookie too.
With the help of code we can set and retrieve cookies.
Q-10)How an inline frame be embedded on a page with graphics and text?
ANS:
The <iframe> tag specifies an inline frame.
An inline frame is used to embed another document within the current HTML document.
<html>
<body>
<iframesrc="index.html">
<p>Your browser does not support iframes.</p>
</iframe>
</body>
</html>
Q.11 EXPLAIN DIFFERENT WEBSITE DESIGNING ISSUES.

ANSWER:BROWSER AND OPERATING SYSTEMS


 Before writing any web page, you should check compatibility with popular browser.
 Different browser may have different view of same page.
 Many of old HTML tags( deprecated tags) may not be supported by modern browsers. So
watchful before using old version of html.
 Technology is moving from HTML to XHTML. Still many users do not use newer version of
browser.
 Furthermore, Usage of CSS and its compatibility with different browsers need to be assessed
before using it.

BANDWIDTH AND CACHE


 According to available bandwidth and connection speeds, user will be able to view your web
site.
 You have to consider such physical constraints while web site designing.
 Heavy graphics loaded page may take more time to load at low bandwidth users.
 Keep graphics less than 30 kilobytes to make them download reasonably on a home
modem.Keep animated gifs to a minimum.
 The site home page should load in < 15‐20 seconds with a 28k modem. Hence, the size of all
files on the home page should be <60k.

DISPLAY RESOLUTION
 Display resolution always affect in visualization of web site.
 While designing web site, you have to consider possible display resolutions of your expected
users client.
 Display resolution is measured in terms of pixels. 800 X 600 and 1024 X 786 are common
resolutions.
 Use relative size to page layout if possible to manage flexible width and height of your pages.
 To make flexible design using HTML layout, divide page into no. of columns, where you can
set certain columns with variable width.

LOOK AND FEEL


 Look and feel of the web site decide the overall appearance of the website. It includes all the
design aspects such as website theme, web typography, graphics, visual structure, navigation
etc.
 Website Theme
 Website theme emphasizes on the unification of design that should be reflected in each
element of the design such that all pages of website hold together and give the impression of a
single unit.
 Website theme should reflect the objective of the organization and convey the message of it.
 Use logo of the company as theme. Use logo on each page at appropriate location.
 Use appropriate color and graphics to create theme which suites company’s domain.

FONT, GRAPHICS AND COLORS


 On paper, we are all used to reading serif fonts and Times New Roman.
 On screens, however, sans‐serif fonts are easier to read.
 The most readable screen font is Verdana, Century Gothic, Tahoma and Arial.
 Be careful with the choice of font. Some font might not viewed the same in other browser.
 Choose simple colors that compliment each other & work on most web browsers.
 Keep graphics less than 30 kilobytes to make them download reasonably on a home modem.

MAKE YOUR SITE EASY TO NAVIGATE


 The visitor should be able to get to any page or link in minimum num of clicks (ideally within
3 mouse clicks) from the home page.
 The visitor should always know what site he/she is on.
 Lead your visitors in the right direction.
 Keep scrolling down to a minimum by keeping individual Web pages short.
 Always have links back to your home or major sections.
Q 12 Write the following styles in separate CSS file and also show how to link this CSS
file in HTML file and show use of styles.
b. The headings should have normal font style and font’s size should be
120%
c. Define a class Arial for paragraph which defines font family Arial and
font style bold.
Apply a background color yellow and apply a background image “apple.jpg”.

Step 1: Create an external style sheet named ex1.css :-

h1,h2,h3
{
font-size:120%
}
p.arial
{
font-family:Ariel;
font-weight:bold;
}
body
{
background-color:yellow;
background-image:url(apple.jpg);
}

Step 2: Create an HTML document which makes use of the external style sheet created in above step.
<html>
<head>
<link rel=”stylesheet” type=”text/css” href=”ex1.css”/>
</head>
<body>
<h1>This text is created using header tag.</h1>
<h2>This text is also created using header tag.</h2>
<p class=”arial”>Now the para is created having the font of type Arial. This text is in bold.
The background is yellow colored having the image of apple over it.
</p>
</body>
</html>
Q 13 Write a JavaScript, that uses a loop, that searches a word in sentence held in an
array, returning the index of the word.
<html>
<head>
<script type=”text/javascript”>
function Search(form1)
{
var Sentence=form1.input.value;
var pattern=prompt(“Enter the word to be searched for:”,””);
alert(pattern);
temp=Sentence.split(“ “);
for(i=0;i<temp.length;i++)
{
if(temp[i]==pattern)
{
alert(“The word is at position:”+(i+1));
}
}
}
</script>
</head>
<body>
<form name=”form1”>
<b>Enter the sentence</b>
<input type=”text” name=”input”><br/>
<input type=”button” value=”Click me” onclick=”Search(form1)”>
</form>
</body>
</html>
Q 14 What is javascript event? List out the major events and show use of at least one
event by writing javascript code.
 Event is activity that represents a change of the state. For example mouse clicks, pressing a
particular key of the keyboard represent the events. Such events are called the intrinsic events.
 Event handler is a script that gets executed in response to these events. Thus event handler
enables the web document to respond the user activities through the browser window.
 Events are specified in lowercase letters and are case sensitives.

List of events:

Blur onblur Losing the focus <button>


<input>
<a>
<textarea>
<select>
Change onchange On occurrence of some <input>
change <textarea>
<select>
Click onclick When user clicks the <a>
mouse button <input>
Dblclick ondblclick When user double <a>
clicks the mouse button <input>
<button>
Focus onfocus When user acquires the <a>
input focus <input>
<select>
<textarea>
Keyup onkeyup When user releases the Form elements such as
key from the keyboard input, button, text,
textarea and so on.
Keydown onkeydown When user presses the Form elements such as
keydown input, button, text,
textarea& so on.

Keypress onkeypress When user presses the Form elements such as


key input, button, text,
textarea and so on.
Mousedown onmousedown When user clicks the Form elements such as
left mouse button input, button, text,
textarea and so on.
Mouseup onmouseup When user releases the Form elements such as
left mouse button input, button, text,
textarea and so on.
Mousemove onmousemove When user moves the Form elements such as
mouse input, button, text,
textarea and so on.
Mouseout onmouseout When the user moves Form elements such as
the mouse away from input, button, text,
some element textarea and so on.
Mouseover onmouseover When the user moves Form elements such as
the mouse away over input, button, text,
some element textarea& so on.
Load onload After getting the <body>
document uploaded
Reset onreset When the reset button <form>
is clicked
Submit onsubmit When the submit <form>
button is clicked
Select onselect On selection <input>
<textarea>
Unload onunload When user exits the <body>
document

JAVASCRIPT EVENT PROGRAM:


onsubmit:
<!DOCTYPE html>
<html>
<head>
<script>
functionconfirmInput()
{
fname = document.forms[0].fname.value;
alert("Hello " + fname + "! You will now be redirected to www.w3Schools.com");
}
</script>
</head>
<body>
<form onsubmit="confirmInput()" action="http://www.w3schools.com/">
Enter your name: <input id="fname" type="text" size="20">
<input type="submit">
</form>
</body>
</html>
onclick:
<!DOCTYPE html>
<html>
<head>
<script>
functionmyFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script></head>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body></html>
Q 15 Explain XSL and XSLT with example.

XSL

XSL stands for EXtensibleStylesheet Language.

CSS = Style Sheets for HTML

HTML uses predefined tags. The meaning of and how to display each tag is well understood.

CSS is used to add styles to HTML elements.

XSL = Style Sheets for XML

XML does not use predefined tags, and therefore the meaning of each tag is not well understood.

A <table> element could indicate an HTML table, a piece of furniture, or something else - and
browsers do not know how to display it!

So, XSL describes how the XML elements should be displayed.

XSL - More Than a Style Sheet Language

XSL consists of four parts:

 XSLT - a language for transforming XML documents


 XPath - a language for navigating in XML documents
 XSL-FO - a language for formatting XML documents (discontinued in 2013)
 XQuery - a language for querying XML documents

XSLT

XSLT is a language for transforming XML documents into XHTML documents or to other XML
documents.

XPath is a language for navigating in XML documents.

What is XSLT?

 XSLT stands for XSL Transformations


 XSLT is the most important part of XSL
 XSLT transforms an XML document into another XML document
 XSLT uses XPath to navigate in XML documents
 XSLT is a W3C Recommendation
XSLT = XSL Transformations

XSLT is the most important part of XSL.

XSLT is used to transform an XML document into another XML document, or another type of
document that is recognized by a browser, like HTML and XHTML. Normally XSLT does this by
transforming each XML element into an (X) HTML element.

With XSLT you can add/remove elements and attributes to or from the output file. You can also
rearrange and sort elements, perform tests and make decisions about which elements to hide and
display, and a lot more.

A common way to describe the transformation process is to say that XSLT transforms an XML
source-tree into an XML result-tree.

XSLT Uses XPath

XSLT uses XPath to find information in an XML document. XPath is used to navigate through
elements and attributes in XML documents.

In the transformation process, XSLT uses XPath to define parts of the source document that should
match one or more predefined templates. When a match is found, XSLT will transform the matching
part of the source document into the result document.

Example:

XML CODE:

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

<catalog>

<cd>

<title>Empire Burlesque</title>

<artist>Bob Dylan</artist>

<country>USA</country>

<company>Columbia</company>

<price>10.90</price>

<year>1985</year>

</cd>

<cd>

<title>Hide your heart</title>


<artist>Bonnie Tyler</artist>

<country>UK</country>

<company>CBS Records</company>

<price>9.90</price>

<year>1988</year>

</cd>

<cd>

<title>Greatest Hits</title>

<artist>Dolly Parton</artist>

<country>USA</country>

<company>RCA</company>

<price>9.90</price>

<year>1982</year>

</cd>

<cd>

<title>Still got the blues</title>

<artist>Gary Moore</artist>

<country>UK</country>

<company>Virgin records</company>

<price>10.20</price>

<year>1990</year>

</cd>

<cd>

<title>Eros</title>

<artist>Eros Ramazzotti</artist>

<country>EU</country>
<company>BMG</company>

<price>9.90</price>

<year>1997</year>

</cd>

</catalog>

XSLT Code:

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

<xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

<html>

<body>

<h2>My CD Collection</h2>

<table border="1">

<trbgcolor="#9acd32">

<th>Title</th>

<th>Artist</th>

</tr>

<tr>

<td><xsl:value-of select="catalog/cd/title"/></td>

<td><xsl:value-of select="catalog/cd/artist"/></td>

</tr>

</table>

</body>

</html>
</xsl:template>

</xsl:stylesheet>

Result:
Q.16 Develop XML document that will hold player (Like Cricket) collection with field
for player-name, age, batting-average and highest-score, write suitable document type
definition and schema for the XML
ANSWER:
CricketTeam.xml
<?xml version='1.0' encoding='UTF-8' ?>
<CricketTeam>
<Team country='India'>
<player>Sachin</player>
<age>40</age>
<batting_average>53.78</batting_average>
<highest_score>200</highest_score>
</Team>

<Team country='Australia'>
<player>smith</player>
<age>26</age>
<batting_average>60.18</batting_average>
<highest_score>200</highest_score>
</Team>

<Team country='West Indies'>


<player>Gayel</player>
<age>36</age>
<batting_average>50.78</batting_average>
<highest_score>215</highest_score>
</Team>
</CricketTeam>

DTD for Cricket.xml


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPECricketTeam [
<!ELEMENT Team(country, player,age, batting_average, highest_score)>
<!ELEMENT country (#PCDATA)>
<!ELEMENT player (#PCDATA)>
<!ELEMENT age (#PCDATA)>
<!ELEMENTbatting_average (#PCDATA)>
<!ELEMENThighest_score (#PCDATA)>
]>

XML SCHEMA:
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema>
<xs:element name="CricketTeam">
<xs:complexType>
<xs:sequence>
<xs:element name="Team" type="xs:string"/>
<xs:complexType>
<xs:sequence>
<xs:element name="country" type="xs:string"/>
<xs:element name="player" type="xs:string"/>
<xs:element name="age" type="xs:string"/>
<xs:element name="batting_average" type="xs:string"/>
<xs:element name="highest_score" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Q 17 Explain cookies in PHP.
Cookies:

 Cookie is a small file that server embeds in the user's machine.


 Cookies are used to identify the users.
 A cookie consists of a name and a textual value. A cookie is created by some software
system on the server.
 In every HTTP communication between browser and a server a header is included. The
header stores the information about the message.
 The header part of the http contains the cookies.
 There can be one or more cookies in browser and server communication.

PHP support for Cookies

 PHP can be used to create and retrieve the cookies.


 The cookie can be set in PHP using the function called setcookie()
 The syntax for the cookie is-

setcookie(name,value,expire_period,path,domain)

 Following is a simple PHP document which illustrates how to set the cookies-

PHP Document(CookieSetDemo.php)
<?php
$Cookie_period=time()+60*60*24*30;
setcookie("Myname", "Kruti",$Cookie_period);
?>

Note that you have got the blank screen it indicates that the cookie is set. In above PHP document we
have set the PHP script for one month. Just observer the third parameter of the setcookie function.
Now you can retrieve the cookie and read the value to ensure whether or the cookie is set.

PHPDocument[CookieReadDemo.php]
<html>
<head><title>Reading Cookies</title>
<body>
<?php
if(isset($_COOKIE["MyName"]))
echo"<h3>Welcome".$_COOKIE[Myname"]."!!!</h3>";
else
echo"<h3>Welcome guest</h3>";
?>
</body>
</html>

Program Explanation:
The isset function is used for checking whether the cookies is set or not. Then using the $_COOKIE
the value of the cookie can be retrieved.
Q: 18 Explain session in PHP.

An alternative way to make data accessible across the various pages of an entire website is to use a
PHP Session.

A session creates a file in a temporary directory on the server where registered session variables and
their values are stored. This data will be available to all pages on the site during that visit.

The location of the temporary file is determined by a setting in the php.ini file called
session.save_path. Bore using any session variable make sure you have setup this path.

When a session is started following things happen −

PHP first creates a unique identifier for that particular session which is a random string of 32
hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.

A cookie called PHPSESSID is automatically sent to the user's computer to store unique session
identification string.

When a PHP script wants to retrieve the value from a session variable, PHP automatically gets the
unique session identifier string from the PHPSESSID cookie and then looks in its temporary directory
for the file bearing that name and a validation can be done by comparing both values.

A session ends when the user loses the browser or after leaving the site, the server will terminate the
session after a predetermined period of time, commonly 30 minutes duration.

Starting a PHP Session

A PHP session is easily started by making a call to the session_start() function.This function first
checks if a session is already started and if none is started then it starts one. It is recommended to put
the call to session_start() at the beginning of the page.

Session variables are stored in associative array called $_SESSION[]. These variables can be accessed
during lifetime of a session.

The following example starts a session then register a variable called counter that is incremented each
time the page is visited during the session.

Make use of isset() function to check if session variable is already set or not.

Put this code in a test.php file and load this file many times to see the result −

<?php

session_start();

if(isset( $_SESSION['counter'] ) ) {

$_SESSION['counter'] += 1;

}else {

$_SESSION['counter'] = 1;
}

$msg = "You have visited this page ". $_SESSION['counter'];

$msg .= "in this session.";

?>

<html><head>

<title>Setting up a PHP session</title>

</head><body>

<?php echo ( $msg ); ?>

</body></html>

It will produce the following result −

You have visited this page 1in this session.

Destroying a PHP Session

A PHP session can be destroyed by session_destroy() function. This function does not need any
argument and a single call can destroy all the session variables. If you want to destroy a single session
variable then you can use unset() function to unset a session variable.

Here is the example to unset a single variable −

<?php

unset($_SESSION['counter']);

?>

Here is the call which will destroy all the session variables −

<?php

session_destroy();

?>

Turning on Auto Session

You don't need to call start_session() function to start a session when a user visits your site if you can
set session.auto_start variable to 1 in php.ini file.

Sessions without cookies

There may be a case when a user does not allow to store cookies on their machine. So there is another
method to send session ID to the browser.
Alternatively, you can use the constant SID which is defined if the session started. If the client did not
send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to
an empty string. Thus, you can embed it unconditionally into URLs.

<?php

session_start();

if (isset($_SESSION['counter'])) {

$_SESSION['counter'] = 1;

}else {

$_SESSION['counter']++;

$msg = "You have visited this page ". $_SESSION['counter'];

$msg .= "in this session.";

echo ( $msg );

?><p>

To continue click following link <br />

<a href = "nextpage.php?<?php echo htmlspecialchars(SID); ?>">

</p>

It will produce the following result −

You have visited this page 1in this session.

To continue click following link


Q.19Write PHP code for database connectivity. Apply insert and delete
operation with proper example.

<?php

$con = mysqli_connect("localhost", "root", "root", "dbtest");


if($con === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
$uname = 'John';
$email = 'john@gmail.com';
$upass = 'john';
$sql = "INSERT INTO users(username,email,password) VALUES ('$uname','$email','$upass')";
if(mysqli_query($con,$sql)){
echo "Record Added!";
}
else {
echo "Error Occured!";
}
echo "<br />";
$del = "DELETE from users where user_id = 1";
if(mysqli_query($con,$del)) {
echo "Record Deleted!";
}
else {
echo "Error Occured!";
}
?>
Q 20 WRITE A PHP PROGRAM TO UPLOAD IMAGE. AND ALSO CHECK FILE
SIZE SHOULD NOT GREATER THAN 30 KB.
ANSWER:

<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
$file_type = $_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));

$expensions= array("jpeg","jpg","png");

if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}

if($file_size > 30000) {


$errors[]='File size must be greater than 30kb';
}

if(empty($errors)==true) {
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
?>
<html>
<body>

<form action = "" method = "POST" enctype = "multipart/form-data">


<input type = "file" name = "image" />
<input type = "submit"/>

<ul>
<li>Sent file: <?php echo $_FILES['image']['name']; ?>
<li>File size: <?php echo $_FILES['image']['size']; ?>
<li>File type: <?php echo $_FILES['image']['type'] ?>
</ul>

</form>

</body>
</html>

OUTPUT:
Q 21. Write a program to create a cookie and retrieve data of that cookie.

<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

<p><strong>Note:</strong> You might have to reload the page to see the value of the cookie.</p>

</body>
</html>
Q. 22 Write a program to modify cookie value.
<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

<p><strong>Note:</strong> You might have to reload the page to see the new value of the
cookie.</p>

</body>
</html>

You might also like