PHP S-22
PHP S-22
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2005 Certified) (ISO/IEC - 27001 - 2005 Certified)
Important Instructions to examiners: PHP is one of the most secure ways of developing websites and
1) The answers should be examined by key words and not as word-to-word as given in the dynamic web applications. PHP has multiple layers of security
model answer scheme. to prevent threats and malicious attacks.
2) The model answer and the answer written by candidate may vary but the examiner may try
b) What is array? How to store data in array? 2M
to assess the understanding level of the candidate.
3) The language errors such as grammatical, spelling errors should not be given more Ans. 1. An array in PHP is an ordered map where a map is a type that
Importance (Not applicable for subject English and Communication Skills. associates values to keys.
4) While assessing figures, examiner may give credit for principal components indicated in the 1M for
figure. The figures drawn by candidate and model answer may vary. The examiner may give 2. Ways to store an array. definition
credit for anyequivalent figure drawn. Using array variable 1M to store
5) Credits may be given step wise for numerical problems. In some cases, the assumed <?php data
constant values may vary and there may be some difference in the candidate’s answers and $array_fruits= array('Apple', 'Orange', 'Watermelon', 'Mango');
model answer. ?>
6) In case of some questions credit may be given by judgement on part of examiner of relevant OR
answer based on candidate’s understanding. Using array indices
7) For programming language papers, credit may be given to any other program based on <?php
equivalent concept.
$array= [];// initializing an array
8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi
and Bilingual (English + Marathi) medium is introduced at first year of AICTE diploma
$array[] = 'Apple';
Programme from academic year 2021-2022. Hence if the students in first year (first and $array[] = 'Orange';
second semesters) write answers in Marathi or bilingual language (English +Marathi), the $array[] = 'Watermelon;
Examiner shall consider the same and assess the answer based on matching of concepts $array[] = „Mango;
with model answer. print_r($array);
?>
Q.No Sub Answer Marking
Q.N. Scheme c) List types of inheritance. 2M
1. Attempt any FIVE of the following: 10 Ans. 1. Single Level Inheritance 2M for any
a) Describe advantages of PHP. 2M 2. Multiple Inheritance four
Ans. Easy to Learn ½ M each, 3. Multiple Inheritance (Interfaces) correct
Familiarity with Syntax any four 4. Hierarchical Inheritance names of
PHP is an open-source web development language, it‟s advantages inheritance
completely free of cost.
PHP is one of the best user-friendly programming languages in d) How can we destroy cookies? 2M
the industry. Ans. We can destroy the cookie just by updating the expire-time value 1M for
PHP supports all of the leading databases, including MySQL, of the cookie by setting it to a past time using the explanatio
ODBC, SQLite and more setcookie() function. n
effective and efficient programming language 1M for
Platform Independent Syntax: setcookie(name, time() - 3600); syntax/
PHP uses its own memory space, so the workload of the server example
and loading time will reduce automatically, which results into e) List any four data types in MYSQL 2M
the faster processing speed.
echo $a1."<br>".$a2."<br>".$a3."<br>".$a4."<br>"; {
?> return(true);
c) Define Introspection and explain it with suitable example. 4M }
Ans. Introspection in PHP offers the useful ability to examine an 1M for //Class "Test" exist or not
object's characteristics, such as its name, parent class (if any) definition if (class_exists('Test'))
properties, classes, interfaces and methods. 1M for {
PHP offers a large number functions that can be used to explanatio $t = new Test();
accomplish the above task. n echo "The class is exist. <br>";
Following are the functions to extract basic information about 2M for any }
classes such as their name, the name of their parent class etc. correct else
example {
echo "Class does not exist. <br>";
}
//Access name of the class
$p= new Test();
echo "Its class name is " ,get_class($p) , "<br>";
//Aceess name of the methods/functions
$method = get_class_methods(new Test());
echo "<b>List of Methods:</b><br>";
foreach ($method as $method_name)
{
echo "$method_name<br>";
}
?>
Output :
The class is exist.
Its class name is Test
Example: List of Methods:
<?php testing_one
class Test testing_two
{ testing_three
function testing_one() d) Write difference between get() and post() method of form (Any 4M
{ four points)
return(true); Ans. HTTP GET HTTP POST 1M for
} In GET method we cannot send In POST method large each
function testing_two() large amount of data rather amount of data can be correct
{ limited data is sent because the sent because the request differentiat
return(true); request parameter is appended parameter is appended ion, any
} into the URL. into the body. four points
function testing_three()
Page 5 / 29 Page 6 / 29
www.diplomachakhazana.in
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2005 Certified) (ISO/IEC - 27001 - 2005 Certified)
Page 7 / 29 Page 8 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2005 Certified) (ISO/IEC - 27001 - 2005 Certified)
// area of circle
case 1: Cookie
return 3.14 * $arguments[0]; Cookie is a small piece of information stored as a file in the user's
browser by the web server. A cookie stores some data temporarily
// IF two arguments then area is rectangle; (until the expiration date has passed).There is no Unique ID
case 2: allocated for a Cookie. The cookie data can be accessed using the
return $arguments[0]*$arguments[1]; $_COOKIE super-global variable. A cookie can be set using the
} setcookie() function.
}
} Use of Session start
} PHP session_start() function is used to start the session. It starts a
new or resumes an existing session. It returns an existing session if
// Declaring a shape type object the session is created already. If a session is not available, it creates
$s = new Shape; and returns a new session.
session_start() creates a session or resumes the current one based
// Function call on a session identifier passed via a GET or POST request, or passed
echo($s->area(2)); via a cookie.
echo "<br>";
Example optional:-
// calling area method for rectangle <?php
echo ($s->area(4, 2)); session_start();
?> ?>
Output: <html>
9.426 <body>
48 <?php
$_SESSION["uname"]="Customer1";
Here the area() method is created dynamically and executed with $_SESSION["fcolor"]="RED";
the help of magic method __call() and its behavior changes echo "The session variable are set with values";
according to the pass of parameters as object. ?>
(Any other example can be considered) </body>
c) Define session and cookie. Explain use of session start. 4M </html>
Ans. Session 1M for d) Explain delete operation of PHP on table data. 4M
Session is a way to store information to be used across multiple each Ans. Delete command is used to delete rows that are no longer required 2M for
pages, and session stores the variables until the browser is closed. definition from the database tables. It deletes the whole row from the table. explanatio
To start a session, the session_start() function is used and to destroy 2M for use n
a session, the session_unset() and the session_destroy() functions of session The DELETE statement is used to delete records from a table: 2M for
are used. start DELETE FROM table_name WHERE some_column = program /
The session variables of a session can be accessed by using the some_value Example
$_SESSION super-global variable.
Page 9 / 29 Page 10 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2005 Certified) (ISO/IEC - 27001 - 2005 Certified)
[WHERE condition] is optional. The WHERE clause specifies Table after Deletion
which record or records that should be deleted. If the WHERE
clause is not used, all records will be deleted.
Below is a simple example to delete records into the student.pridata
table. To delete a record in any table it is required to locate that
record by using a conditional clause. Below example uses name to (Any other example can be considered)
match a record in student.pridata table.
Example:- 4. Attempt any THREE of the following: 12
Assume Following Table a) Write PHP script to sort any five numbers using array 4M
Database Name-student function. 4M for
Table name - pridata Ans. <?php correct and
$a = array(1, 8, 9, 4, 5); equivalent
sort($a); code
foreach($a as $i) {
echo $i.' ';
}
?>
<?php
$server='localhost'; OR
$username='root';
$password=''; <!DOCTYPE html>
$con=mysqli_connect($server,$username,$password); <html>
if(!$con){ <body>
die("Connection to this database failed due to" <H1>Enter five numbers </H1>
.mysqli_connect_error($mysqli)); <form action = 'sort.php' method = 'post'>
} <input type = 'number' name = 'n1' placeholder = 'Number
$sql="DELETE FROM student.pridataWHERE name='amit'"; 1...'><br><br>
if($con->query($sql)==true){ <input type = 'number' name = 'n2' placeholder = 'Number
echo "Record deleted successfully"; 2...'><br><br>
} <input type = 'number' name = 'n3' placeholder = 'Number
else{ 3...'><br><br>
"ERROR:error".$con->error(); <input type = 'number' name = 'n4' placeholder = 'Number
} 4...'><br><br>
$con->close(); <input type = 'number' name = 'n5' placeholder = 'Number
?> 5...'><br><br>
<input type = 'submit' value = 'Submit'>
Output:- </form>
</body>
</html>
Page 11 / 29 Page 12 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2005 Certified) (ISO/IEC - 27001 - 2005 Certified)
sort.php Explanation
<?php The above code creates a car with a constructor which initializes its
if($_SERVER['REQUEST_METHOD'] == 'POST') { member variable named color and price.
$a = array($_POST['n1'], $_POST['n2'], $_POST['n3'], An object of the variable is created, and it is cloned to demonstrate
$_POST['n4'], $_POST['n5']); deep cloning.
sort($a);
c) Create customer form like customer name, address, mobile no, 4M
}
date of birth using different form of input elements & display
foreach($a as $i) {
user inserted values in new PHP form.
echo $i.' ';
Ans. <!DOCTYPE html>
}
<html> 4M for
?>
<body> correct and
(Any other example can be considered)
<form action = 'data..php' method = 'post'> equivalent
b) Write PHP program for cloning of an object 4M <input type = 'text' name = 'name' placeholder = 'Customer code
Ans. (Any other correct program can be considered) 4M for Name...'><br><br>
Code:- correct <input type = 'text' name = 'address' placeholder =
<!DOCTYPE html> program 'Address...'><br><br>
<html>
<input type = 'text' name = 'number' placeholder = 'Mobile
<body>
Number...'><br><br>
<label> Date of Birth: </label>
<?php
<input type = 'date' name = 'dob'><br><br>
class car {
<input type = 'submit' value = 'Submit'><br>
public $color;
</form>
public $price;
</body>
function __construct()
</html>
{
$this->color = 'red';
data.php
$this->price = 200000;
<?php
}
if($_SERVER['REQUEST_METHOD'] == 'POST') {
}
echo '<html><body><form>
$mycar = new car();
Customer Name: '.$_POST['name'].'<br>
$mycar->color = 'blue';
Address: '.$_POST['address'].'<br>
$mycar->price = 500000;
Mobile Number: '.$_POST['number'].'<br>
$newcar = clone $mycar;
Date of Birth: '.$_POST['dob'];
print_r($newcar);
}
?>
?>
</body>
(Any other correct program logic can be considered)
</html>
d) Inserting and retrieving the query result operations 4M
Ans. <?php 2M for
$con = mysqli_connect('localhost', 'root', '', 'class'); inserting
Page 13 / 29 Page 14 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2005 Certified) (ISO/IEC - 27001 - 2005 Certified)
# Connecting to Database 2M for There are two types of validation available in PHP.
$query = "insert into user values(1, 'Amit')"; retrieving Client-Side Validation − Validation is performed on the client
# Inserting Values the query machine web browsers.
$result = mysqli_query($con, $query); result Server Side Validation − After submitted by data, The data is sent
if($result) { operations to a server and performs validation checks in the server machine.
echo 'Insertion Successful <br>';
} Some of Validation rules for field
else { Field Validation Rules
echo 'Insertion Unsuccessful <br>'; Name Should required letters and white-spaces
} Email Should be required @ and .
Website Should required a valid URL
$query = "select * from user"; Radio Must be selectable at least once
# Retrieving Values Check Box Must be checkable at least once
$result = mysqli_query($con, $query); Drop Down menu Must be selectable at least once
foreach($result as $r) { The preg_match() function searches a string for pattern, returning
echo $r['roll_number'].' '.$r['name']; true if the pattern exists, and false otherwise.
}
?> To check whether an email address is well-formed is to use PHP's
Output filter_var() function.
Insertion Successful
1 Amit empty() function will ensure that text field is not blank it is with
Explanation some data, function accepts a variable as an argument and returns
The above code connects with a database named „class‟‟. TRUE when the text field is submitted with empty string, zero,
The exam database has a table named „user‟ with 2 columns NULL or FALSE value.
roll_number and name.
Is_numeric() function will ensure that data entered in a text field is
It executes an insert query on the user and checks whether the
insertion was successful or not. a numeric value, the function accepts a variable as an argument and
It executes a select query on the user and displays the information returns TRUE when the text field is submitted with numeric value.
retrieved.
(Any other example can be considered) Example:-
Validations for: - name, email, phone no, website url
e) How do you validate user inputs in PHP. 4M <!DOCTYPE html>
Ans. Invalid user input can make errors in processing. Therefore, 2M for <body>
validating inputs is a must. explanatio <?php
1. Required field will check whether the field is filled or not in the n $nerror = $merror = $perror = $werror = $cerror = "";
proper way. Most of cases we will use the * symbol for required 2M for $name = $email = $phone = $website = $comment = "";
field. program $pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)* @[a-z0-9-]+(\.[a-z0-9-
2. Validation means check the input submitted by the user. ]+)*(\.[a-z]{2,3})$^";
Page 15 / 29 Page 16 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2005 Certified) (ISO/IEC - 27001 - 2005 Certified)
if($_SERVER["REQUEST_METHOD"]=="POST") { }
if(empty($_POST["name"])) { if (empty($_POST["comment"])) {
$nerror = "Name cannot be empty!"; $cerror = "";
} }
else { else {
$name = test_input($_POST["name"]); $comment = test_input($_POST["comment"]);
if(!preg_match("/^[a-zA-Z-']*$/",$name)) }}
{ function test_input($data)
$nerror = "Only characters and white spaces allowed"; {
} $data = trim($data);
} $data = stripslashes($data);
if(empty($_POST["email"])) { $data = htmlspecialchars($data);
$merror = "Email cannot be empty!"; return $data;
} }
else ?>
{ <p><span class="error">* required field </span></p>
$email = test_input($_POST["email"]); <form method="post" action="<?php echo
if(!preg_match($pattern, $email)) { htmlspecialchars($_SERVER["PHP_SELF"]);?>">
$merror = "Email is not valid"; Name: <input type="text" name="name">
} <span class="error">* <?php echo $nerror;?></span><br/><br/>
} E-mail: <input type="text" name="email">
if(empty($_POST["phone"])) { <span class="error">* <?php echo $merror;?></span><br/><br/>
$perror = "Phone no cannot be empty!"; Phone no: <input type="text" name="phone">
} <span class="error">* <?php echo $perror;?></span><br/><br/>
else { Website: <input type="text" name="website">
$phone = test_input($_POST["phone"]); <span class="error">* <?php echo $werror;?></span><br/><br/>
if (!preg_match ('/^[0-9]{10}+$/', $phone)) { Comment: <textarea name="comment" rows="5"
$perror = "Phn no is not valid"; cols="40"></textarea><br/><br/>
} <input type="submit" name="submit" value="Submit"></form>
} <?php
if(empty($_POST["website"])) { echo "<h2>Your Input:</h2>";
$werror = "This field cannot be empty!"; echo $name; echo "<br>";
} echo $email; echo "<br>";
else { echo $phone; echo "<br>";
$website = test_input($_POST["website"]); echo $website; echo "<br>";
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0- echo $comment;
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { ?>
$werror = "URL is not valid"; </body>
} </html>
Page 17 / 29 Page 18 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2005 Certified) (ISO/IEC - 27001 - 2005 Certified)
Page 19 / 29 Page 20 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2005 Certified) (ISO/IEC - 27001 - 2005 Certified)
Page 21 / 29 Page 22 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2005 Certified) (ISO/IEC - 27001 - 2005 Certified)
0- default. Returns the number of words found. example with each other . It is a case sensitive comparison.
1- returns an array with the words from the string. of each Syntax : $result= strcmp(string1,string2);
2- returns an array where the key is the position of - string1 and string2 indicates strings to be compared with
the word in the string, and value is the actual Any four each other.
word. functions -This function returns 0 if both the strings are equal. It
char : Optional. It specifies special characters to be to be returns a value <0 if string1 is less than string2 and >0 if
considered as words. considered string 1 is greater than string2
Example: Example 1 :
<?php
<?php $str6="Welcome";
$str1="Welcome to WBP Theory & practical"; $str7="Welcome";
echo " <br> Total words in string str1= echo strcmp($str7,$str6);
".str_word_count($str1,0,"&"); ?>
?> 5. strpos() function : This function is used to find the position of
2. strlen() function : This function is used to find number of the first occurrence of specified word inside another string. It
characters in a string . While counting number characters from returns False if word is not present in string. It is a case sensitive
string, function also considers spaces between words. function. by default, search starts with 0th position in a string.
syntax : strlen(string); Syntax : strpos(String,findstring,start);
- string specify name of the string from which characters - string specify string to be searched to find another word
have to be counted. - findstring specify word to be searched in specified first
Example : parameter.
<?php - start is optional . It specifies where to start the search in a
$str3="Hello,welcome to WBP"; string. If start is a negative number then it counts from the
echo "<br> Number of characters in a string '$str3' = " end of the string.
.strlen($str3); Example:
?> <?php
$str8="Welcome to Polytechnic";
$result=strpos($str8,"Poly",0);
3. strrev() function : This function accepts string as an argument echo $result;
and returns a reversed copy of it. ?>
Syntax : $strname=strrev($string variable/String ); 6. str_replace() function : This function is used to replace some
Example : characters with some other characters in a string.
<?php Syntax : str_replace(findword,replace,string,count);
$str4="Polytechnic"; - Find word specify the value to find
$str5=strrev($str4); - replace specify characters to be replaced with search
echo "Orginal string is '$str4' and reverse of it is '$str5'"; characters.
?> - string specify name of the string on which find and replace
has to be performed.
4. strcmp() function : This function is used to compare two strings
Page 25 / 29 Page 26 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous) (Autonomous)
(ISO/IEC - 27001 - 2005 Certified) (ISO/IEC - 27001 - 2005 Certified)
- count is optional . It indicates number of occurrences usability of code in a program. PHP uses extends keyword to n of
replaced from a string. establish relationship between two classes. inheritance
Syntax : class derived_class_name extends base_class_name
Example 1: {
$str10="Welcome to poly"; Class body
$str11=str_replace("poly","msbte",$str10); }
echo $str11; - derived_class_name is the name of new class which is also
known as child class.
7. ucwords() function: This function is used to convert first - base_class_name is the name of existing class which is
character of each word from the string into uppercase. also known as parent class.
Syntax : $variable=ucwords($Stringvar);
Example : A derived class can access properties of base class and also can
<?php have its own properties. Properties defined as public in base class
$str9="welcome to poly for web based development"; can be accessed inside as well as outside of the class but properties
echo ucwords($str9); defined as protected in base class can be accessed only inside its
?> derived class. Private members of class cannot be inherited.
Page 27 / 29 Page 28 / 29
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
Page 29 / 29