Mid 1 Question With Answer (1)
Mid 1 Question With Answer (1)
Echo accepts multiple arguments separated by commas. Print does not accept multiple arguments.
Echo can display outputs of multiple comma-separated Print can only display strings.
strings.
Echo can be used with or without parentheses. Print can also be used with or without
parentheses.
Echo does not return any value. Print always returns an integer value of 1.
Echo performs faster compared to Print. Print performs slower compared to Echo.
In static web pages, Pages will remain same until In dynamic web pages, Content of pages are different
someone changes it manually. for different visitors.
In static web pages, Information are change In dynamic web page, Information are change
rarely. frequently.
In Static Web Pages, database is not used. In dynamic web pages, database is used.
Static web pages are written in languages such Dynamic web pages are written in languages such as:
as: HTML, JavaScript, CSS, etc. CGI, AJAX, ASP, ASP.NET, etc.
Static web pages does not contain any Dynamic web pages contains application program for
application program . different services.
Static web pages require less work and cost in Dynamic web pages require comparatively more
designing them. work and cost in designing them.
Q-5 Write a PHP program to print 1 to 10 numbers using for and while loop statement.
<?php
echo "Numbers from 1 to 10 using for loop:<br>";
for ($i = 1; $i <= 10; $i++)
{
echo $i . " ";
}
echo "<br><br>";
echo "Numbers from 1 to 10 using while loop:<br>";
$i = 1;
while ($i <= 10)
{
echo $i . " ";
$i++;
}
?>
PREPARED BY:-B.P.PATEL
Output:-
== Equal to x == y
!= Not equal to x != y
Logical Operators:
Operator Description Example
and Logical AND (returns True if both operands are True) x and y
or Logical OR (returns True if at least one operand is True) x or y
not Logical NOT (returns the opposite of the operand) not x
Bitwise Operators:
Operator Description Example
& Bitwise AND x&y
` ` Bitwise OR
^ Bitwise XOR x^y
~ Bitwise NOT ~x
<< Left shift x << y
>> Right shift x >> y
Membership Operators:
Operator Description Example
in Checks if a value is present in a sequence x in sequence
not in Checks if a value is not present in a sequence x not in sequence
Identity Operators:
Operator Description Example
is Checks if two objects refer to the same memory location x is y
is not Checks if two objects refer to different memory locations x is not y
PREPARED BY:-B.P.PATEL
Assignment Operators:
Operator Description Example
= Assigns a value to a variable x=y
+= Adds a value to a variable x += y
-= Subtracts a value from a variable x -= y
*= Multiplies a variable by a value x *= y
/= Divides a variable by a value x
/= y
//= Floor divides a variable by a value x //= y
%= Calculates the modulus of a variable and a value x %= y
**= Raises a variable to a power x **= y
<<= Left shifts a variable by a number of bits x <<= y
>>= Right shifts a variable by a number of bits x >>= y
Bitwise operators are used to perform operations on individual bits of integer values. They are often
used in low-level programming and optimization tasks.
Examples:
a = 5 # Binary: 0101
b = 3 # Binary: 0011
# Bitwise AND
result = a & b
print(result)
Output: 1 (Binary: 0001)
# Bitwise OR
result = a | b
print(result)
Output: 7 (Binary: 0111)
# Bitwise XOR
result = a ^ b
print(result)
Output: 6 (Binary: 0110)
# Bitwise NOT
result = ~a
print(result)
Output: -6 (Binary: 1010)
# Left shift
result = a << 2
print(result)
Output: 20 (Binary: 010100)
# Right shift
result = a >> 2
PREPARED BY:-B.P.PATEL
print(result)
Output: 1 (Binary: 0001)
Q-8 Define following terms:
1. Class
• Class is a collection of objects of similar type.
• Object with same properties and operations form a group known as class.
• Class contains data member and data function.
• In a class, variables are called properties (data member) and data functions are called methods.
• Example: Suppose class name is car, then we can create three individual objects with the name
of: Mercedes, Bmw, and Audi.
2. Object
• An object is an instance of a class.
• Object is one type of class variable.
• An object is represented as its properties (attributes) and the operation performed on it.
• We can create multiple objects from a class. Each object has all the properties and methods
defined in the class, but they will have different property values.
• Example: suppose Student is a class which contains two objects s1 and s2 with properties
marks and percentage.
3. Constructor
• constructor is a method defined inside a class is called automatically at the time of creation of
object.
• Purpose of a constructor method is to initialize the object.
• A constructor is a public method which is named as __construct
• Syntax:
function __construct()
{
// initialize the object and its properties by assigning values
}
4.Polymorphism
• Polymorphism means to use the same thing for different purpose.
• It contains the same function name and that function performs different tasks according to the
number of arguments.
5. Encapsulation
• The wrapping up of data and methods into a single unit (called class) is known as
encapsulation.
• Encapsulation is a protection mechanism for the data members and methods present inside the
class.
• In the encapsulation technique, we are restricting the data members from access to outside
world end-user.
• In PHP, encapsulation utilized to make the code more secure and robust.
• Using encapsulation, we are hiding the real implementation of data from the user and also
does not allow anyone to manipulate data members except by calling the desired operation.
6. Overloading
• Overloading means to use the same thing for different purpose.
• It contains the same function name and that function performs different tasks according to the
number of arguments.
7. function overriding:
• The two methods with the same name and same parameter is called overriding.
• Both parent and child classes should have same function name with and number of arguments.
• It is used to replace parent method in child class. The purpose of overriding is to change the
behavior of parent class method.
PREPARED BY:-B.P.PATEL
Q-9 How to create class and object in PHP. Explain with example.
A class is defined by using the class keyword, followed by the name of the class and a pair of curly
braces ({}). All its properties and methods go inside the braces:
Syntax:
<? php
Class class name
{
// codes go here
}
?>
Object:
• Objects of a class are created using the new keyword.
• We can create multiple objects from a class.
• Each object has all the properties and methods defined in the class, but they will have different
property values.
Syntax:
$Objname= new clas name();
<?php
class Add
{
protected $a;
protected $b;
function set_no($a,$b)
{
$this->a = $a; $this->b = $b;
}
function sum()
{
return $this->a + $this->b;
}
}
$no = new Add();
$no->set_no(10,20);
echo $no->sum();
echo "<br> ";
?>
Output:-30
Q-11 Explain the use of final keyword in PHP with proper example
• The final keyword is used only for methods and classes.
• if we declare class method as a Final then that method cannot be override by the child class.
• Same as method if we declare class as a Final then that class cannot be extended any more.
• A final class can contain final as well as non final methods. But there is no use of final methods in
class when class is itself declared as final because inheritance is not possible.
Example (method as final)
<?php
class base
{
final public function display()
{
echo "Base class..";
}
}
class derived extends base
{
public function display()
{
echo "derived class";
}
}
$obj = new derived();
$obj->display();
?>
Output:
Error
Q-12Write a PHP code to demonstrate multilevel inheritance.
<?php
class Grandparent
{
public function familyHistory()
{
PREPARED BY:-B.P.PATEL
echo "This is the grandparent's family history.<br>";
}
}
class Parent1 extends Grandparent
{
public function parentTraits()
{
echo "This is a trait inherited from the parent.<br>";
}
}
class Child extends Parent1
{
public function childTalent()
{
echo "This is the child's unique talent.<br>";
}
}
$childObject = new Child();
$childObject->familyHistory();
$childObject->parentTraits();
$childObject->childTalent();
?>
Output:-
PREPARED BY:-B.P.PATEL
{
$this->name = $name;
$this->age = $age;
}
function demo()
{
echo "Base class function:demo<br>";
}
}
class Derived extends Base
{
function demo()
{
echo "Derived class function:demo<br>";
}
}
$ob = new Base;
$ob->demo();
$ob->display();
$ob1 = new Derived;
PREPARED BY:-B.P.PATEL
$ob1->demo();
$ob1->display();
?>
Output:-
The GET method, appends name/value pairs to POST method packages the name/value pair inside
theURL body of HTTP request, which makes fora clean URL
The length of URL is limited, so it works if POST method imposes no size limitations onforms
thereare few parameters. output.
It is insecure because parameters passed on the It is secure because submitted data are passed
URL are visible in address field of browser. through HTTP handler.
It can’t be used to send binary data, like images Using POST method can be used to send
orword documents, to server. ASCII as well as binary data.
The data send by POST method can be
accessed using $_POST superglobal variable
1. method Attribute
• Purpose: Specifies the HTTP method (like GET or POST) used to send form data to the server.
• Common Values:
o GET:
▪ Data is appended to the URL as query parameters (visible in the browser address bar).
▪ Limited data size due to URL length restrictions.
▪ Generally not suitable for sensitive data.
o POST:
▪ Data is sent in the message body of the HTTP request, not visible in the URL.
▪ Can handle larger amounts of data and is more secure for sensitive information.
2. action Attribute
• Purpose: Defines the URL of the script or page on the server that will process the form data.
• Example:
o If action="process.php", the form data will be sent to the process.php file on the server.
PREPARED BY:-B.P.PATEL
<form action="process.php" method="POST">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit">Submit</button>
</form>
Q-17 Explain session? Explain how to create access and destroy a session with suitable example.
What is a Session?
In web development, a session is a temporary storage mechanism that servers use to maintain information
about a specific user's interaction with a website during a single visit.
Think of it as a temporary container that holds data related to that particular user's session. This data can
include things like:
• User login status: Whether they are logged in or not.
• User preferences: Language, theme, etc.
• Items added to a shopping cart.
• Tracking user activity within the website.
How Sessions Work in PHP
1. Session Start:
o session_start(); This function initializes the session and makes session variables
accessible.
2. Data Storage:
o $_SESSION is a superglobal array in PHP that allows you to store session data.
▪ Example: $_SESSION['username'] = "john_doe";
3. Data Retrieval:
o Access session data using the $_SESSION array:
▪ Example: echo "Welcome, " . $_SESSION['username'];
4. Session Destruction:
o session_destroy(); This function deletes all session data associated with the current user.
Example (PHP)
<?php
session_start();
if(isset($_SESSION['username']))
{
echo "Welcome, " . $_SESSION['username'] . "!";
} else {
header("Location: login.php");
exit();
}
$_SESSION['user_id'] = 123;
$userId = $_SESSION['user_id'];
echo "User ID: " . $userId;
session_destroy();
?>
Q-18 Define following form element
i) Upload
• Upon form submission, the selected files are transmitted to the server along with other form data.
ii) Dropdown
• This is like combobox control of Visual basic. Dropdown list is used to select one option from given
list of choice.
iii) Checkbox.
• It allows you to represent list of options to the users from which user can select none, one or more
than one options at a time.
• Thus it useful when you want to represent various choices to user from which he/she can select
choices as per his/her requirement.
• It displays as small square on web page
PREPARED BY:-B.P.PATEL
Syntax : <input type=”checkbox” name=”Name” value=”Value” [checked]> Text </input>
Text TYPE: Indicates type of input element. So it is checkbox.
NAME: Variable name passed to application.
VALUE: Data associated with variable name
iv) Radio box
• It allows you to represent list of options to the users from which user can select only one options at a
time.
• Thus it useful when you want to represent various choices to user from which he/she can select only
one choice as per his/her requirement.
• It displays as small circle on web page
v) Date
• It defines a date picker. The resulting value includes the year, month, and day
• Syntax: <input type="date">
vi) Color
• It defines a color picker. The default value is #000000 (black).
• Syntax: <input type="color">
Q-19 Write a PHP script to store, retrieve and destroy SESSION data of user.
Session.php
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["User"]="Bhavika";
echo"Session information are set successfully.<br/>";
?>
<a href="session2.php">Vist next page</a>
</body>
</html>
Output:-
Session2.php
<?php
session_start();
?>
<html>
<body>
<?php
echo "User is : ".$_SESSION["User"];
?>
</body>
</html>
Output:-
PREPARED BY:-B.P.PATEL
Coun.php
<?php
session_start();
if(!isset($_session['counter']))
{
$_session['counter']=1;
}
else
{
$_session["counter"]++;
}
echo"Page views : ".$_session["counter"]."<br>"
?>
<a href="des.php">View next page</a>
Output:-
Des.php
<?php
session_start();
session_destroy();
?>
Output:
PREPARED BY:-B.P.PATEL
Q-20 Differentiate COOKIE and SESSION.
Cookies Session
Cookies are client-side files on a local Sessions are server-side files that contain user
computer that hold user information. data.
Cookies end on the lifetime set by the When the user quits the browser or logs out of
user. the programmed, the session is over.
Cookies stored data in text file. Session save data in encrypted form.
In PHP, to get the data from Cookies , In PHP , to get the data from Session,
$_COOKIES the global variable is used $_SESSION the global variable is used
Q-21 Write a PHP code to demonstrate storing and retrieving information from cookies.
<?php
$cookie_name = "user";
$cookie_value = "Engineering";
setcookie($cookie_name, $cookie_value);
?>
<html>
<body>
<?php
if(isset($_COOKIE[$cookie_name]))
{
echo "Cookie named : ".$cookie_name." is set successfully."."<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
else
PREPARED BY:-B.P.PATEL
{
echo "Cookie is not set succcessfully.";;
}
?>
</body>
</html>
Output:-
Q-22 List form controls available in PHP. Explain anyone with proper example.
• Text Box, Textarea, List Box, Dropdown, Check Box, Radio Box, Buttons, Upload, color, date etc.
Introduction to Forms:
• Whenever you are going to design a page, which can accept information from users through various
input fields.
• A form can contain input elements like
1. Textfield
2. Textarea
3. Checkboxes
4. Radio-buttons
5. Drop-down list
6. Submit buttons etc..
• Forms are used to pass data to a server.
• The FORM element has no formatting attributes. Input Elements: Input elements are used to get
input from user in various format.
• 1. Using Textbox: User can enter text or single line using textbox
Syntax:<input type="text" name="Textname" value=”defaultvalue”>
Example:
<form>
Enter your Name:<input type="text" name="txtName">
</form>
Q-23 Write a PHP program that displays an HTML form with following input fields:
1. Name
2. Email
3. Password
4. Gender
5. Hobbies
6. Country
7. Languages and
8. Submit. Then, use $_POST superglobal to retrieve the values of input fields and print them.
PREPARED BY:-B.P.PATEL
<!DOCTYPE html>
<html>
<head>
<title>User Information Form</title>
</head>
<body>
<h2>User Information</h2>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve form data
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$gender = $_POST["gender"];
$hobbies = isset($_POST["hobbies"]) ? implode(", ", $_POST["hobbies"]) : "None";
$country = $_POST["country"];
$languages = isset($_POST["languages"]) ? implode(", ", $_POST["languages"]) : "None";
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<label for="gender">Gender:</label>
<input type="radio" id="male" name="gender" value="Male"> Male
<input type="radio" id="female" name="gender" value="Female"> Female
<input type="radio" id="other" name="gender" value="Other"> Other<br><br>
<label for="hobbies">Hobbies:</label><br>
<input type="checkbox" name="hobbies[]" value="Reading"> Reading<br>
<input type="checkbox" name="hobbies[]" value="Music"> Music<br>
<input type="checkbox" name="hobbies[]" value="Sports"> Sports<br>
<input type="checkbox" name="hobbies[]" value="Travel"> Travel<br><br>
PREPARED BY:-B.P.PATEL
<label for="country">Country:</label>
<select id="country" name="country">
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="UK">UK</option>
<option value="India">India</option>
</select><br><br>
<label for="languages">Languages:</label><br>
<input type="checkbox" name="languages[]" value="English"> English<br>
<input type="checkbox" name="languages[]" value="Spanish"> Spanish<br>
<input type="checkbox" name="languages[]" value="French"> French<br>
<input type="checkbox" name="languages[]" value="German"> German<br><br>
</body>
</html>
PREPARED BY:-B.P.PATEL