Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

List any two features of HTTP protocol. 5.

What will be the output of the


& What is HTTP? following?
Solution: <?Php
HTTP stands for Hypertext Transfer $ a = "LK9";
Protocol. $a++;
Following are the features of HTTP: Echo $a;
i.HTTP defines a set of rules regarding ?>
how messages are formatted and Solution
exchanged between server and browser. LLO
ii. HTTP is stateless protocol because each 6. List any four web browser
command is executed independently. names.?&Give two examples of web
2. What is web browser?& What is the browsers.
role of web server and web browser? Solution:
Solution: Safari, Opera, Google Chrome, Mozilla
A web browser is an application software Firefox.
designed to enable users to access, 7. State the advantages of PHP.
retrieve, present and view documents and Solution:
other resources on the World Wide Web. PHP language has its roots in C and C++.
An information resource is identified by a PHP syntax is most similar to C and C++
Uniform Resource Locator(URL) and may language syntax. So, programmers find it
be a web page, image, video or other easy to learn and manipulate. PHP can run
piece of content. on both UNIX and windows servers.
Example: Mozilla Firefox, Google Chrome 8. What is the difference between == and
etc. ===?
A web server is a program that uses HTTP & What is the difference between
(Hypertext Transfer Protocol) for equality and identity operators? ,
accepting requests from clients, such as Solution:
web browsers, serving them responses '==' should be used to check if the values
along with optional data contents, which of the two operands are equal or not. On
are usually web pages. the other hand, '===' checks the values as
Example: Apache IIS, ssl, http etc. well as the type of operands.
4. What is type casting? 9. "Keywords are case sensitive in PHP".
Solution: Justify True and False.
Type casting is converting a variable or Solution: False. Keywords are case
value into a desired data type. insensitive in PHP.
Type casting in PHP is done by the 10. State the features of PHP.
interpreter. Solution :
PHP also allows you to cast the data type. Loosely Typed Language: PHP supports
This is known as explicit casting. The code variable usage without declaring its data
below demonstrates explicit type casting. type.
<?php It will be taken at the time of the
$a - 1; sb - 1.5; execution based on the type of data it has
Sc - Sa + $b; on its value. ii. Cross Platform
Sc – Sa + (int) $b; Compatibility: It is used to create the
echo $c; desktop application by using
?> advanced PHP features.
11. Write the output of the following PHP PHP.A common example of using the
script. resource data type is a database
$White = "show"; call.
$black = &$white; A variable of data type NULL is a variable
unset($White); that has no value assigned to it.
print $black; 16. State whether the following variables
Solution: are valid or invalid:
Output: show a.$_Underscore
12. What is an Interpolation? b. 7x
Solution: Solution:
In PHP programming, string interpolation In PHP, a variable starts with the $ sign,
or variable interpolation, variable followed by the name of the variable.
substitution, or variable expansion) is the A variable name cannot start with a
process of evaluating a string literal number so 7x is invalid variable name.
containing one or more placeholders, $_Underscore is a valid variable name as a
yielding a result in which the placeholders variable name must start with a letter or
are replaced with their corresponding the underscore character.
values. 17. Differentiate between static and
13. Write purpose of resource data type dynamic web pages.
with suitable example. Solution: Static web pages: Static web
Solution: pages display the exact same information
The special resource type is not an actual whenever anyone visits it. Static web
data type. It is the storing of a reference pages do not have to be simple plain text.
to functions and resources external to They can feature detailed multimedia
PHP. design and even videos. However, every
A common example of using the resource visitor to that page will be greeted by the
data type is a database call. exact same text, multimedia design or
When we connect the database with the video every time he visits the page until
required configuration details like, you alter that page's source code.
$Conn = mysql_connect(localhost, "root", Dynamic web pages: Dynamic web pages
"admin", "passw"); are capable of producing different content
The function will return a resource type for different visitors from the same source
data to be stored into $Conn variable. code file. The website can display
14. Which operator is used to compare different content based on what
data as well as data type? operating system or browser the visitor is
Solution using, whether she is using a PC or a
The === operator is used in php to mobile device, or even the source that
compare the data as well as the data type. referred the visitor.
15. What are the special data types in Developers generally create static pages
PHP? with HTML, but use languages like PHP,
Solution: JavaScript or ActionScript to create
The two special data types in php are dynamic pages.
RESOURCE and NULL.
The special resource type is not an actual
data type. It is the storing of a reference
to function and resources external to
18. Which of the following variable name Step 3: PHP receives the file it reads
is valid or invalid? through it and executes any PHP code it
i.$666666xyz can find. During
ii. $File-name this step, PHP may interact with
Solution: databases, the file system or make
$666666xyz is invalid and $File-name is external API class, amongst other things.
invalid. After it is done with the file, the PHP
19. What will be the following statement interpreter gives the output of the code, if
output? any, back to Apache.
print gettype("4"); Step 4: Apache gets the output back from
Solution: PHP, it sends that output back to a
The output of the above statement will be browser. This is called the web response.
string. The user's browser receives the response
20. Give at least two examples of Web from server and renders the webpage to
Server. the screen.
Solution: 2. Explain the following statements with
i.Apache web server syntax and example.
ii.IIS (Internet Information Server) i. while statement
21. "Php does not require explicit ii. switch statement
variable declaration". Justify T/F. Solution
Solution while statement: A while loop is a control
True. PHP does not require explicit flow statement which consists of a block
variable declaration, php automatically of coc and a condition / expression. The
converts the variable to the correct data condition/expression is evaluated, and if
type, depending on its value as and when the condition expression is true, the code
they are declared in the program. within the block is executed.
22. Will comparison of string "15" and This repeats until the
integer 15 work in PHP? condition/expression becomes false. It is
Solution: an entry-controlled loop. In while loop, we
Yes comparison of string 15 and integer 15 can use the break and continue keywords
will work in PHP. to end the loop or the current iteration.
Answer the following (5 Marks Questions) Syntax:
: while(condition/expression)
1.Explain the execution of php script {
using diagram. I body of loop;
Solution: }
Step 1: The user types in the URL of PHP Alternative Syntax:
website in a Web Client(browser). The while (condition/expression):
client issues 1/ body of loop; endwhile;
• a HTTP request to the server(Let Example:
Apache). <?php.
Step 2: Server gets this request and $i=0;
analyses the request, it looks for while ($1<3)
requested file. If a requested file is found, echo "We are learning PHP<br>";
then Apache gives it to the PHP $ユ++i
interpreter. Otherwise, gives error. ?>
Output:
We are learning PHP default: echo "Invalid Choice";
We are learning PHP • Introduction to HTML, HTTP ...
We are learning PHP VISION
switch statement: A switch statement is a Output:
type of selection control mechanism used ?>
to allow the value of a variable or Php
expression to change the control flow of Explain the features of HTTP protocol.
program execution via search and map. solution
Switch statement is a multiway branch The Hypertext Transfer Protocol (HTTP) is
statement. an application-level protocol for
A switch statement is given an expression distributed formation systems. HTTP is a
and compares its value to all cases in the TCP/IP based communication protocol,
switch all statements in a matching case that is used to deliver ita (HTML files,
are executed, up to the first break image files, query results, etc.) on the
keyword it finds. If n match is found, and a World Wide Web. The default port is CP
default is given, all statements following 80, but other ports can be used as well.
the default keyword are execute up to the There are following three basic features
first break keyword encountered. that make HTTP a simple but a powerful
Syntax: protocol.
switch (expression) i.HTTP is connectionless: The HTTP client
case value: break; is a browser which initiates an HTTP
case value: request, and after a request is made, the
break; client disconnects from the server and
case value: waits for a response The server processes
break; the request and re-establishes the
default: connection with the client to send
Alternative syntax: response back.
switch (expression): ii.HTTP is media independent: Any type of
case value : data can be sent by HT TP as long as both
break; the client and the server know how to
case value: handle the data content. It is required for
break; the client a well as the server to specify
case value : the content type using appropriate MIME-
break; type.
default: iii.HTTP is stateless: HTTP is a stateless
endswitch; protocol because each command is
Example: execute independently. A stateless
<?php protocol does not require the server to
$x - 2; retain information o status about each
switch ($x) user for the duration of multiple request.
{
case 1 : echo "java";
break;
case 2 : echo "php";
break;
case 3 : echo "syspro";
break;
4. Explain scope of a variable in PHP with Output:
suitable example. 21
& To access global variables without global
How to define variable in PHP? Explain in keyword, PHP's GLOBALS array can be
detail scope of variables. used for accessing the variables directly
Solution: iii.Static Variable: Normally, all local
In PHP, variables can be declared variables are deleted when a function is
anywhere in the script. completed/ executed. However, if we
The scope of a variable is the location of want local variable not to be deleted then
the variable's declaration where the it should be declared as static variable. A
variable can b referenced/used. static variable retains its value between
PHP has three different variable scopes: calls to a function but is visible only within
i.local ii. global iii.static that function. Static variable is declared
i. Local scope: A variable declared within a with the static keyword.
function has a local scope. It can only Example:
accessed within that function. It is not <?php
accessible outside the function. function change ()
Example: <?php {
function myfunction () static §x;
$x = 2121; //local scope $x++;
echo "Local Variable : $x"; echo "<br >Static variable current value :
myfunction ()i Sx";
?> change (; change (; change () ;
Output: ?>
2121 Output:
Using Sx outside the function will Static variable current value: 1
generate an error. Static variable current value: 2
ii.Global Scope: A variable declared Static variable current value: 3
outside a function has a global scope.
They can be accessed from any part of the
program. However, by default, they are
not available inside function.
To access a global variable within the
function, it should be declared with the
help of global keyword inside the
function. Example, global Svar_name;
Example:
<?php
function change ()

global $cnt;
$cnt++i
Output:
Sent = 20;
change () ;
echo Scnt;
?>
5. What is data type? List different data 6. Write the difference between break
types in PHP? Explain any two. and continue statement of PHP with an
01310, example.
Solution: Solution:
Variables can store data of different types, Break
and different data types can do different break statement is used to skip the entire
things. loop construct
PHP supports the following data types: break statement can also be used in
і.String switch statement to break switch
ii. Integer construct
iii.Float (floating point numbers - also Syntax:
called double) iv. Boolean break;
v. Array vi. Object vii. NULL Example: <?php
VIT - RESOURCE For ($1=0:$1<5:$1++)
i. PHP string: A string is a sequence of }
characters, like "Hello world!". echo "<br>Hello $i";
A string can be any text inside quotes. You if ($i>=3)
can use single or double quotes: <?php break;
$x = "Hello world!"; echo "‹br>bye Si";
$y = "Hello world! ?>
echo $x; Output:
echo "<br>"; Hello 0 bye o
echo $y; Hello 1
S bye 1
?> Hello 2
PHP Integer: An integer data type is a non- bye 2
decimal number between -2,147,483,648 Hello 3
and 2,147,483,647. Continue
Rules for integers: continue statement is used to skip current
An integer must have at least one digit. iteration and continue with the next
An integer must not have a decimal point. iteration continue statement can also be
An integer can be either positive or used in switch statement to skip a case
negative. Syntax:
Integers can be specified in three formats: continue;
decimal (10-based), hexadecimal (16 Example: <?php
based - prefixed with 0x) or octal (8-based for($i=0;$i<5;$i++)
- prefixed with 0). echo "<br>Hello Si";
In the following example Sx is an integer. 1£($1>=3)
The PHP var_dump function returns the continue;
data type and value: echo "<br>bye $i";
<?php }
$x = 5985; 3>
var_dump (5x); Output:
?> Hello 0 bye O
Output: int(5985) Hello 1
bye 1
Hello 2
bye 2 the development of web application.
Hello 3 It is used for back-end development.
Hello 4 PHP codes are dynamic
7. Explain the concept of variable PHP can't be used in an HTML file
variables with an example. 9.Compare between include() and
Solution require()
We can set variable name dynamically in Include()
PHP with the help of variable variables i.include will only produce a
concept. warning(E_WARNING) and the script will
Such a variable uses value of an existing continue.
variable as a name. It is defined with two ii.Use include, If you want the execution
S signs as prefix. to go on and show users the output, even
Example 1: <?php if the include file is missing.
$x = 'holiday'; iii.include 'filename';
$$x = 'sunday'; Require()i. Require will produce a fatal
echo $Holiday; error e_compile_error and stop the script
?> ii.In case of framework coma CMS or a
Output: complex PHP application coding always
sunday use required to include a key file to the
Example 2: <?php flow of execution. This will help to avoid
$a = 'PHP'; compromising your application security
$b = 'a'; and integrity Just in case one key file is
$c = 'b'; accidentally missing.
$ = 'c'; iii. Require’ file name’;
echo "<br>" Sa; 1. Write the purpose of explode function.
echo”<br>".$$b; Solution=The explode function is used to
echo "<br>". $$$c; split a string by a specified string into
echo "<br>".;11 $$$d; pieces and returns array of pieces, i.e, it
output: breaks a string into an array.
PHP Syntax: explode (separator, string [,
PHP limit]);
PHP The first argument, separator, specifies
PHP where to break the string
8. Explain the difference between HTML The second argument, string, is the input
and PHP. string to split.
Solution: The optional third argument, limit, is the
Differences between HTML and PHP are maximum number of values to return in
as follows: the array. If the limit is reached, the last
HTML element of the array contains the
HTML is a markup language is used to remainder of the string.
specify
the content of a web page at client side.
It is used for front-end development.
HTML codes are static.
HTML can be used in PHP files.
PHP is a server-sided scripting language
used for
2. Write the output of the following they identified as simple literals in single-
script. quoted string.
<?php 6. Write the output of the following PHP
$a = 'PHP'; script:
$b = '$a interpolation'; $str = 'abc, pqr, Imn, xyz';
echo $b; $a = explode(',', $str, 3);
?> Print_r($a);
Solution=Sa interpolation Solution=Output:
Single-quoted strings can't interpolate Array([0]=>abc [1]=>pqr [2]=>lmn,xyz)
variables. The variable name in single- Here explode() is splitted given string by
quoted string can't be expanded by its separator(,) and returns array. The third
value. argumer limit(3), is the maximum number
3. Explain implode() with suitable of values to return in the array. Hence, the
example. last element of array contains the
Solution=The implode() function returns a remainder of the string.
string from the elements of an array. 7. Write the output of the following PHP
Syntax: implode ([separator,) array); script:
separator(optional) specifies what to put <?php
between the array elements. Default is function change()
(an empty string). (Scnt++;)
Example: $cnt = 20;
<?php change();
$a = array("Best", "i", "not", "enough") echo $cnt;
$str = Implode (*, $a); Solution
echo $str; Output:
?> 20
Output: Best is not enough The Sent inside the function is local to
4. Give function to check if variable has that function. So, function will increment
value or not. its local Sent and global Sent remains
Solution=empty() function is used to unchanged. In PHP, global variables, by
check whether variable has value or not. default, are not available inside the
Empty is interpreted (an empty string), function.
(integer), 0.0(float), "0" (string), NULL, 8. What is the difference between echo()
FALSE, array()(an empty an and Svar, (a and print() functions?
variable declared, but without a value in a Solution=echo() has no return value while
class). print() has a return value of 1 so it can be
Syntax: empty (var_name) ; It returns used in expressions.
TRUE when var name exists and has an
empty or zero value. Otherwise it reten
FALSE.
5. Difference between single-quoted
string and double-quoted string.
Solution=Single-quoted string can't
interpolate variable but double-quoted
string can interpole variable.
Escape sequences are identified as white
spaces in double-quoted string whereas,
9. Explain variable function concept in Output:
PHP. float (3.1) bool(true)
Solution=In PHP, we can store name of 12. "A function can have variable number
function inside variable called as variable of arguments." State true or false.
function. Calling of function is based on Solution=True. A function can have
the value of variable. To make a variable variable number of arguments instead of
function call, we have to include the fixed number arguments. All parameters
parameters for a function in parentheses can be retrieved using functions ie.. fune
after the variable. get_args(), func get and func_num_args()
Example: 13. How to find out the position of the
<?php first occurrence of a substring in string?
functionadd(5a, 3b) Solution=strpos(): Finds the position of
echo "Addition is ". (Sa+5b); the first occurrence of a substring in a
} Sresult 'add' $result (5,2); string strpos(string, find, start)
Output: string Required=Specifies the string to
Addition is 7 search.
10. Write an anonymous function to find find start=Required. Specifies the string to
maximum of two numbers. find.
& Write an anonymous function to find Start=Optional. Specifies where to begin
the largest of two numbers. the search.
Solution <?php
<?php echo strpos("I love php, I love php
$max = create_functon too!","php");
('$a,$b',return($a>$b)?$a:$b;*); echo ?>
"Maximum Nmber : $max (5,2); Output
?> 7
Output: 14. State True or False:
Maximum Number: 5 "The fun n_num_args() returns function."
11. Explain the following function with an array of all parameters provided to
syntax and example: the
var_dump Solution=False. The function func num
Solution=var dump: Dumps information args returns the number of arguments
about a variable. passed to the function and not an array.
Syntax: void var_dump(mixed $expression Consider the following example:
, mixed $... 11) <?php
This function displays structured function fool()
information about one or more $numargs func num args();
expressions that include type and value. echo "Number of arguments:
Arrays and objects are explored $oumargs\n";
recursively with values indented to foo(1, 2, 3)
structure. Output
Example: Number of arguments: 3
<?php 15. What will be the output of the
$b-3.1. following PHP script?
$c true; $ str = "String Extraction";
var dump($b, $c); print substr($ str, 2, -11);
?> Solution
Output: ereg("C[aeiov]t', 'cart');
ring Solution=The ereg function searches a
Explanation: string for matches to the regular
substr(string, start, length) returns a part expression given pattern in a case-
of string sensitive way.
According to given string. 2 parameter ereg (string $pattern, string $string [,
start = 2 specifies part of string starts from array &$reqs])
2 index And 3 parameter length = -11 In the expression given, the pattern starts
specifies the length to be returned from first letter with capital C and the string to
the end of string. earched in is starting with small 'c' and we
16. Which function return array are searching for "cart" which is not there
containing all parameters passed to the in t xpression. So it will return a Boolean
function? value false for not found.
Solution=func_get_args() function return 9. What is heredoc? Give example.
array containing all parameters passed to &What is the use of here document?
the function. Solution=PHP introduces a more robust
Example: string creation tool called heredoc that
<?php lets the programe tate multi-line strings
functionfun() without using quotations. The heredoc is
{ used to spanning multiple string.
$params func get args()) <?php
print_r($params); $str - <<<DEMO
} This is a
fun('SureshAgrawal', 'NSGAcademy', 'WT', demo mensage
'VisionPublication with heredos,
?> DEMO
Output: echo $str;
Array ([0] =>Suresh Agrawal [1] ?>
=>NSGAcademy [2] => WT [3] Vision Output:
Publications) This is a demo message with heredoc.
17. Write syntax of function which is used The heredoc starts with the <<<< operator
to create string from an smaller string. and an identifier. After it we can type our
Solution=The implode() function returns a text in more lines as if it were a double
string from the elements of an array. quoted string. It means that we can use
Syntax: variables inside the heredoc.
implode (separator, array) If we are ready with our text we only need
where separator: Specifies what to put to write the identifier again in a new line
between the array elements. Default is as follows:
""(An empty string) <?php
<?php $name "Max";
Sarr array('Hello', 'World!', 'Beautiful', Satr - <<<<DEMO
'Day!"); Hello $name! <br/>
echo implode("-", Sarr)."<br>"; This is a demo message with heredoc.
Output: DEMO:
Hello-World!-Beautiful-Day! echo $ser;
18. What is the output of the following Output:
regular expression:
Hello Max! This is a demo message with 25. Find the output
heredoc. It is not allowed to indent the <?php
closing tag if you do so you will get a $a= array (1, "Shilpa", "T.Y.B.Sc");
parsing error. var_dump($a);
20. Find the output: Solution=The output of above code
<?php fragment is:
$str ="Welcome"; echo "You are $str "; array(3)
?> [0]-> int(1)
Solution=Output: [1]=> string(6) ""Shilpa"
You are Welcome. [2]=> string(9) "T.Y.B.Sc."
21. What is the use of Levenshtein 26.Write lambda function for
algorithm? multiplication of two integers.
Solution=levenshtein() calculates Solution=The lambda function for
similarity of two strings based on how multiplication of two integers can be
many characters must be added, written as follows:
substituted or removed to make them <?php
same. Spro create function('Sa, Sh', 'return Gabri
Syntax: levenshtein (atring_1,atring_2) echo Spro (231
Example: ?>
<?php 1. Explain the following functions with
$a="sun"; example.
$b= "sun"; 1. ucwords()
$ans=levelshtein($a,$b); ii. trim()
echo "No. of characters added or deleted Ⅲ. str_pad()
is ".$ans; iv. ucfirst()
?> V. chunk_split()
Sans levenshtein($a,$b); Solution=1. ucwords(): It converts the first
Output: No. of characters added or character of each word in a string to
deleted is 1. uppercase and returns modified string.
22. How to find the number of parameters Syntax: ucwords(string);
passed to the function? Example: <?php
Solution=The function func_name_args() $str= "nsg academy";
returns the number of arguments passed $str1-ucwords($str);
to the function. echo $strl:
23 . What is the difference between Output:
strcmp() and strcasecmp(). $str="Nsg Academy";
?> trim(): It removes all whitespaces from the
Solution=i. strcmp(): This function beginning and end of a string and returns
compares two strings along with their modified string.
cases. Syntax:
ii. strcasecmp(): This function compares trim(string);
two strings ignoring the cases. Itrim() and rtrim() functions are used to
24. Which function is used for matching remove whitespaces from left side only
regular expression with a string. and right side only simultaneously.
Solution=The preg match() function Example:
searches string for pattern, returning true <?php
if pattern exists, false otherwise. $str = "nsg academy";
$str1-trim($str); A parameter is just like a variable and is
echo $strl specified after the function name, inside
Output: the parentheses. If more than one
nsg academy parameter is passed, then they are
iii. str_pad(): It is used to pad a string to a separated by commas.
given length and returns modified string Example:
W either pad string to both sides, right <?php
side only or left side only by specifying in function display($subject)
op {
parameter. echo "We are learning $subject";
Syntax: str_pad(string, length, padded }
atring(,padding_type]); display("php");
padding type: STR_PAD_BOTH, ?>
STR_PAD_LEFT, STR_PAD_RIGHT Output:
Default padding type is STR_PAD_RIGHT We are learning php
Example: Default parameters: Arguments passed by
<?php value
$str nag academy"; A default parameter allows us to pass
Satrl-str_pad($str, 15, **, STR_PAD_LEFT); default value to the argument in the
echo $str1; function definition. If actual parameter is
Output: **nsg academy not passed then formal parameter will be
iv. ucfirst(): It converts the first character assigned by default value. A function can
of a string to uppercase and returns modir have no or any number of default
string. parameters.
Syntax: Example:
ucfirst(string); <?php
Example: <?php function display($subject="php")
$str "nsg academy": echo "We are learning $subject<br>";
$str1 ucfirst(Satr); display();
echo $str1; display("java");
Output: Nsg academy Output:
V. chunk split(): It is used to split a string We are learning php
into a series of small parts(chunks) of We are learning java
speci length followed by an end string. Arguments passed by reference: If
Syntax: chunk_split(string, length, end), arguments are passed by reference to a
Example: function, then
<?php Satr "nsg academy"; y change in the formal parameter reflects
Satri-chunk_nplit($str, 2, ""); the value of actual parameter. Referenced
echo $strl, parameter
Output: followed by &(ampersand). If more than
ns*gacademy* one parameter is passed, then they are
2.Explain different types of arguments separated by mmas.
passing to function with example. Example: <?php
Solution=There are following 4 types of function change(&Saub)
arguments passing to function: {
Variable parameters: Arguments passed $sub "php";
by value. }
$subject = "Java"; echo "<br>All Words - First Letter Capital :
echo "We are learning Saubject<br>"; *.$str4)
change ($subject); echo "<br>Minimum Length of 17
echo "We are learning subject<br>"; characters: ".str5;
Output: 4. What is an Anonymous function? How
We are learning java is it different from normal function?
We are learning php & Explain anonymous function concept in
Retrieving Parameters: A function can PHP.
have any number of parameters passed to Solution=A function without a specified
specifying in parenthesis. We can retrieve name is called as anonymous function. It
parameters using built-in function is also known as closures or lambda
func_num args(), func_get_arg(), function. Normal function must be
func_get_args(). specified with a name.
Example: i .Anonymous functions are declared at
<?php runtime whereas normal functions are
function display() declared at compile time.
{ ii. Execution of anonymous function is
$n-func_num_args() faster than normal function.
for($i=0;$i<$n;$i++) Anonymous function is stored in a variable
echo "We are but normal function isn't stored in a
learning.func_get_arg($i)."<br>"; variable.
display("php", "java", "tos", "syspro"); iv. Anonymous functions are most useful
Output: in callback parameters where it can be
We are learning php used as argüments to other functions.
We are learning java Example of Normal Function
We are learning tes <?php
We are learning syspro function add (5a , Sb)
3. Consider a string $str = "PUNE {
UNIVERSITY"; write a PHP script to disp return $a-$b;
above string in the format given below }
using built-in functions: ↓ echo "Total is .add(5,3);
1. pune university ?>
II. PUNE UNIVERSITY Output: 8
iii. Pune university Anonymous functions are created using
iv. Pune University create function() function. This function
Solution takes two parameters enclosed in single
<?php quote, the first describes the actual
$str = "PUNE UNIVERSITY"; parameters that the anonymous function
$strl = strtolower($str); takes in and the second is the actual code.
$str2 =strtoupper($str1); Syntax: create_function(args_string,
$str3 =ucfirst (str1); code_string);
$str4= ucwords($str1); Example of Anonymous Function
$str5=str_ pad ($str4,17,'*') ; <?php
echo "<br>LowerCase: "$str1; $fun create_function('Sa, sb', 'return Sa
echo "<br>UpperCase: "$str2; $b;');
echo "<br>Firat Word First Letter Capital: echo "Total is "$fun (5,3);
$str3; ?>
Output: 8 Solution:
CC stands for carbon copy which me that
whose address appears after the cc
Answer the following (1) Mark header would receive a copy of the copy
Questions): message. Also, the cc header would also
Marks for these Questions may vary from appear inside the header of the received
1 to 2 message. Bee stands for blind carbon copy
1. Which are the two parts while which is similar to that of Ce except that
messages are sent using SMTP protocol? the Email recipients specified recipients in
Solution the d in this field do not appear in the
The messages contain two parts, Le, body received message hedera
and header, which are sent wing SMTP. A
message header contains the basic 5 To or Ce fields will not know that a
information as sender's email address and copy sent to these addresses. Which
recipient addresses A message body is the protocol is used to send an e-mail?
email's content. Solution
"POP3 Protocol is used to receive the SMTP in the acronym for Simple Mail
email." True/False. Justify. 2. Transfer Protocol, and an SMTP server is
Solution the machine that runs this protocol and
True. The POP (Post Office Protocol)3 sends out the mail.
protocol is used to access mailboxes and 6 How to set response header in PHP?
download messages from the mail server Solution
to local computer of the user. Response headers in PHP are set with the
3. Write syntax of mail () function. header () .php header ("Content-Type:
& Write the different parameters used in text/plain"); 25
mail (). 7. What is use of checkdnsr().
Solution Solution
Mail () is used to send emails from the Checkdnsrr () function will take an email
PHP script. It returns 1(true) on success address and performance a DNS lookup
otherwise 0(false). on the specified host (either a hostname
Syntax: or IP address) We can use this function
Mail (string $to, string $subject, string before sending ma The function returns
$message (string $additional_headers an error informing the user that the
(string $additional_parameters))) domain related to email ad probably
10: single or multiple receivers of the mail. doesn't exist.
This is an email address. Syntax: bool checkdnsrr (string $host[ ,
subject: subject of the email to be sent. string $type=MX"])
message: message to be sent. 8. Write the protocols used to retrieve
additional headers: optional parameter. email from server. OR
This is typically used to add extra Which protocols are used to retrieve mail
headers (from, cc, bcc). from the server?
additional parameters: optional Solution: The protocols that are used to
parameter. It specifies an additional retrieve mail from the server are POP3,
parameter to the send mail program. IMAP.
9. When IMAP4 protocol is used in email
Differentiate between CC and BCC field handling?
from an email header Solution:
The Internet Message Access Protocol is IMAP (Internet Message Access Protocol)
an application Layer Internet protocol that is a standard protocol for accessing email
ally an e-mail client to access e-mail on a from server.
remote mail server. Features of IMAP protocol:
10. 'SMTP protocol is used to send email'. 1. It is a client/server protocol in which
Justify true/false. email is received and stored by internet
Solution: True. The SMTP (Simple Mail server.
Transfer Protocol) protocol is used by the ii.With IMAP, user's email stays on the
Mail Tran Agent (MTA) to deliver email to email server.
the recipient's mail server. The SMTP iii.This makes it possible to access your
protocol can only use to send emails, not email from anywhere.
to receive them. Iv.This works well even over a slow
Answer the following (5 Marks connection such as modem since it only
Questions) requires small data transfer
Explain how to send email through PHP V. The user can also create and
with example manipulate folders or mailboxes on the
Explain how message can be send on E- server, messages etc.
mail Server? VI. IMAP supports both on-line and off-
Solution: line modes of operations.
An e-mail can be plain test, HTML, or may
contain file attachments mail() is used to 3. Discuss how Email id validation and
send emails from the PHP script it returns verification is done in PHP? (April 2018
1(true) on success other wise 0(false) . Solution
Example: Validation is the process in which, we
<?php accept data from the user and check it
$to = "mukesh. objectes with we predefined standard. Validation is
innetsecretsgroup.com used to validate or check if the data
$subject = “HOW,s the josh”; follows certain specifications
$message = “high!!!. But Best is not In PHP, there are different ways to
Enough": validate email address.
$headers "From: Using eregi() function or eregi()
suresh.rp.agrawal@gmail.com"."\r\n" . function(the case-insensitive version of
”CC: eregi() It verifies whether the input string
suresh.rp.agrawal@ satisfies the regular expression defined by
netsecretsgroup.com"; pattern.
If (mail ($to, $subject, $message, Example:
$headers)) <?php Bemail-
echo "mall sent."; suresh.agrawal@netsenretagroup.com/
else $pattern-z0-9]+(a-2-0-9-1-13[a-z0-9-
echo "mall failed."; 1+(\.(a-z-0-9-
?> if (eregi ($pattern, $email)) echo "Valid
Email":
2. When IMAP4 protocol is used in email else echo "Invalid Email* 72
handling? Explain its features. (April Online verification of domain using
2019, 2014) checkdnsrr ()
& Explain IMAP protocol. Using checkdnstr () function we can check
Solution: our DNS record to verify the existence
domain name or not. This function will uses the host's hard drive space, and most
return true if available otherwise false. enforce storage quo for their users. IMAP
Example: can be slower to load messages than
<?php IMAP, POP3 emails are manipulate
$email="mukesh.jain@netsecret.sgroup.c rapidly, since they exist on the user's local
om"; machine. IMAP mail is only available with
$flag 1=0; $flag2=0; connected and is not available when
list ($uname, $domain)=split('@', $email): offline. In addition, some email programs
$pattern-[a-z0-9-]+(\-[a-z0-9-1)*" if have difficult supporting IMAP, though
($email ($pattern, $uname)) $flag1=1; browser-based solutions are often
if (eregi($domain, 'MX')) available.
$flag2=1; 5. Write a PHP script to accept an email
if($flagl && $flag2) and validate it. Also print domain name
echo "Valid Email"; of the email and result of validation.
Else Solution
echo "inValid Email"; The html and php files to accept an email
Using Filters and validate it and to print domain name
FILTER_VALIDATE_EMAIL o email and result of validation is as
This is a filter which validates the email follows:
wing filter_var() function email.html
Example: <form method="post"
<?php $email- action="emailvalidate.php">
visionpublication@gmail.com Enter emailed<input type="text"
if (filter_var ($email, FILTER VALIDATE name="t1"> <input type="submit"
EMAILI echo "Valid Email"; value="click here">
else <input type="reset"> </form>
echo "Invalid Email"; </HTML>
?> emailvalidate.php
<HTML>
4. Discuss the advantages and <?php
disadvantages of IMAP 4 protocol. $email-S POST['t1'];
Solution if (! filter_var ($email,
Advantages FILTER_VALIDATE_EMAIL))
Synchronization: IMAP can be accessed on echo "$email is not valid";
the Web without an changes take place at else
a central location, the states of emails and echo "$email is valid";$domain get
folders is maintained between sessions, DomainFromEmail($email), 1);
even if the user changes computers. email echo $domain;
client. Because a function getDomainFromEmail($email)
Easy Migration: Migrating from one $domain substr(strrchr($email, "@"), 1);
computer to another does not require return $domain;
downloading t messages again, since they ?>
are manipulated remotely. 6. Which are the internet protocols used
Disadvantages for mail handling? Explain any one
Performance and Maintenance: IMAP can brief.
be complex to maintain, and thus some Solution
hosts not support the protocol. It also
The internet protocols used for mail <sup> tag is used to set the text in
handling are: superscript format. Superscript text
i. SMTP: Simple Mail Transfer Protocol appears half a character above the normal
ii. POP: Post Office Protocol line and is sometimes rendered in a
iii.IMAP: Internet Message Access smaller font.
Protocol Example:
SMTP (Simple Mail Transfer Protocol): (a+b)<sup>2</sup> a<sup>2</sup> 2ab
Simple Mail Transfer Protocol (SMTP) b<sup>2</sup>
Internet standard for email (electronic Output:
mail) transmission across Internet (a+b)²= a²+2ab+b²
Protocol (IP) network SMTP was first State the purpose of pathinfo().
defined by RFC 821 (1982). It uses TCP Solution
port 25.SMTP was updated by The pathinfo() is an inbuilt function which
5341(2008). It uses TCP587. It is known as is used to return information about a
ESMTP and is the protocol in widespread path. It returns an associative array
use t SMTP takes care of sending email to containing the directory name, basename,
another computer. Normally email is sent extension and filename.
to an server (SMTP server), and then to Example:
another server or servers, and finally to its <?php
destination. can only transmit pure text. It print_r(pathinfo("nsgacademy/vision.php"
cannot transmit binary data like pictures, ));
sounds or movies. uses the MIME protocol ?>
to send binary data across TCP/IP Output:
networks. The MIME p converts binary Array ([dirname] =>nsgacademy
data to pure text. [basename] =>vision.php [extension]
7.What is hyperlink? =>php [filename] =>
Solution vision)
HTML links are hyperlinks. It is an element What is DSN?
in HTML document that links to either Solution
another portion of the document or to DSN i.e.. Data Source Name contains the
another document altogether. The HTML information required to connect to the
tag defines a database general, a DSN consists of
hyperlink. hostname, port no, username, dbname
It has the following: and password of databa server.
Syntax: Example:
<a href="url">link text</a> The following example shows a
List the advantages of CSS. PDO_PGSQL DSN for connecting to a
Solution postgresql database pgsql thing example
Advantages of CSS: shewport 5432/dbname-webtechnology;
i.CSS i.e., Cascading Style Sheets used to user-nagacademy;
design web pages. It handles the look and password=vision;
feel part of a web page. List any two features of HTTP protocol.
ii. It saves a lot of work. It can control the Solution
layout of multiple web pages all at once. i.Following are the features of HTTP: HTTP
8.Which tag is used to set the text in defines a set of rules regarding how
superscript format? messages are formatted and exchanget
Solution between server and browser. 1.
ii. HTTP is stateless protocol because each else
command is executed independently. echo "$file is deleted.",
State the use of foreach() function. Write any 2 features of PHP and HTML.
Solution Solution
The foreach construct provides the easiest Features of HTML
way to iterate the array elements. It works i.HTML is hypertext markup language used
on array and objects both. It loops over to create web pages. It is simple and easy
the array, and each value of the array to learn. It is platform independent.
element is assigned to value and the array ii. Images, audios and videos can be added
pointer is advanced by one to go the next to a web page.
element in the array. Features of PHP
Syntax: i.Simple and Interpreted: PHP is very
foreach($array as $value) simple and easy to use as compared to
{ otherscripting language and there is no
// php code to be executed need of compilation as it is an interpreted
} language.
What is Web server? ii.Platform Independent: PHP code can be
Solution executed on every platform like Linux,
A web server is a program that uses HTTP Windows, MacOS.
(Hypertext Transfer Protocol) for Write the output of the following PHP
accepting requests from clients, such as Script.
web browsers, serving them responses <?php
along with optional data contents, which $ age = array("Anna"=>"45","Julie" =>
are usually web pages. Example: Apache, "38", "Benne" => "53");
IIS, ssl, httpd etc. usort($age);
live any two functions of random access print_r($age);
of file data. ?>
solution Solution
fseek(): The fseek() function moves the file Explanation:
pointer from its current position to a new Here asort() sorts given associative array
position, forward or backward, specified in ascending order, according to the value.
by the number of bytes. Write the output of the following php
Syntax: fseek (file, offset[, whence]) script.
rewind(): The rewind() function rewinds <?php
the position of the file pointer to the $a = 'PHP';
beginning of the file. $b = '$a interpolation'
Syntax: rewind(file) echo $b;
How to delete file in PHP? ?>
Solution Solution
unlink() function is used to delete file in $a interpolation
PHP. It returns TRUE on success, or FALSE Explanation:
on failure. Single-quoted strings can't interpolate
Syntax: unlink(filename) variables. The variable name in single-
Example: <?php quoted can't be expanded by its value.
$file = nsg.txt"; Write the output of the following PHP
if (unlink ($file)) script.
echo "Error deleting $file."; $str= 'abc, pqr, Imn, xyz';
p= explode(',', $str, 3); $ ADDRESS<textarea name="address"
print r(Sp); cols="30" rows="10"> </textarea>
Solution <br>
Array ([0]=>abc [1]=>pqr [2]->lmn, xyz) CONTACT<input type="text"
Explanation: name="contact" maxlength="10"><br>
Here explode() partitioned given string by <input type="submit" value="SUBMIT">
separator(,) and returns array. The third <input type="button" value="REFRESH"
arg limit(3), is the maximum number of onclick="window.location.reload()">
values to return in the array. Hence, the </form>
last element array contains the remainder </body> </html>
of the string.
Explain any two of the following
functions with syntax.
What is the output of the following? 1. array_intersect()
<?php II. array_slice()
$p=array(1,2,3,4,5); shuffle()
$q=array(1,3,5,7,9) Solution
$s=array_diff($,$q); i. array_intersect() function returns an
print_r($s); array consisting only of those values
?> present in array_1 that are also present in
Solution each of the other arrays.
Array ([1]=>2 [3]=>4) Syntax:
Explanation: array_intersect (array_1, array_21, array
Here, array_diff() compares both array 3,..., array_4))
and returns the differences i.e. 2 and 4 of Example:
$ present in $q. So, it will return an array <?php
which includes 2 and 4 with their $a array(10,20,30, 40, 50);
respective index $b array(40,50,60,70);
Design HTML form that will accept user $x array_intersect($a, $b);
input as first name, middle name and last echo "Intersecting array: <br>";
name, address, contact number. Provide print_r($x);
buttons to submit the input as well as to ?>
refresh form. Intersecting array: Array ([3] 40 [4]50)
Solution ii. array slice() function returns the subset
<html> of input array starting at the key offi
<head> ending at position calculated to length. If
<title>NSG ACADEMY</title> the length is omitted, then array slice
</head> returns all the elements from the starting
<body> offset.
< form action="input.php"> Syntax:
FIRST NAME<input type="text" array slice(input array, int offset(, int
name="fname"><br> length])
MIDDLE NAME<input type="text" Example:
name="mname"><br> <?php
LAST NAME<input type="text" $a array (10,20,30,40,50,60,70,80); Sx
name="lname"><br> array alice(Sa, 2,5); 6x-> echa "After using
array_slice :<br>"; print r (3x);
?> extra headers (from, cc, bee). It should be
Output: separated with a CRLF(On)
After using array slice: additional_parameters: Optional
Array ( [0] => 30 [1] => 40 [2] => 50 [3] => parameter. It specifies an additional
60 [4] =>70) parameter to the send mail program.
Example:
iii. shuffle() function shuffles the element $to "mukesh.jain@netsecretsgroup.com";
in the input array in any random order. $subject "How's the JOSH";
Syntax: <?php
shuffle (array_name) $message "High !!!!. But Best is not
Example: Enough"; $headers "From:
Sarr array(10,20,30,40,50,60,70); suresh.rp.agrawal@gmail.com"
<?php "\r\n".
echo "Before shuffle :<br>"; "CC:
print r (Sarr); shuffle($arr); suresh.agrawal@netsecret.sgroup.com";
echo "<br>After shuffle :<br>"; if (mail($to, $subject, $message,
Output: $headers))
print r(Sarr); echo "mail sent."; else
?> echo "mail failed.";
Before shuffle: ?>
Array ([0] => 10 [1] 20 [2] 30 [3] 40 [4] =>
50 [5] => 60 [6] => 70) Explain different types of arguments
After shuffle: passing to function with example.
Array ( [0] => 50 [1] => 10 [2] => 60 [3]70 Solution
[4] 40 [5] 20 [6] => 30) There are following 4 types of arguments
Explain how to send email with PHP. passing to function:
Solution i. Variable parameters: Arguments passed
An e-mail can be plain text, HTML, or may by value A parameter is just like a variable
contain file attachments. and is specified after the function name,
mail() is used to send emails from the PHP inside the parentheses. If more than one
script. It returns 1(true) on success parameter is passed, then they are
otherwise 0(false). separated by commas.
Syntax: Example:
mail(string $to, string $subject, string <?php
$message[ stria $additional_headers[, function display($subject)
string $additional parameters ]]); echo "We are learning $subject";
Parameters 1 display("php"); ?>
to: Required parameter. It specifies single Output: We are learning php
or multiple receivers of the mail. This is ii. Default parameters: Arguments passed
email address. by value
subject: Required parameter. It specifies Arguments passed by reference
subject of the email to be sent. message: If arguments passed by reference to a
Required parameter. It defines message function, then any change in formal
to be sent. Each line should be separated paramete reflects the value of actual
with a LF(In). Lines should not exceed 70 parameter. Referenced parameter is
characters. additional_headers: Optional followed &(ampersand). If more than one
parameter. This is typically used to add
parameter is passed, then they are case 'b':
separated by comma case 'B':
Example: case 'c':
function change (&$sub) $b_cnt++;
<?php break;
$sub = "php"; case 'C': $c_cnt++;
$subject = "java"; break;
echo "We are learning $subject<br>"; case 't':
change ($subject); case 'T': $t_cnt++;
echo "We are learning $subject<br>"; ?> break; case 'g':
iv. Retrieving Parameters case 'G': $g_cnt++; break;
A function can have any number of case $space_cnt++;
parameters passed to it without specifying break;
parenthesis. We can retrieve parameters fclose($fp );
using built-in functions like $fp = fopen("abccount.txt", "w");
func_num_args func_get_arg(), fwrite($fp, "Number of occurrences of B:
func_get_args(). $b_cnt\n");
Example: fwrite($fp, "Number of occurrences of C:
<?php $c_cnt\n");
function display() fwrite($fp, "Number of occurrences of T:
{ $t_cnt\n"); fwrite($fp, "Number of
$n-func_num_args(); for($i=0; $i<$n; $i++) occurrences of G: $g_cnt\n");
echo "We are learning fwrite($fp, "Number of occurrences of
".func_get_arg($i)."<br>"; ) space; $space_cnt"); echo "Characters are
} counted and written successfully...";
display("php", "java", "tos", "os"); fclose($fp);
?> ?>
Output:
We are learning php Explain advantages and disadvantages of
We are learning java IMAP4 protocol.
We are learning tes Solution
We are learning os IMAP stands for Internet Message Access
Write a PHP script to read a file abc.txt Protocol. It is an application layer protoc
where file contains character, B,C,T,G and which is used to receive the emails from
space. Count occurrences of each the mail server.
character and write it to the abccount.txt Advantages
file. i. Unlike POP, IMAP allows us to access,
Solution organize, read and sort our email message
<? php without downloading to local machine.
$fp fopen("abc.txt", "r") or die("unable to After viewing the e-mail, if the user wants,
open file"); he can
$b_cnt 0; also download it and keep it on his
$c_cnt = 0; St_cnt = 0; personal computer. We can access emails
$g_cnt = 0; anytime from any place using internet as
$space_cnt = 0; emails are on the server a the time.
while(!feof($fp)) ( $ch fgetc($fp); iii. As the emails, are stored on mail
switch($ch) ( server, it utilizes minimal local storage.
iv.It provides the facility to search all the $port no 5432";
emails and their download contents inside $user = "sagrawal";
the $Pwd ="vision";
mailbox. "pgsql:host-$server:port-
V. It supports technologies like TLS/SSL sport_no;dbname-database:user-$user;
protocols to exchange all information password-$pwd;";
securely. try ( Scon new PDO ($dsn);
Disadvantages $sql = "insert into employee(id,name,
i. Email is only available on the server, so salary) values (7,7,?)";
we may not be able to access it if there is $stmt $con->prepare($sql);
n internet connection. $result $stmt->execute([$id, $name,
ii. In case email usage is more, we would $salary]);
need a larger mailbox storage which might /$result / $stmt->execute(array($id,
cc more. $name, Ssalary));
iii. All emails get synchronized every time if ($result) {
we send or receive it, hence accessing echo "Record inserted successfully";
mails m little slower as compared to }
POP3. else {
iv. If a hacker somehow reaches the echo "Insertion Failed";
server, then all the secret information of } catch (PDOException $e) (
user can leaked. } echo "Connection failed:
Write a PHP script accept and insert $e=>getMessage();
records in employee table. }
Solution
// employee.html What is associative array? Explain with
<html> example how is it different from indexed
<head><title>NSG array? (Ch 3)
Academy</title></head> Solution
<body> Associative array is used to store key
<form action="employee.php"> value pairs whereas indexed array is used
Employee ID<input type="text" to store only values.
name="eid" required><br> Employee In associative array, the key is stored in
Name<input type="text" name="ename" the numeric or string format. Whereas in
required><br> indexed array no need to specify key
Employee Salary<input type="text" because key is like numeric index assigned
name="esalary" required> automatically which always begins with 0.
<input type="submit" value="SUBMIT"> Example: To store details of a book,
</form> indexed array would not be the best
</body> choice. Instead, we could use the book's
/html> heading as the keys in associative array,
// employee.php and respective details as the values.
<?php <?php $booklarray("Name" => "Web
$id = REQUEST['eid']; Technology", "Author" => "Suresh
$name=$REQUEST['ename']; Agrawal", "Publication" => "Vision"); echo
$salary $ =$ REQUEST['esalary'); "<br>Book Details Stored in Associative
server = localhost"; Array<br>";
$database = "nsgacademy"; print_r($book1);
$book2 array("Web Technology",
"SureshAgrawal", "Vision"); echo
"<br><br>Book Details Stored in Indexed
Array<br>";
print_r($book2);
?>
Output:
Book Details Stored in Associative Array
Array([Name] => Web Technology
[Author] => Suresh Agrawal [Publication]
Vi
Book Details Stored in Indexed Array
Array ( [0] => Web Technology [1] =>
Suresh Agrawal [2] => Vision)
Indexed array can be accessed using for
and foreach loop both, but associative ar
only be accessed using foreach loop as
there is no index.
Example:
$book1 = array("Name" => "Web
Technology", "Auth "Suresh Agrawal",
"Publication" -> "Vision"); echo "<br>Book
Details stored in Associative array<br
foreach($bookl as $key => $value) (
<?php
echo "<br>".$key.": ".$value;
$book2 array("Web Technology",
"SureshAgrawal", "Vision echo
"<br><br>Book Details stored in Indexed
array<br>" foreach ($book2 as $value) (
echo "<br>".$value;
?>
Output:
Book Details stored in Associative array
Name: Web Technology
Author: Suresh Agrawal
Publication: Vision
Book Details stored in Indexed array
Web Technology
Suresh Agrawal
Vision
GET POST
The HTTP GET method encodes the form
data in the URL called as query string.
The POST method encodes the
form data in the body of the HTTP
request.
It makes data visible in the browser
address window. The data is not
shown in the URL.
It makes it possible to bookmark the
result of the form. The data cannot be
bookmarked.
GET requests can be cached. POST
requests are never cached.
GET requests have length restriction.
POST requests have no restrictions
on data length.

You might also like