PHP Programming-1
PHP Programming-1
2024-2025
INTERNAL & EXTERNAL MARKS PATTERN
Theory –Marks Distribution
PART – B (2 x 5 = 10 Marks)
(Answer ANY TWO questions)
&
(Open Choice – 2 out of 5 questions)
UNIT- V
Managing Sessions and Using Session Variables -Destroying a
Session -Storing Data in Cookies -Setting Cookies.
UNIT -I
What is PHP?
PHP is an acronym for (PHP: Hypertext Preprocessor) is a widely-used open source
general-purpose scripting language that is especially suited for web development and can be
embedded into HTML.
• PHP scripts are executed on the server.
What is a PHP File?
• PHP files can contain text, HTML, CSS, JavaScript, and PHP code.
• PHP code are executed on the server, and the result is returned to the browser as plain
HTML.
• PHP files have extension ".php".
What Can PHP Do?
• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data
With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies. You can also
output any text, such as XHTML and XML.
Why PHP?
• PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.).
• PHP is compatible with almost all servers used today (Apache, IIS, etc.).
• PHP supports a wide range of databases.
• PHP is free. Download it from the official PHP resource: www.php.net
• PHP is easy to learn and runs efficiently on the server side.
• PHP is widely-used.
How Does PHP Work?
As Previously mentioned that PHP is a server-side programming language which means it runs
in the server. PHP plays an intermediate role between a client and the date stored in the server
and other servers.
What Do You Need to Start Using PHP?
• Install a web server
• Install PHP
• Install a database, such as MySQL
You can install a server on your personal computer such as XAMPP server from the link below:
https://www.apachefriends.org/index.html
A PHP version and MySQL come out of the box when you install XAMPP server. You can use
other development server instead of XAMPP such as WAMPSERVER that you can download
from here (http://www.wampserver.com/en/).
PHP Syntax:
A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
➢ Comments in PHP
A comment in PHP code is a line that is not read/executed as part of the program. Its only
purpose is to be read by someone who is looking at the code.
Ex:
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are NOT case-sensitive.
In the example below, all three echo statements below are legal (and equal):
Ex:
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
?>
PHP Variables:
• Start with a $
• Contain only letters, numbers, and the underscore
• The first character after the $ cannot be a number
• Are case-sensitive
• Use a consistent naming scheme!
Ex:
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
➢ PHP Variables Scope
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
• local
• global
• static
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed
outside a function:
Ex:
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
A variable declared within a function has a LOCAL SCOPE and can only be accessed within
that function:
Ex:
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
• PHP The global Keyword
The global keyword is used to access a global variable from within a function. To
do this, use the global keyword before the variables (inside the function):
Ex:
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
Then, each time the function is called, that variable will still have the information it
contained from the last time the function was called.
Note: The variable is still local to the function.
PHP Data Types
Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource
➢ PHP String
A string can be any text inside quotes. You can use single or double quotes:
Ex:
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
You can use either quotation mark type to create the string.
To use a variable within another string, you must use double quotation marks.
Ex:
$first_name = 'Tobias';
In the following example $x is an integer. The PHP var_dump() function returns the data
type and value:
Ex:
<?php
$x = 5985;
var_dump($x);
?>
➢ PHP Float
float (floating point number) is a number with a decimal point or a number in exponential
form.
In the following example $x is a float. The PHP var_dump() function returns the data type
and value:
Ex:
<?php
$x = 10.365;
var_dump($x);
?>
➢ PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
Ex:
$x = true;
$y = false;
➢ PHP Array
In the following example $cars is an array. The PHP var_dump() function returns the data
type and value:
Ex:
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
➢ PHP Object
An object is a data type which stores data and information on how to process that data.
In PHP, an object must be explicitly declared.
First we must declare a class of object. For this, we use the class keyword. A class is a
structure that can contain properties and methods:
Ex:
<?php
class Car {
function Car() {
$this->model = "VW";
}
}
$herbie = new Car(); // create an object
echo $herbie->model; // show object properties
?>
?>
➢ PHP Resource
• The special resource type is not an actual data type. It is the storing of a reference to
functions and resources external to PHP.
• A common example of using the resource data type is a database call.
• We will not talk about the resource type here, since it is an advanced topic
A website is a collection of many web pages, and web pages are digital files that are written using
HTML(HyperText Markup Language). To make your website available to every person in the
world, it must be stored or hosted on a computer connected to the Internet round a clock. Such
computers are known as a Web Server.
The website’s web pages are linked with hyperlinks and hypertext and share a common interface
and design. The website might also contain some additional documents and files such as images,
videos, or other digital assets.
With the Internet invading every sphere, we see websites for all kinds of causes and purposes. So,
we can also say that a website can also be thought of as a digital environment capable of
delivering information and solutions and promoting interaction between people, places, and things
to support the goals of the organization it was created for.
Components of a Website: We know that a website is a collection of a webpages hosted on a
web-server. These are the components for making a website.
Webhost: Hosting is the location where the website is physically located. Group of webpages
(linked webpages) licensed to be called a website only when the webpage is hosted on the
webserver. The webserver is a set of files transmitted to user computers when they specify the
website’s address..
Address: Address of a website also known as the URL of a website. When a user wants to open a
website then they need to put the address or URL of the website into the web browser, and the
asked website is delivered by the webserver.
Homepage : Home page is a very common and important part of a webpage. It is the first
webpage that appears when a visitor visits the website. The home page of a website is very
important as it sets the look and feel of the website and directs viewers to the rest of the pages on
the website.
Design : It is the final and overall look and feel of the website that has a result of proper use and
integration elements like navigation menus, graphics, layout, navigation menus etc.
Content : Every web pages contained on the website together make up the content of the website.
Good content on the webpages makes the website more effective and attractive.
The Navigation Structure: The navigation structure of a website is the order of the pages, the
collection of what links to what. Usually, it is held together by at least one navigation menu.
How to access Websites?
When we type a certain URL in a browser search bar, the browser requests the page from the Web
server and the Web server returns the required web page and its content to the browser. Now, it
differs from how the server returns the information required in the case of static and dynamic
websites.
Types of Website:
Static Website
Dynamic Website
Static Website: In Static Websites, Web pages are returned by the server which are prebuilt
source code files built using simple languages such as HTML, CSS, or JavaScript. There is no
processing of content on the server (according to the user) in Static Websites. Web pages are
returned by the server with no change therefore, static Websites are fast. There is no interaction
with databases. Also, they are less costly as the host does not need to support server-side
processing with different languages.
Dynamic Website: In Dynamic Websites, Web pages are returned by the server which is
processed during runtime means they are not prebuilt web pages, but they are built during runtime
according to the user’s demand with the help of server-side scripting languages such as PHP,
Node.js, ASP.NET and many more supported by the server. So, they are slower than static
websites but updates and interaction with databases are possible. Dynamic Websites are used over
Static Websites as updates can be done very easily as compared to static websites (Where altering
in every page is required) but in Dynamic Websites, it is possible to do a common change once,
and it will reflect in all the web pages.
There are different types of websites on the whole internet, we had chosen some most common
categories to give you a brief idea –
Blogs: These types of websites are managed by an individual or a small group of persons, they
can cover any topics — they can give you fashion tips, music tips, travel tips, fitness tips.
Nowadays professional blogging has become an external popular way of earning money online.
E-commerce: These websites are well known as online shops. These websites allow us to make
purchasing products and online payments for products and services. Stores can be handled as
standalone websites.
Portfolio: These types of websites acts as an extension of a freelancer resume. It provides a
convenient way for potential clients to view your work while also allowing you to expand on your
skills or services.
Brochure: These types of websites are mainly used by small businesses, these types of websites
act as a digital business card, and used to display contact information, and to advertise services,
with just a few pages.
News and Magazines: These websites needs less explanation, the main purpose of these types of
websites is to keep their readers up-to-date from current affairs whereas magazines focus on the
entertainment.
Social Media: We all know about some famous social media websites like Facebook, Twitter,
Reddit, and many more. These websites are usually created to let people share their thoughts,
images, videos, and other useful components.
Educational: Educational websites are quite simple to understand as their name itself explains it.
These websites are designed to display information via audio or videos or images.
Portal: These types of websites are used for internal purposes within the school, institute, or any
business, These websites often contain a login process allowing students to access their credential
information or allows employees to access their emails and alerts.
Dynamic Websites
Dynamic Website is a website containing data that can be mutable or changeable. It uses client-
side or server scripting to generate mutable content. Like a static website, it also contains HTML
data.
Dynamic websites are those websites that changes the content or layout with every request to the
webserver. These websites have the capability of producing different content for different visitors
from the same source code file. There are two kinds of dynamic web pages i.e. client side
scripting and server side scripting. The client-side web pages changes according to your activity
on the web page. On the server-side, web pages are changed whenever a web page is loaded.
Example: login & signup pages, application & submission forms, inquiry and shopping cart
pages.
A Typical Architecture of dynamic website
There are different languages used to create dynamic web pages like PHP, ASP, .NET and JSP.
Whenever a dynamic page loads in browser, it requests the database to give information
depending upon user’s input. On receiving information from the database, the resulting web page
is applied to the user after applying the styling codes.
Features of dynamic webpage:
• These websites are very flexible.
• In these websites the content can be quickly changed on the user’s computer without new
page request to the web browser.
• In these websites the owner have the ability to simply update and add new content to the
site.
• These websites are featured with content management system, e-commerce system and
intranet or extranet facilities.
• Most of the dynamic web content, is assembled on the web using server-scripting
languages.
Advantages of dynamic webpage:
• It provides more functional websites.
• It is very easy to update.
• It helps in the search engines because new content brings people back to the site.
• These are interactive websites because these can be customized.
• These websites can work as a system to allow staff or users to collaborate.
• It’s easy to modify or update data.
• It provides a user-friendly interactive interface for users.
• proves smooth navigation.
• provide interactive user interface
• It provides a better user experience.
• It provides real-time data.
Disadvantages of dynamic webpages:
• These types of websites are complex.
• These are more expensive to develop.
• Hosting of these websites is also costlier.
• It requires a rapid, high-end web server.
• high production costs.
• Slow to load content.
• Client will require a skilled programmer to build a dynamic website.
• Hosting a website is costly as compared to a dynamic website.
• Low speed compared to a static website
Application Of Dynamic Website:
Here is a list of application where we use dynamic website over static website
• Online booking system:
• E-commerce website.
• Voting or polls,
• Forums
• E-newsletter.
Real-life application:
Here is a list of application where we use dynamic website in real world.
• Facebook
• Twitter
• LinkedIn
• Online booking website.
• Social media
Scope of PHP:
PHP (Hypertext Preprocessor) is a popular server-side scripting language that is primarily used
for web development. Its scope includes:
1. Web Development: PHP is widely used for building dynamic websites and web
applications. It works well with databases (especially MySQL) to generate dynamic
content.
2. Content Management Systems (CMS): Many popular CMS platforms like WordPress,
Joomla, and Drupal are built using PHP, which has contributed to its widespread use.
3. E-commerce: PHP powers many e-commerce platforms like Magento, OpenCart, and
WooCommerce (WordPress plugin).
4. Server-Side Scripting: PHP runs on a web server, making it useful for tasks like handling
form data, user authentication, and session management.
5. Database Integration: PHP integrates easily with databases like MySQL, PostgreSQL,
and SQLite, making it a go-to language for building data-driven web applications.
6. APIs and Web Services: PHP can be used to build RESTful APIs and web services,
allowing communication between different systems over HTTP.
7. Automation and Scripting: PHP can also be used for writing scripts to automate tasks like
data processing, backups, and email handling.
XAMPP and WAMP Installation
Both XAMPP and WAMP are software packages that provide a local development
environment for PHP and MySQL. They include everything you need to run a PHP-based web
application on your computer.
1. Installing XAMPP:
XAMPP is a free, open-source platform that includes Apache, MySQL, PHP, and Perl. Here’s
how to install it:
1. Download XAMPP: Go to the official XAMPP website and download the version of
XAMPP suitable for your operating system (Windows, macOS, or Linux).
2. Run the Installer: After downloading the installer, run it to begin the installation process.
3. Choose Components: You can choose which components you want to install (Apache,
MySQL, PHP, etc.). The default settings work fine for most users.
4. Choose Installation Directory: Select where you want to install XAMPP. The default
directory is usually C:\xampp on Windows.
5. Start XAMPP: After installation is complete, launch the XAMPP Control Panel. Start the
Apache and MySQL services by clicking the "Start" buttons next to each.
6. Test the Installation: Open your browser and go to http://localhost. If the XAMPP
welcome page appears, the installation was successful.
2. Installing WAMP:
WAMP is another local server environment for Windows that includes Apache, MySQL, and
PHP. Here's how to install it:
1. Download WAMP: Visit the official WAMP server website and download the latest
version.
2. Run the Installer: Once the installer is downloaded, run it and follow the on-screen
instructions.
3. Select Installation Directory: Choose the folder where you want WAMP to be installed
(default is C:\wamp).
4. Choose Components: WAMP comes with Apache, MySQL, PHP, and a few other tools.
The default components are usually fine.
5. Configure the Default Browser: During installation, you may be prompted to choose your
default browser (you can leave this as it is if you use the default browser).
6. Start WAMP: Once installed, launch the WAMP Manager. The WAMP icon in the
system tray will turn green when everything is running correctly.
7. Test the Installation: Open your browser and go to http://localhost. If the WAMP server
page shows up, the installation was successful.
Key Differences Between XAMPP and WAMP:
1. Operating System:
o XAMPP is cross-platform, available for Windows, Linux, and macOS.
o WAMP is designed specifically for Windows.
2. Components:
o XAMPP includes additional components like Perl and Mercury Mail Server.
o WAMP focuses mainly on Apache, MySQL, and PHP.
3. Interface:
o XAMPP uses a control panel for managing services.
o WAMP uses a system tray icon for managing the server.
4. Popularity:
o XAMPP is more widely used across different platforms, especially for PHP
developers working on cross-platform projects.
o WAMP is primarily used by developers working on Windows environments
MCQ
1. What does PHP stand for?
• A) Personal Home Page
• B) Predefined Hypertext Processor
• C) Personal Hypertext Processor
• D) Hypertext Preprocessor
Answer: D) Hypertext Preprocessor
2. PHP is mainly used for:
• A) Desktop applications
• B) Web development
• C) Mobile app development
• D) Game development
Answer: B) Web development
3. Which of the following is a correct PHP syntax for outputting "Hello World"?
• A) echo "Hello World";
• B) print("Hello World");
• C) output("Hello World");
• D) Both A and B
Answer: D) Both A and B
4. Which PHP function is used to get the length of a string?
• A) strlen()
• B) strlength()
• C) stringlen()
• D) length()
Answer: A) strlen()
5. Which of the following is NOT a valid PHP variable name?
• A) $var_name
• B) $VarName
• C) $_varName
• D) var_name$
Answer: D) var_name$
6. What does HTML stand for?
• A) Hyper Text Markup Language
• B) Hyper Tool Marking Language
• C) Hypertext Transfer Language
• D) Home Tool Marking Language
Answer: A) Hyper Text Markup Language
7. Which of the following is used to create a website?
• A) HTML
• B) CSS
• C) JavaScript
• D) All of the above
Answer: D) All of the above
50. Which software package provides a local development environment for PHP?
• A) WAMP
• B) XAMPP
• C) Both A and B
• D) Neither A nor B
Answer: C) Both A and B
5 MARKS
1. Explain the role of PHP in web development and its basic syntax with an example.
2. Describe the difference between static and dynamic websites with examples.
3. What is PHP, and how does it integrate with HTML to create dynamic web pages?
4. Explain the key advantages of using PHP for web development over other server-side
languages.
5. What are the common features and functions of a dynamic website?
6. Discuss the scope of PHP in modern web development and its integration with databases.
7. What are the key differences between XAMPP and WAMP for local PHP development?
8. Describe the process of installing XAMPP and configuring it to run PHP scripts locally.
9. How does PHP handle form data submitted from a web page? Provide an example.
10.Explain the concept of PHP sessions and their use in maintaining user state across pages.
11.What is the role of MySQL in conjunction with PHP, and how can you connect to a
MySQL database using PHP?
12.How does the echo statement in PHP work, and what are its common uses in web
development?
13.Describe the steps to install and configure WAMP for local web development and running
PHP.
10 MARKS
1. Explain the basic features and benefits of PHP in web development, with examples of
common PHP functions.
2. Describe the differences between static and dynamic websites, and explain how PHP is
used to create dynamic websites.
3. What is the role of PHP in building dynamic websites, and how does it interact with
HTML, CSS, and JavaScript?
4. Discuss the scope of PHP in modern web development, including its usage in content
management systems, e-commerce, and web applications.
5. Explain the installation process of XAMPP and WAMP, and compare their features and
suitability for different web development needs.
6. Describe how to establish a connection between PHP and a MySQL database, and
demonstrate basic operations like INSERT, UPDATE, and SELECT.
7. What are PHP sessions and cookies, and how are they used for maintaining user state and
preferences across multiple web pages?
8. Explain the concept of error handling in PHP using try, catch, and finally, and provide
examples of catching different types of exceptions.
9. Discuss the process of debugging PHP scripts, including common errors and how tools like
XAMPP and WAMP can assist in the development process.
UNIT- II
PHP Syntax
?>
Output
Hello, world!
Embedding PHP in HTML
PHP code can be embedded within HTML using the standard PHP tags.
In this example, the <?php echo “Hello, PHP!”; ?> statement
dynamically inserts a heading into the HTML document.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP Syntax Example</title>
</head>
<body>
<h1><?php echo "Hello, PHP!"; ?></h1>
</body>
</html>
SGML or Short HTML Tags
These are the shortest option to initialize a PHP code. The script starts
with <? and ends with ?>. This will only work by setting
the short_open_tag setting in the php.ini file to ‘on’.
Example:
PHP
<?
?>
Output
Hello, world!
Case Sensitivity
PHP is partially case-sensitive-
• Keywords (like if, else, while, echo) are not case-sensitive.
• Variable names are case-sensitive.
Example:
PHP
<?php
?>
Comments in PHP
Comments are used to make code more readable by explaining the
purpose of specific code blocks. Comments are ignored by the PHP
interpreter.
1. Single Line Comment
As the name suggests, these are single line or short relevant explanations
that one can add to their code. To add this, we need to begin the line
with (//) or (#).
PHP
<?php
?>
Output
Hello World!
Output:
hello world!!!
2. Multi-Line or Multiple Line Comment
It is used to accommodate multiple lines with a single tag and can be
extended to many lines as required by the user. To add this, we need to
begin and end the line with (/*…*/)
PHP
<?php
?>
Output
Hello World!
Variables and Data Types
Variables are used to store data that can be manipulated within PHP.
They are declared using the $ symbol followed by the variable name.
Declaring Variables
Variables are created by assigning a value to them using the assignment
operator (=).
PHP
$name = "XYZ"; // String
$age = 30; // Integer
$isEmployed = true; // Boolean
Data Types
PHP supports several data types, including:
• String: A sequence of characters.
• Integer: Whole numbers.
• Float (Double): Numbers with a decimal point.
• Boolean: Represents true or false.
• Array: A collection of values.
• Object: An instance of a class.
• NULL: A special type representing a variable with no value.
• Resource: A special type that holds a reference to external resources
(like database connections).
Blocks in PHP
In PHP, multiple statements can be executed simultaneously (under a
single condition or loop) by using curly-braces ({}). This forms a block
of statements that gets executed simultaneously.
PHP
<?php
$var = 50;
if ($var>0){
echo ("Positive as \n");
echo ("greater than 0");
}
?>
Output
Positive as
greater than 0
How to embed PHP code in an HTML page ?
PHP is the abbreviation of Hypertext Preprocessor and earlier it was
abbreviated as Personal Home Page.
We can use PHP in HTML code by simply adding a PHP tag without
doing any extra work.
Example 1: First open the file in any editor and then write HTML code
according to requirement. If we have to add PHP code then we can add
by simply adding <?php ….. ?> tags in between and add your PHP code
accordingly.
• PHP
<!DOCTYPE html>
<html>
<head>
<title>PHP</title>
</head>
<body>
<h1>
<?php
echo "hii GeeksforGeeks "
?>
</h1>
</body>
</html>
Output:
<body>
<h2>Welcome to GeeksforGeeks</h2>
<?php
echo "Good morning";
?>
<?php
$str = "This is GeeksforGeeks portal";
echo " $str.";
?>
</body>
</html>
Output:
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$str = $_POST['fname'];
if (empty($str))
{
echo "String is empty";
}
else
{
?>
<h1>
<?php echo $str ?>
</h1>
<?php
}
}
?>
</body>
</html>
Output:
PHP Variables
?>
Data Types in PHP
• Integers: Integers are whole numbers without decimals, which can be
positive or negative.
• Doubles: Floats are numbers with decimal points or in exponential form.
• NULL: The NULL data type represents a variable with no value.
• Strings: Strings are sequences of characters, enclosed in single (‘ ‘) or
double (” “) quotes.
• Booleans: Booleans represent two possible values: true or false.
• Arrays: Arrays are used to store multiple values in a single variable.
Arrays can be indexed, associative, or multidimensional.
• Objects: Objects are instances of classes, which are templates for
creating data structures with properties and methods.
• Resources: Resources are special variables that hold references to
external resources, such as database connections or file handles.
PHP Variable Scope
The scope of a variable refers to where it can be accessed within the
code. PHP variables can have local, global, static, or superglobal scope.
1. Local Scope or Local Variable
Variables declared within a function have local scope and cannot be
accessed outside the function. Any declaration of a variable outside the
function with the same name (as within the function) is a completely
different variable.
Example: This example shows the local variable in PHP.
PHP
<?php
$num = 60;
function local_var() {
local_var();
?>
Output
Variable num inside function is: 50
Variable num outside function is: 60
2. Global Scope or Global Variable
The variables declared outside a function are called global variables.
These variables can be accessed directly outside a function. To get
access within a function we need to use the “global” keyword before the
variable to refer to the global variable.
Example: This example shows the Global Variables in PHP.
PHP
<?php
$num = 20;
global_var();
?>
Output
Variable num inside function: 20
Variable num outside function: 20
3. Static Variables
It is the characteristic of PHP to delete the variable. Once it completes its
execution and the memory is freed. But sometimes we need to store the
variables even after the completion of function execution. To do this, we
use the static keywords and the variables are then called static
variables. PHP associates a data type depending on the value for the
variable.
Example: This example shows the Static variable in PHP.
PHP
<?php
// Static Variable
static $num = 5;
$sum = 2;
$sum++;
$num++;
?>
Output
6
3
7
3
Note: You must have noticed that $num regularly increments even after
the first function call but $sum doesn’t. This is because $sum is not
static, and its memory is freed after the execution of the first function
call.
4. Superglobals
Superglobals are built-in arrays in PHP that are accessible from
anywhere in the script, including within functions. Common
superglobals include $_GET, $_POST, $_SESSION, $_COOKIE,
$_SERVER, and $_GLOBALS.
PHP
<?php
Output
World
?>
Output
704
int(704)
2. Float (Double)
Can hold numbers containing fractional or decimal parts including
positive and negative numbers or a number in exponential form. By
default, the variables add a minimum number of decimal places. The
Double data type is the same as a float as floating-point numbers or real
numbers.
PHP
<?php
$val1 = 50.85;
$val2 = 654.26;
echo $sum;
echo "\n\n";
?>
Output
705.11
float(705.11)
3. String
Hold letters or any alphabets, even numbers are included. These are
written within double quotes during declaration. The strings can also be
written within single quotes, but they will be treated differently while
printing variables. To clarify this look at the example below.
PHP
<?php
$name = "Krishna";
echo "The name of the Geek is $name \n";
echo 'The name of the geek is $name ';
echo "\n\n";
?>
Output
The name of the Geek is Krishna
The name of the geek is $name
string(7) "Krishna"
4. Boolean
Boolean data types are used in conditional testing. Hold only two values,
either TRUE(1) or FALSE(0). Successful events will return true and
unsuccessful events return false. NULL type values are also treated
as false in Boolean. Apart from NULL, 0 is also considered false in
boolean. If a string is empty then it is also considered false in boolean
data type.
PHP
<?php
if(TRUE)
echo "This condition is TRUE";
if(FALSE)
echo "This condition is not TRUE";
?>
Output
This condition is TRUE
User-Defined (compound) Data Types
1. Array
Array is a compound data type that can store multiple values of the same
data type. Below is an example of an array of integers. It combines a
series of data that are related together.
PHP
<?php
?>
Output
First Element: 10
Second Element: 20
Third Element: 30
array(3) {
[0]=>
int(10)
[1]=>
int(20)
[2]=>
int(30)
}
We will discuss arrays in detail in further articles.
2. Objects
Objects are defined as instances of user-defined classes that can hold
both values and functions and information for data processing specific to
the class. This is an advanced topic and will be discussed in detail in
further articles. When the objects are created, they inherit all the
properties and behaviours from the class, having different values for all
the properties.
Objects are explicitly declared and created from the new keyword.
PHP
<?php
class gfg {
public $message;
function __construct($message) {
$this->message = $message;
}
function msg() {
return "This is an example of " . $this->message . "!";
}
}
?>
Output
This is an example of Object Data Type!
Special Data Types
1. NULL
These are special types of variables that can hold only one value i.e.,
NULL. We follow the convention of writing it in capital form, but it’s
case-insensitive NULL, Null, and null are treated the same. If a variable
is created without a value or no value, it is automatically assigned a
value of NULL. It is written in capital letters.
PHP
<?php
$nm = NULL;
echo $nm; // this will return no output
Output
NULL
2. Resources
Resources in PHP are not an exact data type. These are basically used to
store references to some function call or to external PHP resources. For
example, consider a database call. This is an external resource. Resource
variables hold special handles for files and database connections.
PHP Operators
Operators are used to performing operations on some values.
$x + Sum the
+ Addition
$y operands
Difference
$x –
– Subtraction s the
$y
operands
Operato Synta
r Name x Operation
Product of
$x *
* Multiplication the
$y
operands
The
$x / quotient of
/ Division
$y the
operands
$x raised
Exponentiatio $x **
** to the
n $y
power $y
The
$x % remainder
% Modulus
$y of the
operands
Note: The exponentiation has been introduced in PHP 5.6.
Example: This example explains the arithmetic operator in PHP.
PHP
<?php
// Define two numbers
$x = 10;
$y = 3;
// Addition
echo "Addition: " . ($x + $y) . "\n";
// Subtraction
echo "Subtraction: " . ($x - $y) . "\n";
// Multiplication
echo "Multiplication: " . ($x * $y) . "\n";
// Division
echo "Division: " . ($x / $y) . "\n";
// Exponentiation
echo "Exponentiation: " . ($x ** $y) . "\n";
// Modulus
echo "Modulus: " . ($x % $y) . "\n";
?>
Output
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333
Exponentiation: 1000
Modulus: 1
Logical or Relational Operators:
These are basically used to operate with conditional statements and
expressions. Conditional statements are based on conditions. Also, a
condition can either be met or cannot be met so the result of a
conditional statement can either be true or false. Here are the logical
operators along with their syntax and operations in PHP.
Operator Name Syntax Operation
True if either of
Logical $x or
or the operands is
OR $y
true else false
True if either of
Logical $x xor the operands is
xor
XOR $y true and false if
both are true
OR the operands is
true else false
Logical True if $x is
! !$x
NOT false
Example: This example describes the logical & relational operator in
PHP.
PHP
<?php
$x = 50;
$y = 30;
if ($x == 50 and $y == 30)
echo "and Success \n";
if ($x == 50 or $y == 20)
echo "or Success \n";
if ($x == 50 || $y == 20)
echo "|| Success \n";
if (!$z)
echo "! Success \n";
?>
Output:
and Success
or Success
xor Success
&& Success
|| Success
! Success
Comparison Operators: These operators are used to compare two
elements and outputs the result in boolean form. Here are the
comparison operators along with their syntax and operations in PHP.
Operator Name Syntax Operation
Returns True
$x == if both the
== Equal To
$y operands are
equal
Returns True
Not $x != if both the
!=
Equal To $y operands are
not equal
Returns True
Not $x <> if both the
<>
Equal To $y operands are
unequal
Returns True
if both the
$x === operands are
=== Identical
$y equal and are
of the same
type
Returns True
if both the
Not $x == operands are
!==
Identical $y unequal and
are of
different types
Returns True
Less $x <
< if $x is less
Than $y
than $y
Returns True
Greater $x >
> if $x is greater
Than $y
than $y
Operator Name Syntax Operation
Returns True
Less
$x <= if $x is less
<= Than or
$y than or equal
Equal To
to $y
Returns True
Greater
$x >= if $x is greater
>= Than or
$y than or equal
Equal To
to $y
Example: This example describes the comparison operator in PHP.
PHP
<?php
$a = 80;
$b = 50;
$c = "80";
Operand on
the left
$x = obtains the
= Assign
$y value of the
operand on
the right
Operator Name Syntax Operation
Simple
Add then $x += Addition
+=
Assign $y same as $x
= $x + $y
Simple
Subtract $x -= subtraction
-=
then Assign $y same as $x
= $x – $y
Simple
Multiply $x *= product
*=
then Assign $y same as $x
= $x * $y
Simple
Divide then
$x /= division
/= Assign
$y same as $x
(quotient)
= $x / $y
Simple
Divide then
$x %= division
%= Assign
$y same as $x
(remainder)
= $x % $y
Example: This example describes the assignment operator in PHP.
PHP
<?php
// Simple assign operator
$y = 75;
echo $y, "\n";
$x + Union of both
+ Union
$y i.e., $x and $y
Returns true
$x == if both has
== Equality
$y same key-
value pair
$x != Returns True
!= Inequality
$y if both are
Operator Name Syntax Operation
unequal
Returns True
if both have
the same key-
$x ===
=== Identity value pair in
$y
the same
order and of
the same type
Returns True
Non- $x !== if both are not
!==
Identity $y identical to
each other
Returns True
$x <>
<> Inequality if both are
$y
unequal
Example: This example describes the array operation in PHP.
PHP
<?php
$x = array("k" => "Car", "l" => "Bike");
$y = array("a" => "Train", "b" => "Plane");
var_dump($x + $y);
var_dump($x == $y) + "\n";
var_dump($x != $y) + "\n";
var_dump($x <> $y) + "\n";
var_dump($x === $y) + "\n";
var_dump($x !== $y) + "\n";
?>
Output:
array(4) {
["k"]=>
string(3) "Car"
["l"]=>
string(4) "Bike"
["a"]=>
string(5) "Train"
["b"]=>
string(5) "Plane"
}
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)
Increment/Decrement Operators: These are called the unary operators
as they work on single operands. These are used to increment or
decrement values.
Operator Name Syntax Operation
First
increments
Pre-
++ ++$x $x by one,
Increment
then return
$x
First
decrements
Pre-
— –$x $x by one,
Decrement
then return
$x
First returns
Post- $x, then
++ $x++
Increment increment it
by one
First returns
Post- $x, then
— $x–
Decrement decrement it
by one
Example: This example describes the Increment/Decrement operators in
PHP.
PHP
<?php
$x = 2;
echo ++$x, " First increments then prints \n";
echo $x, "\n";
$x = 2;
echo $x++, " First prints then increments \n";
echo $x, "\n";
$x = 2;
echo --$x, " First decrements then prints \n";
echo $x, "\n";
$x = 2;
echo $x--, " First prints then decrements \n";
echo $x;
?>
Output:
3 First increments then prints
3
2 First prints then increments
3
1 First decrements then prints
1
2 First prints then decrements
1
String Operators: This operator is used for the concatenation of 2 or
more strings using the concatenation operator (‘.’). We can also use the
concatenating assignment operator (‘.=’) to append the argument on the
right side to the argument on the left side.
Operato Synta
r Name x Operation
Concatenatio Concatenate
. $x.$y
n d $x and $y
First
concatenate
Concatenatio
$x.=$ s then
.= n and
y assigns,
assignment
same as $x
= $x.$y
Example: This example describes the string operator in PHP.
PHP
<?php
$x = "Geeks";
$y = "for";
$z = "Geeks!!!";
echo $x . $y . $z, "\n";
$x .= $y . $z;
echo $x;
?>
Output:
GeeksforGeeks!!!
GeeksforGeeks!!!
Spaceship Operators:
PHP 7 has introduced a new kind of operator called spaceship operator.
The spaceship operator or combined comparison operator is denoted by
“<=>“. These operators are used to compare values but instead of
returning the boolean results, it returns integer values. If both the
operands are equal, it returns 0. If the right operand is greater, it returns -
1. If the left operand is greater, it returns 1. The following table shows
how it works in detail:
Operator Syntax Operation
$x <=>
$x < $y Identical to -1 (right is greater)
$y
$x <=>
$x > $y Identical to 1 (left is greater)
$y
$x == $x <=>
Identical to 0 (both are equal)
$y $y
Operator Syntax Operation
$x <=>
$x != $y Not Identical to 0
$y
Example: This example illustrates the use of the spaceship operator in
PHP.
PHP
<?php
$x = 50;
$y = 50;
$z = 25;
MCQ
1. What is the correct way to declare a PHP variable?
o a) var name;
o b) name = "John";
o c) $name = "John";
o d) name := "John";
o Answer: c) $name = "John";
2. Which of the following is the correct way to embed PHP code within
an HTML file?
o a) <script>PHP code</script>
o b) <php>PHP code</php>
o c) <?php PHP code ?>
o d) <?php] PHP code [?>
o Answer: c) <?php PHP code ?>
3. Which symbol is used to denote a PHP variable?
o a) @
o b) #
o c) $
o d) &
o Answer: c) $
4. What will be the output of the following PHP code?
php
Copy code
$x = 5;
$y = 10;
echo $x + $y;
o a) 510
o b) 15
o c) 5 + 10
o d) 5 10
o Answer: b) 15
5. What is the purpose of the echo statement in PHP?
o a) To define a variable
o b) To output text to the browser
o c) To perform a calculation
o d) To accept user input
o Answer: b) To output text to the browser
6. Which of the following is used to end a PHP statement?
o a) .
o b) ;
o c) :
o d) ,
o Answer: b) ;
7. What is the correct way to write a comment in PHP?
o a) /* This is a comment */
o b) // This is a comment
o c) # This is a comment
o d) All of the above
o Answer: d) All of the above
8. How can you check if a PHP script is being processed in a web
browser?
o a) Using print()
o b) Using echo
o c) Using exit()
o d) Using print_r()
o Answer: b) Using echo
9. Which of the following will work to declare a constant in PHP?
o a) define('PI', 3.14);
o b) constant('PI', 3.14);
o c) constant PI = 3.14;
o d) var PI = 3.14;
o Answer: a) define('PI', 3.14);
10.Which PHP function is used to include a PHP file in another PHP
file?
o a) include()
o b) require()
o c) include_once()
o d) All of the above
o Answer: d) All of the above
11.What will the following PHP code output?
php
Copy code
echo "<h1>Hello World</h1>";
o a) Hello World
o b) <h1>Hello World</h1>
o c) Hello World as an H1 tag
o d) None of the above
o Answer: c) Hello World as an H1 tag
12.How do you display the value of a PHP variable inside an HTML
tag?
o a) <?php echo $variable ?>
o b) <php echo $variable ?>
o c) <?php $variable ?>
o d) <?php var $variable ?>
o Answer: a) <?php echo $variable ?>
13.Which of the following is the correct syntax for embedding HTML in
PHP?
o a) <?php <h1>Heading</h1> ?>
o b) <?php echo "<h1>Heading</h1>"; ?>
o c) <?php echo '<h1>Heading</h1>'; ?>
o d) Both b and c are correct
o Answer: d) Both b and c are correct
14.Which of the following is a valid variable name in PHP?
o a) 2name
o b) _name
o c) @name
o d) #name
o Answer: b) _name
15.What will be the output of the following code?
php
Copy code
$x = 10;
echo $x;
o a) 10
o b) $x
o c) Error
o d) None of the above
o Answer: a) 10
16.Which PHP data type is used to store true or false values?
o a) String
o b) Integer
o c) Boolean
o d) Object
o Answer: c) Boolean
17.Which function is used to get the type of a variable in PHP?
o a) gettype()
o b) type()
o c) var_type()
o d) typeof()
o Answer: a) gettype()
18.Which of the following is not a valid data type in PHP?
o a) Integer
o b) String
o c) Object
o d) Floaty
o Answer: d) Floaty
19.Which data type in PHP is used to store decimal values?
o a) Integer
o b) String
o c) Float
o d) Boolean
o Answer: c) Float
20.What will the following code output?
php
Copy code
$x = "Hello";
$y = 5;
echo $x . $y;
o a) Hello5
o b) Hello 5
o c) Hello
o d) 5
o Answer: a) Hello5
5 MARKS
1. Explain how to embed PHP code into an HTML file and provide an
example.
2. Describe the different data types available in PHP and give an example
for each.
3. What is the significance of the $ symbol in PHP? Illustrate with an
example.
4. How can you embed HTML code within a PHP file and display output
using PHP?
5. What are the different ways to define a variable in PHP, and what are the
rules for naming a variable?
6. Explain the working of the if, else if, and else statements with an
example.
7. What are the different comparison operators in PHP and how are they
used in conditional statements?
10 MARKS
1.Explain the basic syntax of PHP and the role of the <?php ?> tags in
embedding PHP code within HTML.
2.Describe how PHP variables are declared, initialized, and used, along with
an explanation of variable scope and global vs local variables.
3.Compare and contrast the use of if, else if, and else statements in PHP, with
examples to demonstrate their practical application in conditional logic.
4.Explain the different data types in PHP (integer, float, string, array, and
object), and provide examples of how each is used in PHP scripts.
UNIT – 3
Syntax:
switch(expression)
{
case val1:
// Code Statement
break;
case val2:
// Code statement
break;
...
default:
// Code Statement
}
Example 1: The following code demonstrates the switch statement.
• PHP
<?php
$x = 2;
switch ($x) {
case 1:
printf("Choice is 1");
break;
case 2:
printf("Choice is 2");
break;
case 3:
printf("Choice is 3");
break;
default:
printf("Choice other than 1, 2 and 3");
?>
Output
Choice is 2
Example 2:
• PHP
<?php
$n='C';
switch($n)
{
case 'A':
case 'B':
printf("A and B\n");
break;
case 'C':
case 'D':
printf("C and D\n");
break;
?>
Output
C and D
PHP while Loop
The while loop is the simple loop that executes nested statements
repeatedly while the expression value is true. The expression is checked
every time at the beginning of the loop, and if the expression evaluates
to true then the loop is executed otherwise loop is terminated.
Flowchart of While Loop:
Syntax:
while (if the condition is true) {
// Code is executed
}
Example 1: This example uses a while loop to display numbers.
• PHP
<?php
// Declare a number
$num = 10;
// While Loop
while ($num < 20) {
echo $num . "\n";
$num += 2;
}
?>
Output
10
12
14
16
18
while-endWhile loop:
Syntax:
while (if the condition is true):
// Code is executed
...
endwhile;
Example 2: This example uses while and endwhile to display the
numbers.
• PHP
<?php
// Declare a number
$num = 10;
// While Loop
while ($num < 20):
echo $num . "\n";
$num += 2;
endwhile;
?>
Output
10
12
14
16
18
?>
Output
0
5
10
15
Example 2: The following code shows another example of for loop.
• PHP
<?php
Creating a Function
Syntax:
function function_name(){
executable code;
}
Example:
PHP
1
<?php
2
3
function funcGeek()
4
{
5
echo "This is Geeks for Geeks";
6
}
7
8
// Calling the function
9
funcGeek();
10
11
?>
Output:
This is Geeks for Geeks
Example:
PHP
1
<?php
2
3
// function along with three parameters
4
function proGeek($num1, $num2, $num3)
5
{
6
$product = $num1 * $num2 * $num3;
7
echo "The product is $product";
8
}
9
10
// Calling the function
?>
Output:
The product is 30
PHP
<?php
defGeek("Ram", 15);
// will be considered
defGeek("Adam");
?>
Output:
In the above example, the parameter $num has a default value 12, if we
do not pass any value for this parameter in a function call then this
default value 12 will be considered. Also the parameter $str has no
default value , so it is compulsory.
Functions can also return values to the part of program from where it is
called. The return keyword is used to return value back to the part of
program, from where it was called. The returning value may be of any
type including the arrays and objects. The return statement also marks
the end of the function and stops the execution after that and returns the
value.
Example:
PHP
<?php
The product is 30
Example:
PHP
<?php
// pass by value
function valGeek($num) {
$num += 2;
return $num;
// pass by reference
function refGeek(&$num) {
$num += 10;
return $num;
$n = 10;
valGeek($n);
refGeek($n);
?>
Output:
// Create an array
$sub = array("DBMS", "Algorithm", "C++", "JAVA");
// Declare 2D array
$detail = array(array(1, 2, 3, 4),
array(5, 6, 7, 8));
<?php
$length = count($arr);
?>
Output
12345
Using foreach Loop
The PHP foreach loop is an method to iterate through an array. There is
no need of index number in foreach loop.
PHP
<?php
}
?>
Output
12345
Using while Loop with each() Function
The PHP each() function can be used in combination with a while
loop to iterate through an array while maintaining the internal pointer.
PHP
<?php
. $element['value'] . "\n";
?>
Output
0 => apple
1 => banana
2 => cherry
Using array_walk() with a callback function
In PHP, `array_walk()` iterates through an array, applying a user-defined
callback function to each element. The callback receives each array
element as an argument, allowing for custom operations on array values
without needing to manage iteration explicitly.
Example:
PHP
<?php
function printElement($value) {
array_walk($array, 'printElement');
?>
Output
12345
Using array_map() with a Callback Function
The array_map() function in PHP applies a callback function to each
element of an array, creating and returning a new array with the results
of the callback function.
Example:
PHP
<?php
function increment($value) {
return $value + 1;
?>
Output
23456
Using array_reduce()
This approach uses array_reduce() to apply a callback function to each
element of the array, reducing the array to a single cumulative value.
Example:
PHP
<?php
});
?>
Output
apple
banana
cherry
let fruits = [
fruit_name: "Apple",
fruit_color: "Red",
},
fruit_name: "Pomegranate",
fruit_color: "Red",
},
fruit_name: "Grapes",
fruit_color: "Green",
},
fruit_name: "Kiwi",
fruit_color: "Green",
},
];
let filtered_fruits = fruits.filter((fruit) =>
console.log(filtered_fruits);
Output
[
{ fruit_name: 'Apple', fruit_color: 'Red' },
{ fruit_name: 'Pomegranate', fruit_color: 'Red' }
]
Approach 2: Using Object.values()
In this approach, we will use the same array containing multiple objects
which we have created previously, and here we will create another
function that will be responsible for containing our logic for the above-
enlightened problem statement.
Then the first part of our logic will be using Object.values() method that
will actually accumulate all the object values for us and just after that we
will use Array.reduce() method which will reduce our array into objects
and then using nullish coalescing operator (??) we will either add the
property value inside the accumulator value (part of reduce method) or
we will add an empty array instead of it ([ ]).
The second part of our logic says that we have to push the current value
inside the accumulator value itself that contains the previously added
value in it and then at the end, we will return the accumulator value
itself.
Syntax:
Object.values(obj)
Example: This example shows the implementation of the above-
explained approach.
JavaScript
let fruits = [
{
fruit_name: "Apple",
fruit_color: "Red",
},
{
fruit_name: "Pomegranate",
fruit_color: "Red",
},
fruit_name: "Grapes",
fruit_color: "Green",
},
fruit_name: "Kiwi",
fruit_color: "Green",
},
];
acc[current.fruit_color].push(current);
return acc;
}, {})
);
console.log(groupingViaCommonProperty);
Output
[
[
{ fruit_name: 'Apple', fruit_color: 'Red' },
{ fruit_name: 'Pomegranate', fruit_color: 'Red' }
],
[
{ fruit_name: 'Grapes', fruit_color: 'Green' },
{ fruit_name: 'Kiwi', frui...
Approach 3: Using the reduce() method
The reduce() method in JavaScript applies a function to each element of
an array, accumulating a single result, and returns the final output.
Syntax:
array.reduce( function(total, currentValue, currentIndex, arr),
initialValue );
Example: In this example, we are using the reduce() method and create
an array of arrays containing fruits of the same color. The resultArray
logs the grouped fruits.
JavaScript
const fruits = [
fruit_name: "Apple",
fruit_color: "Red",
},
fruit_name: "Pomegranate",
fruit_color: "Red",
},
fruit_name: "Grapes",
fruit_color: "Green",
},
fruit_name: "Kiwi",
fruit_color: "Green",
},
];
return acc;
}, {});
Output
[
[
{ fruit_name: 'Apple', fruit_color: 'Red' },
{ fruit_name: 'Pomegranate', fruit_color: 'Red' }
],
[
{ fruit_name: 'Grapes', fruit_color: 'Green' },
{ fruit_name: 'Kiwi', frui...
Output
[
[
{ fruit_name: 'Apple', fruit_color: 'Red' },
{ fruit_name: 'Pomegranate', fruit_color: 'Red' }
],
[
{ fruit_name: 'Grapes', fruit_color: 'Green' },
{ fruit_name: 'Kiwi', fruit_color: 'Green' }
]
]
Approach 4: Using for…of loop
The for…of loop in JavaScript iterates over iterable objects like arrays,
strings, maps, sets, etc. We can use it to group objects in an array based
on a common property.
Syntax:
for ( variable of iterableObjectName) {
...
}
Example: In this example, we are using the above-explained approach.
JavaScript
1
const fruits = [
fruit_name: "Apple",
fruit_color: "Red",
},
fruit_name: "Pomegranate",
fruit_color: "Red",
},
fruit_name: "Grapes",
fruit_color: "Green",
},
{
fruit_name: "Kiwi",
fruit_color: "Green",
},
];
if (!groupedByColor[color]) {
groupedByColor[color] = [fruit];
} else {
groupedByColor[color].push(fruit);
console.log(resultArray);
Output
[
[
{ fruit_name: 'Apple', fruit_color: 'Red' },
{ fruit_name: 'Pomegranate', fruit_color: 'Red' }
],
[
{ fruit_name: 'Grapes', fruit_color: 'Green' },
{ fruit_name: 'Kiwi', frui...
Output:
[
[
{ fruit_name: 'Apple', fruit_color: 'Red' },
{ fruit_name: 'Pomegranate', fruit_color: 'Red' }
],
[
{ fruit_name: 'Grapes', fruit_color: 'Green' },
{ fruit_name: 'Kiwi', fruit_color: 'Green' }
]
]
Approach 5: Using forEach()
Using the forEach() method in JavaScript, we can iterate over each
element in an array and group objects based on a common property.
Syntax:
array.forEach(callback(element, index, arr), thisValue)
Example: In this example, the forEach() loop iterates over each fruit in
the fruits array. It checks the fruit_color property, creates an empty array
for color if it doesn’t exist in the groupedByColor object, and then
pushes the fruit into the corresponding array based on its color.
JavaScript
const fruits = [
fruit_name: "Apple",
fruit_color: "Red",
},
fruit_name: "Pomegranate",
fruit_color: "Red",
},
{
fruit_name: "Grapes",
fruit_color: "Green",
},
{
fruit_name: "Kiwi",
fruit_color: "Green",
},
];
fruits.forEach((fruit) => {
groupedByColor[color].push(fruit);
});
console.log(resultArray);
Output:
[
[
{ fruit_name: 'Apple', fruit_color: 'Red' },
{ fruit_name: 'Pomegranate', fruit_color: 'Red' }
],
[
{ fruit_name: 'Grapes', fruit_color: 'Green' },
{ fruit_name: 'Kiwi', fruit_color: 'Green' }
]
]
Approach 6: Using Map
Using the Map object, we can efficiently group objects based on a
common property. Map provides better performance for frequent
additions and lookups compared to plain objects.
Syntax:
new Map(iterable);
Example:
JavaScript
const fruits = [
];
fruits.forEach((fruit) => {
if (!groupedByColor.has(color)) {
groupedByColor.set(color, [fruit]);
} else {
groupedByColor.get(color).push(fruit);
});
const resultArray = Array.from(groupedByColor.values());
console.log(resultArray);
Output
[
[
{ fruit_name: 'Apple', fruit_color: 'Red' },
{ fruit_name: 'Pomegranate', fruit_color: 'Red' }
],
[
{ fruit_name: 'Grapes', fruit_color: 'Green' },
{ fruit_name: 'Kiwi', frui...
MCQ
9. What is the correct syntax for a for loop in PHP? A) for($i = 0; $i < 5;
$i++)
B) for(i = 0; i < 5; i++)
C) for($i; $i <= 5; $i++)
D) for($i = 0; $i < 5)
Answer: A) for($i = 0; $i < 5; $i++)
10.Which loop is best suited when the number of iterations is known
beforehand? A) while
B) for
C) do-while
D) foreach
Answer: B) for
11.What will this PHP code output?
php
Copy code
for ($i = 1; $i <= 3; $i++) {
echo $i;
}
A) 1
B) 12
C) 123
D) 1234
Answer: C) 123
12.In a for loop, if the condition is never true, what happens? A) The
loop will execute infinitely
B) The loop will never execute
C) The loop will execute once
D) An error occurs
Answer: B) The loop will never execute
13.Which of the following is used to declare a function in PHP? A)
function myFunc() { }
B) func myFunc() { }
C) def myFunc() { }
D) declare function myFunc() { }
Answer: A) function myFunc() { }
14.What will be the output of the following PHP code?
php
Copy code
function add($a, $b) {
return $a + $b;
}
echo add(2, 3);
A) 5
B) 23
C) 6
D) Error
Answer: A) 5
15.What does the return keyword do in PHP functions? A) Terminates
the function without returning any value
B) Returns a value and exits the function
C) Prints the value to the screen
D) Stops the program execution
Answer: B) Returns a value and exits the function
16.Which PHP function is used to include the content of one PHP file in
another? A) include()
B) require()
C) require_once()
D) All of the above
Answer: D) All of the above
17.Which PHP function is used to get the length of a string? A) len()
B) strlen()
C) length()
D) str_length()
Answer: B) strlen()
18.How do you create an indexed array in PHP? A) $arr = array(1, 2, 3);
B) $arr = [1, 2, 3];
C) $arr = (1, 2, 3);
D) Both A and B
Answer: D) Both A and B
19.How can you access the first element of an array $arr = [10, 20, 30];?
A) $arr[0]
B) $arr[1]
C) $arr[10]
D) $arr['first']
Answer: A) $arr[0]
20.Which of the following will modify the value of the third element of
an array $arr = [1, 2, 3, 4, 5];? A) $arr[3] = 10;
B) $arr[2] = 10;
C) $arr[1] = 10;
D) $arr[5] = 10;
Answer: B) $arr[2] = 10;
21.What will the count() function do with an array? A) Counts the
elements in an array
B) Displays the array values
C) Deletes an element
D) Changes the array structure
Answer: A) Counts the elements in an array
22.How do you check if an array element exists in PHP? A) isset()
B) array_key_exists()
C) in_array()
D) All of the above
Answer: D) All of the above
23.Which function in PHP is used to add an element to the end of an
array? A) array_push()
B) array_pop()
C) array_add()
D) array_insert()
Answer: A) array_push()
24.Which PHP function removes the last element of an array? A)
array_pop()
B) array_shift()
C) array_unshift()
D) array_slice()
Answer: A) array_pop()
25.How do you create an associative array in PHP? A) $arr = ["a" => 1,
"b" => 2];
B) $arr = [1, 2, 3];
C) $arr = (a = 1, b = 2);
D) $arr = array("a", "b", 1, 2);
Answer: A) $arr = ["a" => 1, "b" => 2];
26.Which loop is used to iterate over an array in PHP? A) foreach
B) for
C) while
D) All of the above
Answer: A) foreach
27.How do you loop through an associative array in PHP? A)
foreach($array as $key => $value)
B) for($key = 0; $key < count($array); $key++)
C) while($value = each($array))
D) for($i = 0; $i < sizeof($array); $i++)
Answer: A) foreach($array as $key => $value)
28.What will the following code print?
php
Copy code
$arr = [1, 2, 3];
foreach ($arr as $value) {
echo $value;
}
A) 1 2 3
B) 123
C) 1
D) 3
Answer: B) 123
29.What is the purpose of array_map() in PHP? A) Sorts an array
B) Applies a callback function to each element of an array
C) Returns a subset of an array
D) Combines multiple arrays
Answer: B) Applies a callback function to each element of an array
30.Which of the following functions returns all the keys of an array? A)
array_keys()
B) array_values()
C) array_flip()
D) array_unique()
Answer: A) array_keys()
31.How do you store form selection values in an array in PHP? A)
$_POST['field_name']
B) $_GET['field_name']
C) Both A and B
D) None of the above
Answer: C) Both A and B
32.What does the $_POST superglobal contain? A) Values submitted via
GET
B) Values submitted via POST method
C) Cookie values
D) Server information
Answer: B) Values submitted via POST method
33.Which PHP function would you use to group form selections into an
array? A) explode()
B) implode()
C) array_merge()
D) array_map()
Answer: A) explode()
34.How can you retrieve the value of a checkbox that was selected in a
form? A) $_POST['checkbox_name']
B) $_POST['checkbox_name[]']
C) $_GET['checkbox_name']
D) $_POST['checkbox_name[0]']
Answer: B) $_POST['checkbox_name[]']
35.Which function sorts an array in ascending order in PHP? A)
array_sort()
B) sort()
C) array_order()
D) arrange()
Answer: B) sort()
36.What does the array_reverse() function do? A) Sorts an array in
reverse order
B) Returns the keys of an array in reverse
C) Reverses the order of an array without changing its keys
D) Reverses the array values
Answer: C) Reverses the order of an array without changing its keys
37.Which of the following is used to join array elements into a string? A)
implode()
B) explode()
C) join()
D) Both A and C
Answer: D) Both A and C
38.Which function removes duplicate elements from an array? A)
array_unique()
B) array_diff()
C) array_merge()
D) array_filter()
Answer: A) array_unique()
39.How can you combine two arrays into one in PHP? A) merge()
B) combine()
C) array_merge()
D) array_combine()
Answer: C) array_merge()
40.What function would you use to find the intersection of two arrays?
A) array_merge()
B) array_diff()
C) array_intersect()
D) array_union()
Answer: C) array_intersect()
41.What does the array_shift() function do in PHP? A) Removes the last
element of an array
B) Removes the first element of an array
C) Adds an element to the beginning of the array
D) Sorts the array in ascending order
Answer: B) Removes the first element of an array
42.Which of the following functions adds an element to the beginning of
an array? A) array_unshift()
B) array_push()
C) array_add()
D) array_insert()
Answer: A) array_unshift()
43.Which function is used to check if an array contains a specific value?
A) array_key_exists()
B) in_array()
C) array_exists()
D) isset()
Answer: B) in_array()
44.What does the array_slice() function do in PHP? A) Returns a portion
of the array
B) Merges two arrays
C) Reverses the order of an array
D) Filters the elements of an array
Answer: A) Returns a portion of the array
45.Which function is used to change all the keys of an array to their
values? A) array_flip()
B) array_map()
C) array_key_exists()
D) array_change_key_case()
Answer: A) array_flip()
46.How do you check if a key exists in an associative array? A) isset()
B) array_key_exists()
C) key_exists()
D) in_array()
Answer: B) array_key_exists()
47.Which of the following functions adds elements at the end of an
associative array? A) array_push()
B) array_unshift()
C) array_append()
D) array_add()
Answer: A) array_push()
48.Which function merges two associative arrays? A) array_merge()
B) array_push()
C) array_add()
D) array_combine()
Answer: A) array_merge()
49.How do you count the number of elements in an associative array?
A) count()
B) sizeof()
C) array_count()
D) Both A and B
Answer: D) Both A and B
50.Which of the following functions retrieves the first element of an
associative array? A) array_shift()
B) array_pop()
C) reset()
D) end()
Answer: C) reset()
5 MARKS
1. Explain the difference between switch and if-else statements in PHP.
2. What is the purpose of a while() loop in PHP and how does it differ from
a do-while() loop?
3. How does a for() loop work in PHP? Provide an example.
4. Describe how to define a function in PHP and call it.
5. How do you create an indexed array in PHP? Give an example.
6. What is the significance of the array_push() function in PHP?
7. How can you modify an element in an array in PHP? Explain with an
example.
8. What is the foreach() loop used for in PHP and how does it work with
arrays?
9. How do you group multiple form selections into an array in PHP?
10.How do you check if an array contains a specific value in PHP?
11.Explain how the array_merge() function works in PHP with an example.
12.What is the role of isset() and empty() functions in PHP with arrays?
13.Describe how you can use array_map() to process elements in an array.
14.How do you add elements to the beginning of an array in PHP? Explain
with an example.
15.What is the array_slice() function in PHP and how is it used?
10 MARKS
1. Explain the process of creating, modifying, and accessing elements in
indexed and associative arrays in PHP.
2. Compare and contrast switch() and if-else statements with examples in
PHP.
3. How does the while() loop work in PHP? Illustrate with an example and
discuss potential issues like infinite loops.
4. Describe the for() loop structure in PHP and provide a real-world
scenario where it is useful.
5. What is the importance of functions in PHP? Create a function that
accepts parameters and returns a result.
6. Discuss the concept of array functions in PHP with examples of
array_map(), array_filter(), and array_reduce().
7. Explain the concept of processing arrays using loops, especially with
foreach(), and demonstrate with examples.
8. How would you handle form selections in PHP and group the values
using arrays? Provide an example.
9. Describe how to modify arrays in PHP using functions like
array_splice(), array_slice(), and array_merge().
10.Explain the difference between array_keys() and array_values() in PHP
and illustrate their usage with examples.
UNIT – IV
if ($file) {
// Read one character at a time
while (($char = fgetc($file)) !== false) {
echo $char;
}
5 Marks
1. Explain the function of fopen() in file handling in PHP.
2. How does fgets() work in reading data from a file in PHP?
3. Describe the difference between fopen() and file_get_contents() in PHP.
4. What is the purpose of feof() in file reading operations in PHP?
5. How can you read an entire file in PHP using file_get_contents()?
6. What is the significance of fclose() in PHP file handling?
7. Describe how to read a file line by line in PHP.
8. What does file_exists() do in PHP and how is it used in file operations?
9. Explain how to handle errors when reading a file in PHP.
10.How can you read a file into an array in PHP using file()?
11.What is the use of fread() in reading files and how does it differ from
fgets()?
12.How do you check if a file is readable before attempting to read it in
PHP?
13.Discuss the use of file_get_contents() for reading remote files in PHP.
14.What are the benefits of using fgetcsv() for reading CSV files in PHP?
15.How does file() function read a file and return it as an array in PHP?
10 Marks
1. Explain the entire process of reading data from a file in PHP using
fopen(), fgets(), and fclose().
2. How do you handle large files efficiently in PHP while reading them line
by line?
3. Discuss the different ways of reading files in PHP and compare their
performance.
4. Explain the role of file pointers in file reading operations in PHP.
5. Demonstrate the usage of fread() with an example and explain how it
differs from fgets().
6. How does PHP handle file locking during read operations, and what
functions are involved?
7. Discuss the security concerns involved in reading files in PHP and how to
mitigate them.
8. What is the purpose of file_get_contents() and how does it handle file
reading and errors?
9. Explain how to read binary data from a file using PHP and give an
example.
10.How can you implement error handling in PHP when attempting to read a
file that does not exist?
UNIT-V
A PHP session is used to store data on a server rather than the computer
of the user. Session identifiers or SID is a unique number which is used
to identify every user in a session based environment. The SID is used to
link the user with his information on the server like posts, emails etc.
How are sessions better than cookies?
Although cookies are also used for storing user related data, they have
serious security issues because cookies are stored on the user’s computer
and thus they are open to attackers to easily modify the content of the
cookie. Addition of harmful data by the attackers in the cookie may
result in the breakdown of the application.
Apart from that cookies affect the performance of a site since cookies
send the user data each time the user views a page. Every time the
browser requests a URL to the server, all the cookie data for that website
is automatically sent to the server within the request.
Below are different steps involved in PHP sessions:
• Starting a PHP Session: The first step is to start up a session. After a
session is started, session variables can be created to store information.
The PHP session_start() function is used to begin a new session.It also
creates a new session ID for the user.
Below is the PHP code to start a new session:
<?php
session_start();
?>
session_start();
$_SESSION["Rollnumber"] = "11";
$_SESSION["Name"] = "Ajay";
?>
session_start();
?>
Output:
The Name of the student is :Ajay
The Roll number of the student is :11
• Destroying Certain Session Data: To delete only a certain session
data,the unset feature can be used with the corresponding session variable
in the $_SESSION associative array.
The PHP code to unset only the “Rollnumber” session variable from the
associative session array:
<?php
session_start();
if(isset($_SESSION["Name"])){
unset($_SESSION["Rollnumber"]);
}
?>
• Destroying Complete Session: The session_destroy() function is used to
completely destroy a session. The session_destroy() function does not
require any argument.
<?php
session_start();
session_destroy();
?>
Important Points
1. The session IDs are randomly generated by the PHP engine .
2. The session data is stored on the server therefore it doesn’t have to be
sent with every browser request.
3. The session_start() function needs to be called at the beginning of the
page, before any output is generated by the script in the browser.
PHP Cookies
A cookie in PHP is a small file with a maximum size of 4KB that the
web server stores on the client computer. They are typically used to keep
track of information such as a username that the site can retrieve to
personalize the page when the user visits the website next time. A cookie
can only be read from the domain that it has been issued from. Cookies
are usually set in an HTTP header but JavaScript can also set a cookie
directly on a browser.
Setting Cookie In PHP: To set a cookie in PHP,
the setcookie() function is used. The setcookie() function needs to be
called prior to any output generated by the script otherwise the cookie
will not be set.
Syntax:
setcookie(name, value, expire, path, domain, security);
Parameters: The setcookie() function requires six arguments in general
which are:
• Name: It is used to set the name of the cookie.
• Value: It is used to set the value of the cookie.
• Expire: It is used to set the expiry timestamp of the cookie after which
the cookie can’t be accessed.
• Path: It is used to specify the path on the server for which the cookie will
be available.
• Domain: It is used to specify the domain for which the cookie is
available.
• Security: It is used to indicate that the cookie should be sent only if a
secure HTTPS connection exists.
Below are some operations that can be performed on Cookies in PHP:
• Creating Cookies: Creating a cookie named Auction_Item and assigning
the value Luxury Car to it. The cookie will expire after 2 days(2 days *
24 hours * 60 mins * 60 seconds).
Example: This example describes the creation of the cookie in PHP.
• PHP
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "cookie is created."
?>
<p>
<strong>Note:</strong>
You might have to reload the
page to see the value of the cookie.
</p>
</body>
</html>
</body>
</html>
Output:
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>
</body>
</html>
Output:
</body>
</html>
Output:
MCQ
1.What is the purpose of a session in web development?
• A. To store user data permanently
• B. To maintain state across multiple pages
• C. To authenticate users
• D. To store data on the server permanently
Answer: B. To maintain state across multiple pages
2. Which PHP function is used to start a session?
• A. session_start()
• B. start_session()
• C. initialize_session()
• D. begin_session()
Answer: A. session_start()
3. How do you set a session variable in PHP?
• A. $_SESSION["variable"] = "value";
• B. session_set("variable", "value");
• C. set_session("variable", "value");
• D. session["variable"] = "value";
Answer: A. $_SESSION["variable"] = "value";
4. Which of the following functions is used to destroy all session variables in
PHP?
• A. session_unset()
• B. session_destroy()
• C. unset_session()
• D. destroy_session()
Answer: B. session_destroy()
5. What does the session_unset() function do in PHP?
• A. Ends the session
• B. Deletes all session variables
• C. Clears the session data from the server
• D. Removes the session file
Answer: B. Deletes all session variables
6. What is the default duration of a session in PHP?
• A. 30 minutes
• B. Until the browser is closed
• C. 1 hour
• D. 24 hours
Answer: B. Until the browser is closed
7. What is the PHP superglobal used to access session variables?
• A. $_SESSION
• B. $_COOKIE
• C. $_SERVER
• D. $_POST
Answer: A. $_SESSION
8. How can you check if a session variable is set in PHP?
• A. isset($_SESSION["variable"]);
• B. check_session("variable");
• C. is_session_set("variable");
• D. session_set("variable");
Answer: A. isset($_SESSION["variable"]);
9. Which PHP function is used to set a cookie?
• A. setcookie()
• B. cookie_set()
• C. set_cookie()
• D. create_cookie()
Answer: A. setcookie()
10. Which of the following can be stored in a cookie?
• A. Only strings
• B. Strings, integers, and arrays
• C. Only integers
• D. Only session data
Answer: A. Only strings
11. How do you retrieve a cookie value in PHP?
• A. $_COOKIE["cookie_name"]
• B. getcookie("cookie_name")
• C. cookie("cookie_name")
• D. $_SESSION["cookie_name"]
Answer: A. $_COOKIE["cookie_name"]
12. What is the maximum size of a cookie in PHP?
• A. 1024 bytes
• B. 4096 bytes
• C. 2048 bytes
• D. 512 bytes
Answer: B. 4096 bytes
13. How long does a session last in PHP by default?
• A. Until the browser is closed
• B. 1 hour
• C. 30 minutes
• D. 24 hours
Answer: A. Until the browser is closed
14. Which function removes a session variable in PHP?
• A. unset()
• B. remove_session_variable()
• C. session_remove()
• D. delete_session_variable()
Answer: A. unset()
15. How can you destroy a specific session variable in PHP?
• A. unset($_SESSION["variable"]);
• B. session_unset("variable");
• C. destroy_session_variable("variable");
• D. remove_session("variable");
Answer: A. unset($_SESSION["variable"]);
16. What is the syntax to delete a cookie in PHP?
• A. setcookie("cookie_name", "", time() - 3600);
• B. delete_cookie("cookie_name");
• C. unsetcookie("cookie_name");
• D. remove_cookie("cookie_name");
Answer: A. setcookie("cookie_name", "", time() - 3600);
17. Which PHP function checks whether a cookie exists?
• A. isset()
• B. cookie_exists()
• C. isset_cookie()
• D. check_cookie()
Answer: A. isset()
18. What does the time() function return in PHP?
• A. The current date and time
• B. The current timestamp
• C. The timestamp of the session start
• D. The cookie expiration time
Answer: B. The current timestamp
19. How can you prevent a session from timing out in PHP?
• A. By using session_set_timeout()
• B. By resetting session expiration periodically
• C. By storing the session in a database
• D. By extending the browser's timeout
Answer: B. By resetting session expiration periodically
20. What is a session ID in PHP?
• A. A unique identifier for each session
• B. A random number generated for each user
• C. A way to store user data
• D. A method for authentication
Answer: A. A unique identifier for each session
21. What happens if a user does not accept cookies in a browser?
• A. The user cannot access the website
• B. Cookies will be rejected and no session data will be saved
• C. The user will be redirected to a different page
• D. Cookies will be stored in the browser but never sent to the server
Answer: B. Cookies will be rejected and no session data will be saved
22. Which of the following is a characteristic of session cookies?
• A. They are stored until the user manually deletes them
• B. They are deleted once the session ends
• C. They last for a specific time duration set by the developer
• D. They are stored in the database
Answer: B. They are deleted once the session ends
23. How can you make a cookie secure?
• A. By setting the secure flag to true
• B. By encrypting the cookie value
• C. By setting the HttpOnly flag
• D. All of the above
Answer: D. All of the above
24. What is the difference between a session and a cookie?
• A. Cookies are more secure than sessions
• B. Cookies are stored on the client-side, while sessions are stored on the
server-side
• C. Sessions store data temporarily, while cookies store data permanently
• D. There is no difference
Answer: B. Cookies are stored on the client-side, while sessions are stored on the
server-side
25. What is the function of session_regenerate_id() in PHP?
• A. To regenerate the session data
• B. To change the session ID and keep the session active
• C. To regenerate session cookies
• D. To reset the session timeout
Answer: B. To change the session ID and keep the session active
26. How do you store data in a session in PHP?
• A. $_SESSION["key"] = "value";
• B. session_set("key", "value");
• C. store_session("key", "value");
• D. session_data("key", "value");
Answer: A. $_SESSION["key"] = "value";
27. Which of the following is used to check if a session is started?
• A. isset($_SESSION)
• B. session_started()
• C. check_session()
• D. session_status()
Answer: A. isset($_SESSION)
28. What is the correct way to destroy a session in PHP?
• A. unset($_SESSION); session_destroy();
• B. session_destroy();
• C. delete_session();
• D. unset($_SESSION["variable"]); session_end();
Answer: A. unset($_SESSION); session_destroy();
29. Which PHP function allows you to set the expiration date of a cookie?
• A. setcookie()
• B. cookie_set()
• C. set_expiration()
• D. expire_cookie()
Answer: A. setcookie()
30. How do you make a session cookie that expires when the browser is
closed?
• A. By not setting an expiration date
• B. By setting the expiration to 0
• C. By using time() as the expiration
• D. By setting the secure flag
Answer: A. By not setting an expiration date
31. What is the correct syntax to set a cookie that expires in 1 hour in PHP?
• A. setcookie("name", "value", time() + 3600);
• B. setcookie("name", "value", time() - 3600);
• C. setcookie("name", "value", "1 hour");
• D. cookie("name", "value", 3600);
Answer: A. setcookie("name", "value", time() + 3600);
32. How can you pass data between pages using sessions in PHP?
• A. By using $_GET variables
• B. By using $_SESSION variables
• C. By using cookies
• D. By using hidden form fields
Answer: B. By using $_SESSION variables
33. Which of the following is true about the HttpOnly flag in cookies?
• A. It makes the cookie accessible via JavaScript
• B. It prevents the cookie from being accessed by client-side scripts
• C. It makes the cookie expire immediately
• D. It makes the cookie visible to the user
Answer: B. It prevents the cookie from being accessed by client-side scripts
34. What does the session_regenerate_id() function do?
• A. Changes the session data
• B. Creates a new session variable
• C. Changes the session ID while preserving the session data
• D. Ends the current session and starts a new one
Answer: C. Changes the session ID while preserving the session data
35. Which of the following is NOT a feature of session management in PHP?
• A. Session data can be stored on the server
• B. Sessions can store complex data like arrays
• C. Sessions work without the user’s browser storing any data
• D. Cookies are used to store session data on the server
Answer: D. Cookies are used to store session data on the server
36. How can you make a cookie available only on a specific path?
• A. By setting the path parameter in setcookie()
• B. By using a session variable
• C. By setting the domain parameter
• D. By setting the expire parameter
Answer: A. By setting the path parameter in setcookie()
37. How do you secure a cookie from being modified by the user?
• A. By setting the HttpOnly flag
• B. By encrypting the cookie value
• C. By setting the secure flag
• D. All of the above
Answer: D. All of the above
38. What happens if session_start() is called after HTML output is sent?
• A. It will generate a warning and fail to start the session
• B. It will ignore the session_start() command
• C. It will create a new session
• D. It will delete the session
Answer: A. It will generate a warning and fail to start the session
39. What does the secure flag do when set for a cookie?
• A. It ensures the cookie is only sent over HTTPS connections
• B. It makes the cookie encrypted
• C. It makes the cookie accessible only to the server
• D. It prevents the cookie from being deleted
Answer: A. It ensures the cookie is only sent over HTTPS connections
40. What is the main difference between $_SESSION and $_COOKIE?
• A. $_SESSION stores data on the client side, $_COOKIE stores data on
the server side
• B. $_SESSION is temporary, $_COOKIE is permanent
• C. $_COOKIE stores data temporarily, $_SESSION stores data
permanently
• D. There is no difference
Answer: B. $_SESSION is temporary, $_COOKIE is permanent
41. How do you prevent a session from timing out?
• A. Use session_set_timeout()
• B. Reset session variables regularly
• C. Increase the session timeout in php.ini
• D. Both B and C
Answer: D. Both B and C
42. Which PHP function sets a secure cookie?
• A. set_secure_cookie()
• B. setcookie() with secure flag
• C. cookie_set()
• D. secure_cookie()
Answer: B. setcookie() with secure flag
43. How can you force PHP to delete a session cookie?
• A. By calling session_unset() and session_destroy()
• B. By setting session.cookie_lifetime to 0
• C. By calling setcookie() with the expiration time in the past
• D. By changing the session ID
Answer: C. By calling setcookie() with the expiration time in the past
44. What is stored in a PHP session by default?
• A. User preferences
• B. Session ID
• C. Variables like $_SESSION
• D. All data sent from the browser
Answer: C. Variables like $_SESSION
45. What does session_destroy() do?
• A. Destroys all session variables
• B. Deletes the session cookie from the browser
• C. Ends the current session
• D. All of the above
Answer: D. All of the above
46. How do you make a session more secure?
• A. Use session_regenerate_id() regularly
• B. Set a session expiration time
• C. Use session.cookie_secure and session.cookie_httponly flags
• D. All of the above
Answer: D. All of the above
47. What is the main advantage of using sessions over cookies?
• A. Sessions are stored on the server, which makes them more secure than
cookies
• B. Cookies are easier to use
• C. Sessions can store more data
• D. There is no advantage
Answer: A. Sessions are stored on the server, which makes them more secure than
cookies
48. Which of the following is true about cookies?
• A. Cookies can be accessed by both client and server
• B. Cookies are stored only on the server
• C. Cookies are not secure for storing sensitive information
• D. Both A and C
Answer: D. Both A and C
49. What happens if you set a session variable after calling session_start()?
• A. It overwrites the previous session data
• B. The new variable is added to the session
• C. The session data is lost
• D. It causes a syntax error
Answer: B. The new variable is added to the session
50. Which of the following is the correct way to check if a cookie is set in
PHP?
• A. isset($_COOKIE["cookie_name"])
• B. isset(cookie_name())
• C. check_cookie("cookie_name")
• D. $_COOKIE["cookie_name"]
Answer: A. isset($_COOKIE["cookie_name"])
5 MARKS
1. What is a session in PHP, and how does it help in maintaining state
across pages?
2. Explain how to start a session in PHP and provide an example of how to
set and retrieve session variables.
3. Describe the process of destroying a session in PHP. What are the
functions involved, and why is it necessary to destroy a session?
4. What are cookies in PHP, and how do they differ from sessions? Discuss
their advantages and disadvantages.
5. Write a PHP script to create a session, set session variables, and retrieve
them on another page.
6. How can you prevent session hijacking in PHP? Discuss methods such as
regenerating session IDs and using secure cookies.
7. What is the purpose of session_unset() and session_destroy()? Explain
with examples.
8. Explain the process of setting a cookie in PHP. What parameters are
required, and what are the default values for some of them?
9. Discuss the HttpOnly and secure flags for cookies. How do they enhance
the security of cookies?
10.Write a PHP script that checks if a session variable is set and displays a
message accordingly.
11.Describe how PHP handles session data storage and retrieval. Where is
the session data stored, and what are the implications for server-side
memory?
12.What is the role of the session_regenerate_id() function in session
management? Provide an example where it could be useful.
13.How can you delete a specific cookie in PHP? Explain the process with
an example.
14.What is the maximum size limit for a cookie in PHP? How can exceeding
this limit affect your application?
15.Describe how sessions and cookies can be used together in PHP for
managing user authentication. Explain the process from logging in to
maintaining the session.
10 MARKS
1. Explain in detail how PHP sessions work from the time they are started to
when they are destroyed. Include the functions involved, how session IDs
are handled, and the role of the session cookie.
2. Discuss the differences between session variables and cookies in PHP.
Include the storage mechanisms, security considerations, and use cases
where one might be preferred over the other.
Create a comprehensive PHP script that:
o Starts a session,
o Sets several session variables,
o Checks if the session variables are set,
o Destroys the session, and
o Displays appropriate messages at each step.**
3. Explain the security risks associated with sessions in PHP. Discuss how
to mitigate risks like session hijacking and session fixation. Include
techniques like regenerating session IDs and using secure, HttpOnly
cookies.
4. Write a PHP script that:
o Sets a cookie with a custom expiration time (e.g., 1 day),
o Checks if the cookie is set,
o Updates the cookie value after 1 hour, and
o Deletes the cookie after 2 hours.**
5. Describe the lifecycle of a session in PHP. How does PHP handle session
storage and retrieval by default? Include information about the session
cookie, session storage path, and session timeout configuration.
6. What are some potential issues with cookies (like size limit, security
concerns) in web development? Explain how to overcome these
challenges by using various cookie flags, like secure, HttpOnly, and
SameSite.
7. In a PHP application, you need to manage user preferences (such as
language and theme). Discuss how you can use both session variables and
cookies to store and retrieve these preferences. Provide code examples to
illustrate the process.
8. Explain how to use PHP sessions for user authentication. Include how to
start a session, store user credentials in session variables, and securely
destroy the session after logout. Discuss the security measures to prevent
session hijacking.
9. Write a detailed explanation of the differences between persistent and
non-persistent cookies in PHP. How would you handle scenarios where
data should be retained beyond a user’s session using persistent cookies,
and how do you set their expiration?