(IWD) - Lab Manual

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

Laboratory Manual

[Computer Engineering, Semester IV]


Enrolment No
Name
Branch Computer Engineering
Academic Term
Institute R. C. Technical Institute, Ahmedabad (640)

Directorate of Technical Education


Gandhinagar - Gujarat
DTE’s Mission:
• To provide globally competitive technical education;
• Remove geographical imbalances and inconsistencies;
• Develop student friendly resources with a special focus on girls’ education and support
to weaker sections;
• Develop programs relevant to industry and create a vibrant pool of technical
professionals.

Institute’s Vision:

Institute’s Mission:

Department’s Vision:

Department’s Mission:
R. C. Technical
Name Institute, Ahmedabad (640)
of institute

Certificate

This is to certify that Mr./Ms ………………………………………………………………….


Enrollment No. ………….…………….…….…….……. of 4th Semester of Diploma in Computer
Engineering of ……………………………………………………………………….
R. C. Technical Institute, Ahmedabad (640) (GTU Code) has satisfactorily
completed the term work in course
Introduction to Web Development (4340704)
…………………………………………………………………………………….……. for the academic year:
…………………… Term: Odd/Even prescribed in the GTU curriculum.

Place:…………………..

Date: …………………..

Signature of Course Faculty Head of the Department


Preface
The primary aim of any laboratory/Practical/field work is enhancement of required skills as
well as creative ability amongst students to solve real time problems by developing relevant
competencies in psychomotor domain. Keeping in view, GTU has designed competency focused
outcome-based curriculum - 2021 (COGC-2021) for Diploma engineering programmes. In this more
time is allotted to practical work than theory. It shows importance of enhancement of skills amongst
students and it pays attention to utilize every second of time allotted for practical amongst Students,
Instructors and Lecturers to achieve relevant outcomes by performing rather than writing practice in
study type. It is essential for effective implementation of competency focused outcome- based Green
curriculum-2021. Every practical has been keenly designed to serve as a tool to develop & enhance
relevant industry needed competency in each and every student. These psychomotor skills are very
difficult to develop through traditional chalk and board content delivery method in the classroom.
Accordingly, this lab manual has been designed to focus on the industry defined relevant outcomes,
rather than old practice of conducting practical to prove concept and theory.

By using this lab manual, students can read procedure one day in advance to actual
performance day of practical experiment which generates interest and also, they can have idea of
judgement of magnitude prior to performance. This in turn enhances predetermined outcomes
amongst students. Each and every Experiment /Practical in this manual begins by competency,
industry relevant skills, course outcomes as well as practical outcomes which serve as a key role for
doing the practical. The students will also have a clear idea of safety and necessary precautions to be
taken while performing experiment.

This manual also provides guidelines to lecturers to facilitate student-centered lab activities
for each practical/experiment by arranging and managing necessary resources in order that the
students follow the procedures with required safety and necessary precautions to achieve outcomes.
It also gives an idea that how students will be assessed by providing Rubrics.

In our day-to-day lives, we use a number of web applications, such as online ticket or hotel
booking, e-commerce, social networks, email, etc. All of these web applications are stored on a remote
server, delivered over the Internet and accessed through a browser interface. PHP is an open-source,
server-side scripting language designed specifically for web applications. PHP is one of the most
popular choices among developers to develop dynamic, interactive, secure and database-driven web
applications. In the growing field of Web technologies, it is essential for diploma-passing students to
learn the PHP language to help them build web applications. The goal of this course is to develop web
development skills in students using the server-side scripting language PHP. Students will learn the
integration of HTML, PHP and MySQL database to develop web applications.

Although we try our level best to design this lab manual, but always there are chances of
improvement. We welcome any suggestions for improvement.
Programme Outcomes (POs):
Following programme outcomes are expected to be achieved through the practical of the course:

1. Basic and Discipline specific knowledge: Apply knowledge of basic mathematics, science and
engineering fundamentals and engineering specialization to solve the engineering problems.
2. Problem analysis: Identify and analyse well-defined engineering problems using codified standard
methods.
3. Design/development of solutions: Design solutions for engineering well-defined technical
problems and assist with the design of systems components or processes to meet specified needs.
4. Engineering Tools, Experimentation and Testing: Apply modern engineering tools and
appropriate technique to conduct standard tests and measurements.
5. Engineering practices for society, sustainability and environment: Apply appropriate technology
in context of society, sustainability, environment and ethical practices.
6. Project Management: Use engineering management principles individually, as a team member or
a leader to manage projects and effectively communicate about well-defined engineering
activities.
7. Life-long learning: Ability to analyse individual needs and engage in updating in the context of
technological changes in field of engineering.
Practical Outcome - Course Outcome matrix
Course Outcomes (COs):
a. CO1: Develop PHP scripts using variables, operators and control structures.
b. CO2: Develop PHP scripts using arrays and functions.
c. CO3: Develop PHP scripts by applying object oriented concepts.
d. CO4: Develop web pages using form controls with validation to collect user inputs in PHP.
e. CO5: Develop and host interactive websites using PHP and MySQL database.
Sr.
No Experiment/Practical Outcome CO1 CO2 CO3 CO4 CO5
.
Environment Setup √ - - - -
1 i. Install and configure PHP, Web Server and MySQL
database using XAMPP/WAMP/LAMP/MAMP.
ii. Create a web page that displays “Hello World.”
2 Form Introduction - - - √ -
i. Create a web page that collects user information
using a form and displays it when the user clicks the
submit button.
3 Variables, Operators and Expressions √ - - - -
i. Write a script to implement a simple calculator for
mathematical operations.
ii. A company has following payment scheme for their
staff:
a. Net Salary = Gross Salary – Deduction
b. Gross Salary = Basic pay + DA + HRA + Medical
c. Deduction = Insurance + PF
Where, DA (Dearness Allowance) = 50% of Basic pay
HRA (House Rent Allowance) = 10% of Basic pay
Medical = 4% of Basic pay
Insurance = 7% of Gross salary
PF (Provident Fund) = 5% of Gross salary
Write a script to take the basic salary of an employee
as input and calculate the net payment to any
employee.
4 Decision making statements √ - - - -
i. Write a script that reads the name of the car and
displays the name of the company the car belongs to
as per the below table:
Car Company
Safari, Nexon, Tigor, Tiago Tata
XUV700, XUV300, Bolero Mahindra
i20, Verna, Venue, Creta Hyundai
Swift, Alto, Baleno, Brezza Suzuki
ii. Write a script to read the marks of 4 subjects and
display the result as per the below instructions:
GTU
Mark-Range
GRADE
AA 85 - 100
AB 75 - 84
BB 65 - 74
BC 55 - 64
CC 45 - 54
CD 40 - 44
DD 35 - 39
FF < 35 (FAIL)
a. Each of the four subjects is worth 100 marks.
b. If a student gets less than 35 marks in any subject,
then he/she will be marked as FAIL, otherwise he/she
will be marked as PASS.
The result contains the grade of each individual subject
in tabular format as per the above table.
Loops
iii. Write a script to display Fibonacci numbers up to a
given term.
iv. Write a script to display a multiplication table for
the given number.
Arrays - √ - - -
5
i. Write a script to calculate the length of a string and
count the number of words in the given string without
using string functions.
ii. Write a script to sort a given indexed array.
iii. Write a script to perform 3 x 3 matrix
Multiplication.
iv. Write a script to encode a given message into
equivalent Morse code.
6 Functions - √ - - -
i. Consider a currency system in which there are
notes of 7 denominations, namely Rs. 1, Rs. 2, Rs. 5, Rs.
10, Rs. 20, Rs. 50 and Rs. 100. Write a function that
computes the smallest number of notes that will
combine for a given amount of money.
ii. Write scripts using string functions:
a. to check if the given string is lowercase or not.
b. to reverse the given string.
c. to remove white spaces from the given string.
d. to replace the given word from the given string.
iii. Write scripts using math functions:
a. to generate a random number between the given
range.
b. to display the binary, octal and hexadecimal of a
given decimal number.
c. to display the sin, cos and tan of the given angle.
iv. Write a script to display the current date and time
in different formats.
7 OOP Concepts - - √ - -
i. Write a script to:
a. Define a class with constructor and destructor.
b. Create an object of a class and access its public
properties and methods.
ii. Write a script that uses the set attribute and get
attribute methods to access a class’s private attributes
of a class.
iii. Write a script to demonstrate single inheritance.
iv. Write a script to demonstrate multiple inheritance.
v. Write a script to demonstrate multilevel
inheritance.
vi. Write a script to demonstrate method overriding.
vii. Write a script to demonstrate method overloading
based on the number of arguments.
viii. Write a script to demonstrate a simple interface.
ix. Write a script to demonstrate a simple abstract
class.
x. Write a script to demonstrate cloning of objects.
8 Forms - - - √ -
i. Create a web page using a form to collect employee
information.
ii. Extend practical - 8(i) to validate user information
using regular expressions.
iii. Create two distinct web pages to demonstrate
information passing between them using URL - Get
method.
iv. Create two different web pages to demonstrate
information passing between web pages using Hidden
variables – Post method.
9 Session, Cookies - - √ -
-
i. Create web pages to demonstrate passing
information using Session.
ii. Write a script to demonstrate storing and retrieving
information from cookies.
10 Database - - - - √
i. Create a web page that reads employee
information using a form and stores it in the database.
ii. Create a web page for employee log-in.
iii. Write a script to upload an image to the server.
iv. After an employee logs in, create a Home web page
that displays basic employee information.
v. Create a web page to delete employee profiles
from the database.
vi. Create a web page that allows employees to
change their password.
11 Email, PDF, JSON - - - - √
i. Write a script to generate a salary slip for an
employee in PDF format.
ii. Write a script to send an email.
iii. Write a script to convert an associative array into
JSON string format and vice versa.
Simple Web Application √ √ √ √ √
12 Create a simple web application for Employee
Management with 3-4 web pages and host it using
cPanel and Filezilla.
Industry Relevant Skills
The following industry relevant skills of the competency “Develop Interactive Web application
using PHP and MySQL” are expected to be developed in the student by undertaking the
practical of this laboratory manual.
1. Install and configure software as per requirements.
2. Write code for the given problem.
3. Debug program to fix errors.
4. Follow Coding Guidelines.

Guidelines to Teachers
1. Couse faculty should demonstrate experiment with all necessary implementation
strategies described in curriculum.
2. Couse faculty should explain industrial relevance before starting of each experiment.
3. Course faculty should involve & give opportunity to all students for hands on experience.
4. Course faculty should ensure mentioned skills are developed in the students by asking.
5. Utilise 2 hrs of lab hours effectively and ensure completion of write up with quiz also.
6. Encourage peer to peer learning by doing same experiment through fast learners.

Instructions for Students


1. Organize the work in the group and make record of all observations.
2. Students shall develop maintenance skill as expected by industries.
3. Student shall attempt to develop related hand-on skills and build confidence.
4. Student shall develop the habits of evolving more ideas, innovations, skills etc.
5. Student shall refer technical magazines and data books.
6. Student should develop habit to submit the practical on date and time.
7. Student should well prepare while submitting write-up of exercise.
Continuous Assessment Sheet

Enrolment No: Name:


Term:
Sr. Date Marks
Experiment/Practical Outcome Page Sign
No Perform (10)
Environment Setup
1 i. Install and configure PHP, Web Server and
MySQL database using XAMPP/WAMP/LAMP/
MAMP.
ii. Create a web page that displays “Hello
World.”
2 Form Introduction
i. Create a web page that collects user
information using a form and displays it when the
user clicks the submit button.
3 Variables, Operators and Expressions
i. Write a script to implement a simple
calculator for mathematical operations.
ii. A company has following payment scheme
for their staff:
a. Net Salary = Gross Salary – Deduction
b. Gross Salary = Basic pay + DA + HRA +
Medical
c. Deduction = Insurance + PF
Where, DA (Dearness Allowance) = 50% of Basic
pay
HRA (House Rent Allowance) = 10% of Basic pay
Medical = 4% of Basic pay
Insurance = 7% of Gross salary
PF (Provident Fund) = 5% of Gross salary
Write a script to take the basic salary of an
employee as input and calculate the net payment
to any employee.
4 Decision making statements
i. Write a script that reads the name of the car
and displays the name of the company the car
belongs to as per the below table:
Car Company
Safari, Nexon, Tigor, Tiago Tata
XUV700, XUV300, Bolero Mahindra
i20, Verna, Venue, Creta Hyundai
Swift, Alto, Baleno, Brezza Suzuki
ii. Write a script to read the marks of 4 subjects
and display the result as per the below
instructions:
GTU
Mark-Range
GRADE
AA 85 - 100
AB 75 - 84
BB 65 - 74
BC 55 - 64
CC 45 - 54
CD 40 - 44
DD 35 - 39
FF < 35 (FAIL)
a. Each of the four subjects is worth 100 marks.
b. If a student gets less than 35 marks in any
subject, then he/she will be marked as FAIL,
otherwise he/she will be marked as PASS.
The result contains the grade of each individual
subject in tabular format as per the above table.
Loops
iii. Write a script to display Fibonacci numbers
up to a given term.
iv. Write a script to display a multiplication table
for the given number.
Arrays
5
i. Write a script to calculate the length of a
string and count the number of words in the
given string without using string functions.
ii. Write a script to sort a given indexed array.
iii. Write a script to perform 3 x 3 matrix
Multiplication.
iv. Write a script to encode a given message into
equivalent Morse code.
6 Functions
i. Consider a currency system in which there
are notes of 7 denominations, namely Rs. 1, Rs.
2, Rs. 5, Rs. 10, Rs. 20, Rs. 50 and Rs. 100. Write a
function that computes the smallest number of
notes that will combine for a given amount of
money.
ii. Write scripts using string functions:
a. to check if the given string is lowercase or
not.
b. to reverse the given string.
c. to remove white spaces from the given
string.
d. to replace the given word from the given
string.
iii. Write scripts using math functions:
a. to generate a random number between the
given range.
b. to display the binary, octal and
hexadecimal of a given decimal number.
c. to display the sin, cos and tan of the given
angle.
iv. Write a script to display the current date and
time in different formats.
7 OOP Concepts
i. Write a script to:
a. Define a class with constructor and
destructor.
b. Create an object of a class and access its
public properties and methods.
ii. Write a script that uses the set attribute and
get attribute methods to access a class’s private
attributes of a class.
iii. Write a script to demonstrate single
inheritance.
iv. Write a script to demonstrate multiple
inheritance.
v. Write a script to demonstrate multilevel
inheritance.
vi. Write a script to demonstrate method
overriding.
vii. Write a script to demonstrate method
overloading based on the number of arguments.
viii. Write a script to demonstrate a simple
interface.
ix. Write a script to demonstrate a simple
abstract class.
x. Write a script to demonstrate cloning of
objects.
8 Forms
i. Create a web page using a form to collect
employee information.
ii. Extend practical - 8(i) to validate user
information using regular expressions.
iii. Create two distinct web pages to
demonstrate information passing between them
using URL - Get method.
iv. Create two different web pages to
demonstrate information passing between web
pages using Hidden variables – Post method.
9 Session, Cookies
i. Create web pages to demonstrate passing
information using Session.
ii. Write a script to demonstrate storing and
retrieving information from cookies.
Database
10
i. Create a web page that reads employee
information using a form and stores it in the
database.
ii. Create a web page for employee log-in.
iii. Write a script to upload an image to the
server.
iv. After an employee logs in, create a Home web
page that displays basic employee information.
v. Create a web page to delete employee
profiles from the database.
vi. Create a web page that allows employees to
change their password.
11 Email, PDF, JSON
i. Write a script to generate a salary slip for an
employee in PDF format.
ii. Write a script to send an email.
iii. Write a script to convert an associative array
into JSON string format and vice versa.
Simple Web Application
12 Create a simple web application for Employee
Management with 3-4 web pages and host it
using cPanel and Filezilla.
Introduction to Web Development (4340704)

Date: _____________

Practical No. 1: Environment Setup.


Install and configure PHP, Web Server and MySQL database using
XAMPP/WAMP/LAMP/MAMP.
Create a web page that displays “Hello World.”

Objectives:
A development environment is required to write, compile, run, and debug any
application. This practical will help student to set up PHP environment for executing
PHP program using different server like XAMPP or WAMP server.

Relevant Program Outcomes (POs):


Basic and Discipline specific knowledge (PO1): Apply knowledge of basic
mathematics, science and engineering fundamentals and engineering
specialization to solve the Computer Engineering problems.
Engineering Tools, Experimentation and Testing (PO4): Apply modern Computer
Engineering tools and appropriate technique to conduct standard tests and
measurements.
Engineering practices for society, sustainability and environment (PO5): Apply
appropriate technology in context of society, sustainability, environment and
ethical practices.

Competency and Practical Skills:


This practical is expected to develop the following skills for the industry-identified
competency ‘Develop Interactive Web application using PHP and MySQL’:
Installing and configuring softwares as per the requirements.
Programming skills.
Debugging skills.

Relevant Course Outcomes (COs):


Develop PHP scripts using variables, operators and control structures.

Practical Outcomes:
Install and configure web application development environment for PHP and
MySQL.

Relevant Affective domain Outcomes (ADOs):


Maintain tools and equipments.
Follow Coding standards and practices.
Follow ethical practices

1|Page
Introduction to Web Development (4340704)

Prerequisite Theory:
XAMPP is one of the most popular software pack to set up web application development
environment for PHP with all required software components. XAMPP is an Open Source
AMP stack which stands for Cross platform, Apache, MariaDB, PHP and Perl. Apache is
cross platform web server, MariaDB is the most widely used database developed by
MySQL, PHP is a backend scripting language and Perl is a programming used for web
development. X denotes Cross-platform, which means that it can work on different
platforms such as Windows, Linux, and macOS.
XAMPP allows a local host or server to test its website and clients on computers and
laptops before releasing them to the main server. It provides a suitable environment for
testing and verifying the functioning working of projects based on Apache, Perl, MySQL
database, and PHP on the host's system. It also includes administrative tools such as
phpMyAdmin, Filezilla FTP Server, Mercury mail server and JSP Tomcat server.

Resources Required:
Sr.
Instrument /Components Configuration/Specification
No
Processor:
1. Computer System RAM:
Operating System:

2. XAMPP server XAMPP Version:

3. Text Editor Editor:

4. Web Browser Browser:


5. Internet Connection -

Procedure:
Below steps describes installation of XAMPP on Windows operating system. Steps are
similar for Linux and Mac operating systems.
i. Install XAMPP
Open the XAMPP website. Go to https://www.apachefriends.org/index.html in
your computer's web browser.

2|Page
Introduction to Web Development (4340704)

Download latest XAMPP for Windows operating system.


Once the XAMPP setup has been downloaded, you can start the installation by
double clicking on the .exe file.
An active antivirus program can interfere with the installation process, so it is best
to temporarily disable any antivirus software until all XAMPP components have
been successfully installed.

Because User Account Control (UAC) restricts writing access to the C: drive and can
interfere with the XAMPP installation, it is recommended that this be disabled for
the duration of the installation.

After that the start screen of the XAMPP setup wizard should appear automatically.
Click on ‘Next’ to configure the installation settings.

3|Page
Introduction to Web Development (4340704)

Under ‘Select Components’, you have the option to exclude individual components
of the XAMPP software bundle from the installation. But for a full local test server,
we recommend you install using the standard setup and all available components.
After making your choice, click ‘Next’.

In this next step, you have the chance to choose where you’d like the XAMPP
software packet to be installed. If you opt for the standard setup, then a folder with
the name xampp will be created under C:\ for you. After you’ve chosen a location,
click ‘Next’.

4|Page
Introduction to Web Development (4340704)

Select the language in the next dialog box.

On Ready to Install screen click on “Next”.

5|Page
Introduction to Web Development (4340704)

Once all the preferences have been decided, click to start the installation. The setup
wizard will unpack and install the selected components and save them to the
designated directory. This process may take few minutes.

Your Firewall may interrupt the installation process to block the some components
of the XAMPP. Use the corresponding check box to enable communication between
the Apache server and your private network or work network. Remember that
making your XAMPP server available for public networks isn’t recommended.
Once all the components are unpacked and installed, you can close the setup
wizard by clicking on ‘Finish’. Click to tick the corresponding check box and open
the XAMPP Control Panel once the installation process is finished.

XAMPP Control Panel provides controls for the individual components of your
xampp test server. The control panel user interface allows you to start or stop
individual modules: Apache, MySQL, FileZilla, Mercury and Tomcat. The XAMPP
Control Panel also offers you various other buttons, including:
Config: allows you to configure the XAMPP as well as the individual components

6|Page
Introduction to Web Development (4340704)

Netstat: shows all running processes on the local computer


Shell: opens a UNIX shell
Explorer: opens the XAMPP folder in Windows Explorer
Services: shows all services currently running in the background
Help: offers links to user forums
Quit: closes the XAMPP Control Panel

Individual modules can be started or stopped on the XAMPP Control Panel through
the corresponding buttons under ‘Actions’. You can see which modules have been
started because their names are highlighted green under the ‘Module’ title.

If a module can’t be started as a result of an error, you’ll be informed of this straight


away in red font. A detailed error report can help you identify the cause of the issue.
You have an ‘Admin’ option located on the Control Panel for every module in your
XAMPP.
Click on the Admin button of your Apache server to go to the web address of your
web server. The Control Panel will now start in your standard browser, and you’ll
be led to the dashboard of your XAMPP’s local host. The dashboard features

7|Page
Introduction to Web Development (4340704)

numerous links to websites for useful information as well as the open source
project BitNami, which offers you many different applications for your XAMPP, like
WordPress or other content management systems. Alternatively, you can reach the
dashboard through localhost/dashboard/.

You can use the Admin button of your database module to open phpMyAdmin.
Here, you can manage the databases of your web projects that you’re testing on
your XAMPP. Alternatively, you can reach the administration section of your MySQL
database via localhost/phpmyadmin/

ii. Testing XAMPP installation


To check whether your test server is installed and configured correctly, you have the
option to create a PHP test page, store them on your XAMPP’s local host, and retrieve
them via the web browser.
Open the XAMPP directory through the ‘Explorer’ button in the Control Panel and
choose the folder htdocs (C:\xampp\htdocs for standard installations). This
directory should store all the web pages that you want to test on your XAMPP
server. The htdocs folder should already contain data to help configuration of the
web server. But you should store your own projects in a new folder (for example
‘test’ folder).

8|Page
Introduction to Web Development (4340704)

You can create a new PHP file with below code in your editor and storing it as
test.php in your ‘test’ folder (C:\xampp\htdocs\test):

Now open a web browser and load your PHP page via localhost/test/test.php. If
your browser window displays the words ‘Hello World’, then you’ve successfully
installed and configured your XAMPP.

Output:
Snapshot of XAMPP Control Panel after installation.
Output:

9|Page
Introduction to Web Development (4340704)

Snapshot of “Hello World” script code.

Output:

Snapshot of output of “Hello World” script in web browser.


Output:

10 | P a g e
Introduction to Web Development (4340704)

Practical related Quiz:


What does XAMPP stand for?
A) Xpandable Apache MySQL PHP Perl
B) XML Apache MySQL PHP Perl
C) XAMPP doesn't stand for anything
D) Cross-platform Apache MySQL PHP Perl
Which operating systems is XAMPP compatible with?
A) Only Windows
B) Only Linux
C) Both Windows and Linux
D) None of the above
Which port number is used by default for the Apache web server in XAMPP?
A) Port 80
B) Port 443
C) Port 8080
D) Port 8888
Which directory in XAMPP contains the files for the Apache web server?
A) /htdocs
B) /bin
C) /mysql
D) /apache
Which of the following is not included in XAMPP by default?
A) PHP
B) Perl
C) PostgreSQL
D) MySQL
Which of the following is the recommended way to start and stop XAMPP on
Windows?
A) Use the XAMPP Control Panel
B) Use the Command Prompt
C) Start and stop each component separately
D) Use the Windows Task Manager
Which configuration file should you edit to change the PHP settings in XAMPP?
A) php.ini

11 | P a g e
Introduction to Web Development (4340704)

B) httpd.conf
C) my.ini
D) config.inc.php
Which port number is used by default for the MySQL database in XAMPP?
A) Port 80
B) Port 443
C) Port 3306
D) Port 8080
Which of the following is not a security risk associated with using XAMPP?
A) Leaving the default username and password for the MySQL database unchanged
B) Running XAMPP on a publicly accessible network
C) Disabling the firewall on your computer
D) Using weak or easily guessable passwords for XAMPP components
Which of the following is a tool included in XAMPP that allows you to administer
MySQL databases?
A) phpMyAdmin
B) Apache Tomcat
C) Microsoft SQL Server Management Studio
D) Oracle SQL Developer
Which of the following XAMPP components allows you to run PHP scripts?
A) Apache HTTP Server
B) MySQL
C) Perl
D) Node.js

References:
https://www.apachefriends.org
https://phpandmysql.com/extras/installing-xampp
https://www.youtube.com/watch?v=at19OmH2Bg4
https://www.youtube.com/watch?v=PaDgry5QAt4
https://www.w3schools.com/php

12 | P a g e
Introduction to Web Development (4340704)

Assessment Rubrics:
% of
Criteria Rubrics Marks
point
Excellent (10-8 marks): Completed programs/scripts
correctly as per the requirements.
C1: Adequate (7-6 marks): Completed programs/scripts
Program correctly with approx. 70% requirements.
50 %
Completeness/ Poor (5-4 marks): Completed programs/scripts correctly
Correctness with 70% - 50% requirements.
Unsatisfactory (0-3 marks): Completed programs/ scripts
correctly with less than 50% requirements.
Excellent (10-8 marks): The code is clean, well-organized and
very easy to understand.
Adequate (7-6 marks): The code is fairly easy to read and
C2: understand.
25 %
Readability Poor (5-4 marks): The code is readable only by someone who
knows what it is supposed to be doing.
Unsatisfactory (0-3 marks): The code is poorly organized and
very difficult to understand.
Excellent (10-8 marks):
• Coding standards are followed in complete code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• The Complete code is well-documented with comments
explaining the code.
Adequate (7-6 marks):
• Coding standards are followed in most of the code while
naming variables/functions/ classes, explaining the
C3:
purpose of variables/ functions/classes.
Coding
25 % • Most of the code is documented with comments
Standards/ explaining the code.
Documentation
Poor (5-4 marks):
• Coding standards are followed in very little code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• Very little code is documented with comments
explaining the code.
Unsatisfactory (0-3 marks):
• Coding standards are not followed properly.
• Proper comments are not written explaining the code.
Total Marks for Practical = 0.5 * (Marks of C1) + 0.25 * (Marks of C2) + 0.25 * (Marks of C3)

Signature with Date:

13 | P a g e
Introduction to Web Development (4340704)

Date: _____________

Practical No. 2: Form Introduction.


Create a web page that collects user information using a form and displays it when
the user clicks the submit button.

Objectives:
Forms are important component of the web application that allows it to collect
information from the users. Most websites use different forms for various tasks such as
log in, registration, contact us, and application specific information collection. Now a
days you rarely see any website without a form. This practical will help students to
design a form to collect user data using PHP.

Relevant Program Outcomes (POs):


Basic and Discipline specific knowledge (PO1): Apply knowledge of basic
mathematics, science and engineering fundamentals and engineering
specialization to solve the Computer Engineering problems.
Problem analysis (PO2): Identify and analyse well-defined Computer Engineering
problems using codified standard methods.
Design/development of solutions (PO3): Design solutions for Computer
Engineering well-defined technical problems and assist with the design of systems
components or processes to meet specified needs.
Engineering Tools, Experimentation and Testing (PO4): Apply modern Computer
Engineering tools and appropriate technique to conduct standard tests and
measurements.

Competency and Practical Skills:


This practical is expected to develop the following skills for the industry-identified
competency ‘Develop Interactive Web application using PHP and MySQL’:
Programming skills.
Debugging skills.

Relevant Course Outcomes (COs):


Develop web pages using form controls with validation to collect user inputs in PHP.

Practical Outcomes:
Develop web pages using Form controls such as text box, button, check box, radio
button, text area etc.

Relevant Affective domain Outcomes (ADOs):


Maintain tools and equipments.
Follow Coding standards and practices.

14 | P a g e
Introduction to Web Development (4340704)

Follow ethical practices

Prerequisite Theory:
Web forms are one of the most common ways for a user to interact with a
web application. Forms allow users to enter data, which is typically sent to a web server
for processing and storage or used on the client-side to update the interface in some
way immediately.
The HTML of a web form is made up of one or more form controls (also known as
widgets) and some additional elements to help structure the overall form - these are
commonly referred to as HTML forms. Most common controls are single or multi-line
text boxes, dropdown boxes, buttons, checkboxes and radio buttons. There are some
other elements such as date, time, day color, file etc. Form controls can also be
programmed to enforce specific formats or values to be entered (form validation).
Define HTML Form:
The HTML <form> element is used to create an HTML form for user input:

<form>
...
form elements
...
</form>

Define HTML Form Element:


HTML form elements are mostly created using the <input> element.

<form action="/action.php" method="get">


<label for="uname">User Name:</label><br>
<input type="text" id="uname" name="uname"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password">
<input type="submit" value="Submit">
</form>

• The <label> tag defines a label for many form elements. The <label> element is
useful for screen-reader users, because the screen-reader will read out loud the
label when the user focus on the input element.
• The <input type="submit"> defines a button for submitting the form data to a
form-handler. The form-handler is typically a file on the server with a script for
processing input data.
• The action attribute defines the action to be performed when the form is
submitted. Usually, the form data is sent to a file on the server when the user clicks
on the submit button.
• The method attribute specifies the HTTP method to be used when submitting the
form data. The form-data can be sent as URL variables (with method="get") or as
HTTP post transaction (with method="post").

15 | P a g e
Introduction to Web Development (4340704)

• The HTML id attribute is used to specify a unique id for an HTML element. You
cannot have more than one element with the same id in an HTML document.
• Each input field must have a name attribute to be submitted. If the name attribute
is omitted, the value of the input field will not be sent at all. It is used by PHP script
to read form data from that input element.
• The type attribute defines type of input element. By default value of the type
attribute is "text". Different types of input elements are as follow:

Element Type Description


<input type="text"> Displays a single-line text input field.
<input type="radio"> Displays a radio button (for selecting one of many
choices)
<input type="checkbox"> Displays a checkbox (for selecting choices)
<input type="submit"> Displays a submit button (for submitting the form)
<input type="button"> Displays a clickable button
<input type="reset"> Displays a reset button (for resetting the form)
<input type="search"> Displays a text input field for search field.
<input type="password"> Displays a text input field for password.
<input type="number"> Displays a text input field for numbers.
<input type="tel"> Displays a text input field for telephone.
<input type="url"> Displays a text input field for URL.
<input type="email"> Displays a text input field for email.
<input type="range"> Displays a range slider.
<input type="file"> Displays a file-select field and a "Browse" button for
file uploads
<input type="color"> Displays an input field for color picker.
<input type="datetime- Displays a date and time input field, with no time zone
local">
<input type="date"> Displays an input fields for date
<input type="time"> Displays an input fields for time.
<input type="month"> Displays an input fields for month.
<input type="week"> Displays an input fields for week.
<textarea> … <textarea> Displays a multi-line plain-text input field.

TextBox:
The <input type="text"> provides a single-line input field to input text.

16 | P a g e
Introduction to Web Development (4340704)

<form action="/action.php" method="get">


<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
<input type="submit" value="Submit">
</form>

Radio Button:
Radio Button allows user to select only one choice from a limited number of choices.

<form action="/action.php" method="get">


<input type="radio" id="male" name="gender"value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender"
value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
<input type="submit" value="Submit">
</form>

Check Box:
Check Box allows a user to select zero or more choices from a limited number of choices.

<form action="/action.php" method="get">


<input type="checkbox" id="fruit1" name="friut1"
value="Mango">
<label for=" fruit1">Mango</label><br>

<input type="checkbox" id="fruit2" name="friut2"


value="Banana">
<label for=" fruit2">Banana</label><br>

<input type="checkbox" id="fruit3" name="friut3"


value="Grapes">
<label for=" fruit3">Grapes </label><br>
<input type="submit" value="Submit">
</form>

Resources Required:

17 | P a g e
Introduction to Web Development (4340704)

Sr.
Instrument /Components Configuration/Specification
No
Processor:
1. Computer System RAM:
Operating System:

2. XAMPP server XAMPP Version:

3. Text Editor Editor:

4. Web Browser Browser:

Source code and Output:


Create a web page that collects user information using a form and displays it when the
user clicks the submit button.
Source Code:

18 | P a g e
Introduction to Web Development (4340704)

Output:

Practical related Quiz:

19 | P a g e
Introduction to Web Development (4340704)

Which attribute is used to associate a label with an input element?


A) for
B) id
C) name
D) class
What is the purpose of the "required" attribute in HTML 5 form elements?
A) To make sure the input field is not empty.
B) To validate the input based on a specified pattern.
C) To limit the number of characters that can be entered.
D) None of the above.
Which input type in HTML 5 is used for selecting a date?
A) date
B) datetime
C) time
D) month
Which attribute is used to specify the action to be performed when a form is
submitted?
A) action
B) method
D) target
D) submit
Which attribute is used to group related radio buttons together?
A) name
B) id
C) class
D) for
Which input type in HTML 5 is used for selecting a file?
A) file
B) image
C) url
D) password
Which attribute is used to set a default value in an input element?
a) value
b) default

20 | P a g e
Introduction to Web Development (4340704)

c) initial
d) none of the above
Which attribute is used to specify the maximum number of characters allowed in
an input element?
A) maxlength
B) maxchar
C) length
D) limit
Which attribute is used to specify a pattern for input validation?
A) pattern
B) validate
C) input-pattern
D) regex
Which attribute is used to specify whether an input field should be disabled?
A) disabled
B) enable
C) active
D) none of the above
Which input type in HTML 5 is used for creating a dropdown list?
a) select
b) dropdown
c) menu
d) list

References:
https://www.w3schools.com/html/html_forms.asp
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form
https://www.quackit.com/html/codes/html_form_code.cfm
https://www.javatpoint.com/html-form
https://www.geeksforgeeks.org/html-forms
https://www.tutorialspoint.com/html/html_forms.htm

21 | P a g e
Introduction to Web Development (4340704)

Assessment Rubrics:
% of
Criteria Rubrics Marks
point
Excellent (10-8 marks): Completed programs/scripts
correctly as per the requirements.
C1: Adequate (7-6 marks): Completed programs/scripts
Program correctly with approx. 70% requirements.
50 %
Completeness/ Poor (5-4 marks): Completed programs/scripts correctly
Correctness with 70% - 50% requirements.
Unsatisfactory (0-3 marks): Completed programs/ scripts
correctly with less than 50% requirements.
Excellent (10-8 marks): The code is clean, well-organized and
very easy to understand.
Adequate (7-6 marks): The code is fairly easy to read and
C2: understand.
25 %
Readability Poor (5-4 marks): The code is readable only by someone who
knows what it is supposed to be doing.
Unsatisfactory (0-3 marks): The code is poorly organized and
very difficult to understand.
Excellent (10-8 marks):
• Coding standards are followed in complete code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• The Complete code is well-documented with comments
explaining the code.
Adequate (7-6 marks):
• Coding standards are followed in most of the code while
naming variables/functions/ classes, explaining the
C3:
purpose of variables/ functions/classes.
Coding
25 % • Most of the code is documented with comments
Standards/ explaining the code.
Documentation
Poor (5-4 marks):
• Coding standards are followed in very little code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• Very little code is documented with comments
explaining the code.
Unsatisfactory (0-3 marks):
• Coding standards are not followed properly.
• Proper comments are not written explaining the code.
Total Marks for Practical = 0.5 * (Marks of C1) + 0.25 * (Marks of C2) + 0.25 * (Marks of C3)

Signature with Date:

22 | P a g e
Introduction to Web Development (4340704)

Practical No. 3: Variables, Operators and Expression


Write a script to implement a simple calculator for mathematical operations.
A company has following payment scheme for their staff:
• Net Salary = Gross Salary – Deduction
• Gross Salary = Basic pay + DA + HRA + Medical
• Deduction = Insurance + PF
where, DA (Dearness Allowance) = 50% of Basic pay
HRA (House Rent Allowance) = 10% of Basic pay
Medical = 4% of Basic pay
Insurance = 7% of Gross salary
PF (Provident Fund) = 5% of Gross salary
Write a script to take the basic salary of an employee as input and calculate the
net payment to any employee.

Objectives:
Variables, Operators and Expressions are core part of any programming language.
• Variables are used to store data.
• Operators are used to perform various types of operations on data.
• Anything that you write in PHP script is an expression.
This practical will allow students to practise writing PHP scripts that use variables,
operators, and expressions to solve simple problems.

Relevant Program Outcomes (POs):


Basic and Discipline specific knowledge (PO1): Apply knowledge of basic
mathematics, science and engineering fundamentals and engineering
specialization to solve the Computer Engineering problems.
Problem analysis (PO2): Identify and analyse well-defined Computer Engineering
problems using codified standard methods.
Design/development of solutions (PO3): Design solutions for Computer
Engineering well-defined technical problems and assist with the design of systems
components or processes to meet specified needs.
Engineering Tools, Experimentation and Testing (PO4): Apply modern Computer
Engineering tools and appropriate technique to conduct standard tests and
measurements.

Competency and Practical Skills:


This practical is expected to develop the following skills for the industry-identified
competency ‘Develop Interactive Web application using PHP and MySQL’:

23 | P a g e
Introduction to Web Development (4340704)

Programming skills.
Debugging skills.

Relevant Course Outcomes (COs):


Develop PHP scripts using variables, operators and control structures.

Practical Outcomes:
Use PHP variables to store data in PHP scripts.
Perform operation on data using operator in PHP scripts.

Relevant Affective domain Outcomes (ADOs):


Maintain tools and equipments.
Follow Coding standards and practices.
Follow ethical practices.

Prerequisite Theory:
Variables:
A variable is a named area of storage, where you can store a value.
• In PHP, variables are represented by a dollar sign ($) followed by the name of
the variable.
• Variable names are case-sensitive. For example, $var and $Var are two
different variables.
• A valid variable name starts with a letter or underscore, followed by any number
of letters, numbers, or underscores.
• A PHP variable name cannot contain spaces.
• For example, $enrollmentno, $subject_name, $_itemid are valid
variable names and $12var, $student name, part_id are invalid variable
names.
• PHP is loosely-typed language, so it doesn’t need to specify data type of
variables. It automatically analyse assigned value and defined data type of
variable.
• Assignment Operator (=) is used to assign the value to a variable. For example,
$subject_name = “Introduction to Web Development”;
PHP has total eight different data types which can be used to define variables:
• Integers − whole numbers, without a decimal point. E.g. – 415, 8341.
• Doubles − floating-point numbers. E.g. – 12.5, 3.14.
• Booleans − two possible values either TRUE or FALSE.
• NULL − special type that only has one value: NULL.

24 | P a g e
Introduction to Web Development (4340704)

• Strings − sequences of characters. E.g. - 'Introduction to Web Development'.


• Arrays − named and indexed collections of other values.
• Objects − instances of programmer-defined classes
• Resources − special variables that hold references to resources external to PHP.
(such as database connections).
Operators:
Operator is a symbol used to perform operations on operands (variables or values). For
example:
$a = $b + 10;
Above code uses arithmetic operator (+) to add 10 to variable $b and assign it to
variable $a.
PHP operators can be categorized into following types:
Arithmetic Operators:
Operator Name Example Description
+ Addition $a + $b Sum of two operands
- Subtraction $a - $b Difference of two operands
* Multiplication $a * $b Multiply tow operands
/ Division $a / $b Quotient of operands
% Modulo $a % $b Reminder of operands
++ Increment $a++ Same as $a = $a + 1
-- Decrement $a-- Same as $a = $a - 1

Assignment Operators:
Operator Name Example Description
$a = $b Value of right operand is assigned
= Assign
to left operand
+= Add then assign $a += $b Same as $a = $a + $b
-= Subtract then assign $a -= $b Same as $a = $a - $b
*= Multiply then assign $a *= $b Same as $a = $a * $b
Divide then assign $a /= $b
/= Same as $a = $a / $b
(Quotient)
Divide then assign $a %= $b
%= Same as $a = $a % $b
(Reminder)

25 | P a g e
Introduction to Web Development (4340704)

Bitwise Operators:
Operator Name Example Description
$a & $b Bitwise AND operation between $a
& Bitwise AND
and $b
$a | $b Bitwise OR operation between $a
| Bitwise OR
and $b
$a ^ $b Bitwise XOR operation between $a
^ Bitwise XOR
and $b
~ Bitwise NOT ~ $a Bitwise NOT operation on $a
<< Left shift $a << $b Left shift bits of $a by $b steps
>> Right shift $a >> $b Right shift bits of $a by $b steps

Comparison Operators:
Operator Name Example Description
== Equal $a == $b Returns TRUE if $a is equal to $b
$a != $b Returns TRUE if $a is not equal to
!= Not equal
$b
$a <> $b Returns TRUE if $a is not equal to
<> Not equal
$b
$a === $b Returns TRUE if $a and $b are
=== Identical
equal and of same data type
$a !== $b Returns TRUE if $a and $b are not
!== Not identical
equal or of different data type
< Less than $a < $b Returns TRUE if $a is less than $b
$a > $b Returns TRUE if $a is greater than
> Greater than
$b
Less than or equal $a <= $b Returns TRUE if $a is less than or
<=
to equal to $b
Greater than or $a >= $b Returns TRUE if $a is greater than
>=
equal to or equal to $b
$a <=> $b Return -1 if $a is less than $b
<=> Spaceship Return 0 if $a is equal $b
Return 1 if $a is greater than $b

26 | P a g e
Introduction to Web Development (4340704)

Logical Operators:
Operator Name Example Description
$a and $b Returns TRUE if both $a and $b are
and Logical AND
true
$a or $b Returns TRUE if either $a or $b is
or Logical OR
true
$a xor $b Returns TRUE if either $a or $b is
xor Logical XOR
true, but not both are TRUE
! Logical NOT ! $a Returns TRUE if $a is FALSE
$a && $b Returns TRUE if both $a and $b are
&& Logical AND
true
$a || $b Returns TRUE if either $a or $b is
|| Logical OR
true

String Operators:
Operator Name Example Description
. Concatenation $a . $b Concatenate both $a and $b
Concatenation and $a .= $b
.= Same as $a = $a . $b
assign

Expressions
In PHP, anything that has a value is an expression, so most of the statements you write
in PHP scrips are expression. For Example:

$a = $b; // $b is an expression
$a = $b * $c; // $b * $c is an expression
$a = sum($b, $c); // sum($b, $c) is an expression
$b++; // $b++ is an expression

Resources Required:
Sr.
Instrument /Components Configuration/Specification
No
Processor:
1. Computer System RAM:
Operating System:

2. XAMPP server XAMPP Version:

3. Text Editor Editor:

4. Web Browser Browser:

27 | P a g e
Introduction to Web Development (4340704)

Source code and Output:


Write a script to implement a simple calculator for mathematical operations.
Source Code:

28 | P a g e
Introduction to Web Development (4340704)

Output:

A company has following payment scheme for their staff:


• Net Salary = Gross Salary – Deduction
• Gross Salary = Basic pay + DA + HRA + Medical
• Deduction = Insurance + PF
where, DA (Dearness Allowance) = 50% of Basic pay
HRA (House Rent Allowance) = 10% of Basic pay
Medical = 4% of Basic pay
Insurance = 7% of Gross salary
PF (Provident Fund) = 5% of Gross salary
Write a script to take the basic salary of an employee as input and calculate
the net payment to any employee.

Source Code:

29 | P a g e
Introduction to Web Development (4340704)

Output:

30 | P a g e
Introduction to Web Development (4340704)

Practical related Quiz:


Which of the following is a valid PHP variable name?
A) $my_var
B) 123var
C) $my-var
D) $my var
Which operator is used for exponentiation in PHP?
A) ^
B) **
C) //
D) *
What is the output of the following code snippet?
$a = 10;
$b = 3;
$c = $a % $b;
echo $c;
A) 1
B) 3
C) 0
D) 7
What is the purpose of the var_dump() function in PHP?
A) To print out the data type and value of a variable.
B) To convert a string to lowercase.
C) To check if a variable is set and is not NULL.
D) To remove whitespace from the beginning and end of a string.
What is the purpose of the ++$a operator in PHP?
A) It increments the value of $a and then returns the new value.
B) It returns the value of $a and then increments it.
C) It decrements the value of $a and then returns the new value.
D) It returns the value of $a and then decrements it.
What is the output of the following code snippet?
$a = "Hello";
$b = "World";

31 | P a g e
Introduction to Web Development (4340704)

echo $a . " " . $b;


A) HelloWorld
B) Hello World
C) HelloWorld
D) Error
What is the output of the following code snippet?
$a = 10;
$b = 5;
$a -= $b;
echo $a;
A) 5
B) 10
C) 15
D) Error
What is the output of the following code snippet?
$a = 5;
$b = "5";
if ($a == $b) {
echo "Equal";
}
else {
echo "Not Equal";
}
a. Equal
b. Not Equal
c. Error
d. Depends on the version of PHP used

References:
https://www.php.net/manual/en/language.variables.php
https://www.php.net/manual/en/language.expressions.php
https://www.w3schools.com/php/php_variables.asp
https://www.w3schools.com/php/php_operators.asp
https://www.geeksforgeeks.org/php-variables

32 | P a g e
Introduction to Web Development (4340704)

Assessment Rubrics:
% of
Criteria Rubrics Marks
point
Excellent (10-8 marks): Completed programs/scripts
correctly as per the requirements.
C1: Adequate (7-6 marks): Completed programs/scripts
Program correctly with approx. 70% requirements.
50 %
Completeness/ Poor (5-4 marks): Completed programs/scripts correctly
Correctness with 70% - 50% requirements.
Unsatisfactory (0-3 marks): Completed programs/ scripts
correctly with less than 50% requirements.
Excellent (10-8 marks): The code is clean, well-organized and
very easy to understand.
Adequate (7-6 marks): The code is fairly easy to read and
C2: understand.
25 %
Readability Poor (5-4 marks): The code is readable only by someone who
knows what it is supposed to be doing.
Unsatisfactory (0-3 marks): The code is poorly organized and
very difficult to understand.
Excellent (10-8 marks):
• Coding standards are followed in complete code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• The Complete code is well-documented with comments
explaining the code.
Adequate (7-6 marks):
• Coding standards are followed in most of the code while
naming variables/functions/ classes, explaining the
C3:
purpose of variables/ functions/classes.
Coding
25 % • Most of the code is documented with comments
Standards/ explaining the code.
Documentation
Poor (5-4 marks):
• Coding standards are followed in very little code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• Very little code is documented with comments
explaining the code.
Unsatisfactory (0-3 marks):
• Coding standards are not followed properly.
• Proper comments are not written explaining the code.
Total Marks for Practical = 0.5 * (Marks of C1) + 0.25 * (Marks of C2) + 0.25 * (Marks of C3)

Signature with Date:

33 | P a g e
Introduction to Web Development (4340704)

Practical No. 4: Decision making statements and Loops


Write a script that reads the name of the car and displays the name of the company
the car belongs to as per the below table:
Car Company
Safari, Nexon, Tigor, Tiago Tata
XUV700, XUV300, Bolero Mahindra
i20, Verna, Venue, Creta Hyundai
Swift, Alto, Baleno, Brezza Suzuki

Write a script to read the marks of 4 subjects and display the result as per the below
instructions:
GTU
Mark-Range
GRADE
AA 85 - 100
AB 75 - 84
BB 65 - 74
BC 55 - 64
CC 45 - 54
CD 40 - 44
DD 35 - 39
FF < 35 (FAIL)
• Each of the four subjects is worth 100 marks.
• If a student gets less than 35 marks in any subject, then he/she will be marked
as FAIL, otherwise he/she will be marked as PASS.
The result contains the grade of each individual subject in tabular format as per the
above table.
Write a script to display Fibonacci numbers up to a given term.
Write a script to display a multiplication table for the given number.

Objectives:
This practical will help student to practice writing PHP scripts using Decision making
structure and Loops.
• Conditional statements are used to perform different actions based on different
conditions.
• Loops are used to run same block of code again and again certain number of
times.

Relevant Program Outcomes (POs):


Basic and Discipline specific knowledge (PO1): Apply knowledge of basic
mathematics, science and engineering fundamentals and engineering
specialization to solve the Computer Engineering problems.
34 | P a g e
Introduction to Web Development (4340704)

Problem analysis (PO2): Identify and analyse well-defined Computer Engineering


problems using codified standard methods.
Design/development of solutions (PO3): Design solutions for Computer
Engineering well-defined technical problems and assist with the design of systems
components or processes to meet specified needs.
Engineering Tools, Experimentation and Testing (PO4): Apply modern Computer
Engineering tools and appropriate technique to conduct standard tests and
measurements.

Competency and Practical Skills:


This practical is expected to develop the following skills for the industry-identified
competency ‘Develop Interactive Web application using PHP and MySQL’:
Programming skills.
Debugging skills.

Relevant Course Outcomes (COs):


Develop PHP scripts using variables, operators and control structures.

Practical Outcomes:
Use decision making statements in PHP scripts.
Use loops in PHP scripts.

Relevant Affective domain Outcomes (ADOs):


Maintain tools and equipments.
Follow Coding standards and practices.
Follow ethical practices.

Prerequisite Theory:
Decision Making Statements:
Controls statements are used to control are used to control the flow of execution of
program based on certain conditions. In PHP, there are following decision making
statements:

• if statement
• if...else statement
• if...elseif...else statement
• switch statement

if statement:
if statement allow us to run a block of code if certain condition is true. If condition is
false it will not execute block of code.
35 | P a g e
Introduction to Web Development (4340704)

if(condition) {
Block of code // statements to execute if condition is
// true
}

if...else statement:
if...else executes a block of code if certain condition is true and another block of
code if condition is false.

if(condition) {
Block of code // statements to execute if
// condition is true
}
else {
Block of code // statements to execute if
// condition is false
}

if...elseif...else statement:

It is similar to multiple if...else statements. It executes different blocks of


code based on different conditions.

if(condition) {
Block of code // statements to execute if this
// condition is true
}
elseif(condition) {
Block of code // statements to execute if this
// condition is true
} elseif(condition) {
Block of code // statements to execute if this
// condition is true
} else {
Block of code // statements to execute if all
// conditions are false
}

switch statement:
The switch statement is used to perform different actions based on different conditions.
Use the switch statement to select one of many blocks of code to be executed.

36 | P a g e
Introduction to Web Development (4340704)

switch(n) {
case value1:
code to be executed if n== value1;
break;
case value2:
code to be executed if n== value2;
break;
case value3:
code to be executed if n== value3;
break;
case value4:
code to be executed if n== value4;
break;
......
default:
code to be executed if n != any case;
}

Loops:
Loops in PHP are used to execute the same block of code a specified number of times.
PHP supports below loop statements:

• while loop
• do...while loop
• for loop
• foreach loop
while loop:
while loop executes a block of code as long as the specified condition is true.
while(condition) {
Block of code // statements to execute
// till condition is true
}

do...while loop:
do...while loop executes a block of code once, and then repeats the loop as long as the
specified condition is true
do {
Block of code // statements to execute till
// condition is true. Executed once
// before checking condition.
} while(condition);

37 | P a g e
Introduction to Web Development (4340704)

for loop:
for loop executes a block of code a specified number of times.

for(init counter; condition; increment/decrement counter) {


Block of code // statements to execute
// till condition is true
}

foreach loop:
foreach loop executes a block of code for each element in an array.

foreach ($array as $val) {


Block of code // statements to execute
// for each element in an array
}

break statement:
break statement is used to terminate the execution of a loop prematurely.

while(condition1) {
Block of code // statements to execute
// till condition1 is true
if(condition2) {
break; // exit while loop is condition2
// is true
}
}

continue statement:
continue statement is used to halt the current iteration of a loop and start next
iteration of loop. It does not terminate the loop.
while(condition1) {

if(condition2) {
continue; // if condition2 is true then
// remaining part of the loop will
// not be executed in this
// iteration
}
Block of code // statements to execute
// till condition1 is true
}

38 | P a g e
Introduction to Web Development (4340704)

Resources Required:
Sr.
Instrument /Components Configuration/Specification
No
Processor:
1. Computer System RAM:
Operating System:

2. XAMPP server XAMPP Version:

3. Text Editor Editor:

4. Web Browser Browser:

Source code and Output:


Write a script that reads the name of the car and displays the name of the company
the car belongs to as per the below table:
Car Company
Safari, Nexon, Tigor, Tiago Tata
XUV700, XUV300, Bolero Mahindra
i20, Verna, Venue, Creta Hyundai
Swift, Alto, Baleno, Brezza Suzuki

Source Code:

39 | P a g e
Introduction to Web Development (4340704)

Output:

Write a script to read the marks of 4 subjects and display the result as per the below
instructions:
GTU
Mark-Range
GRADE
AA 85 - 100
AB 75 - 84
BB 65 - 74
BC 55 - 64
CC 45 - 54
CD 40 - 44
DD 35 - 39
FF < 35 (FAIL)

40 | P a g e
Introduction to Web Development (4340704)

• Each of the four subjects is worth 100 marks.


• If a student gets less than 35 marks in any subject, then he/she will be marked
as FAIL, otherwise he/she will be marked as PASS.
The result contains the grade of each individual subject in tabular format as per the
above table.
Source Code:

41 | P a g e
Introduction to Web Development (4340704)

Output:

Write a script to display Fibonacci numbers up to a given term.


Source Code:

42 | P a g e
Introduction to Web Development (4340704)

Output:

Write a script to display a multiplication table for the given number.


Source Code:

43 | P a g e
Introduction to Web Development (4340704)

Output:

Practical related Quiz:


Which of the following is a decision-making statement in PHP?
A) for loop
B) switch statement
C) do-while loop
D) foreach loop
Which loop statement in PHP will always execute the code block at least once?
A) for loop
B) while loop
C) do-while loop

44 | P a g e
Introduction to Web Development (4340704)

D) foreach loop
Which of the following loop statements in PHP is used to execute a code block for
a specific number of times?
A) for loop
B) while loop
C) do-while loop
D) foreach loop
What is the output of the following code?
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
continue;
}
echo $i;
}
A) 12345678910
B) 1234678910
C) 123468910
A) 123456789
Which of the following is used to execute a code block multiple times in PHP?
A) decision-making statement
B) loop statement
C) function
D) class
Which of the following is used to skip an iteration in a loop in PHP?
A) continue
B) break
C) return
D) exit
Which of the following is used to execute a block of code if none of the conditions
in a series of if-else statements are true?
A) if statement
B) else if statement
C) else statement
D) switch statement

45 | P a g e
Introduction to Web Development (4340704)

What is the correct syntax of the switch statement in PHP?


A) switch { case value: // code block }
B) switch ( value ) { case: // code block }
C) switch ( value ) { case value: // code block }
D) switch ( case value ) { // code block }
What is the output of the following code?
$x = 10;
if ($x > 5 && $x < 15) {
echo "The number is between 5 and 15";
} else {
echo "The number is not between 5 and 15";
}
A) The number is between 5 and 15
B) The number is not between 5 and 15
C) The number is 10
D) None of the above
What is the output of the following code?
$i = 1;
do {
echo $i;
} while ($i < 1);
A) 1
B) Infinite loop
C) No output
D) None of the above

References:
https://www.w3schools.com/php/php_if_else.asp
https://www.w3schools.com/php/php_looping.asp
https://www.geeksforgeeks.org/php-decision-making
https://www.geeksforgeeks.org/php-loops
https://www.tutorialspoint.com/php/php_decision_making.htm
https://www.tutorialspoint.com/php/php_loop_types.htm

46 | P a g e
Introduction to Web Development (4340704)

Assessment Rubrics:
% of
Criteria Rubrics Marks
point
Excellent (10-8 marks): Completed programs/scripts
correctly as per the requirements.
C1: Adequate (7-6 marks): Completed programs/scripts
Program correctly with approx. 70% requirements.
50 %
Completeness/ Poor (5-4 marks): Completed programs/scripts correctly
Correctness with 70% - 50% requirements.
Unsatisfactory (0-3 marks): Completed programs/ scripts
correctly with less than 50% requirements.
Excellent (10-8 marks): The code is clean, well-organized and
very easy to understand.
Adequate (7-6 marks): The code is fairly easy to read and
C2: understand.
25 %
Readability Poor (5-4 marks): The code is readable only by someone who
knows what it is supposed to be doing.
Unsatisfactory (0-3 marks): The code is poorly organized and
very difficult to understand.
Excellent (10-8 marks):
• Coding standards are followed in complete code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• The Complete code is well-documented with comments
explaining the code.
Adequate (7-6 marks):
• Coding standards are followed in most of the code while
naming variables/functions/ classes, explaining the
C3:
purpose of variables/ functions/classes.
Coding
25 % • Most of the code is documented with comments
Standards/ explaining the code.
Documentation
Poor (5-4 marks):
• Coding standards are followed in very little code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• Very little code is documented with comments
explaining the code.
Unsatisfactory (0-3 marks):
• Coding standards are not followed properly.
• Proper comments are not written explaining the code.
Total Marks for Practical = 0.5 * (Marks of C1) + 0.25 * (Marks of C2) + 0.25 * (Marks of C3)

Signature with Date:

47 | P a g e
Introduction to Web Development (4340704)

Practical No. 5: Arrays


Write a script to calculate the length of a string and count the number of words in
the given string without using string functions.
Write a script to sort a given indexed array.
Write a script to perform 3 x 3 matrix Multiplication.
Write a script to encode a given message into equivalent Morse code.

Objectives:
In PHP, array data structure allows user to store multiple elements of similar data type
under a single variable. Array provide below advantages:
• No need to use multiple variables to store different data.
• Easy to traverse data in array using loops.
• Easy to sort data stored in array.
This practical will help student to practice writing PHP scripts using arrays.

Relevant Program Outcomes (POs):


Basic and Discipline specific knowledge (PO1): Apply knowledge of basic
mathematics, science and engineering fundamentals and engineering
specialization to solve the Computer Engineering problems.
Problem analysis (PO2): Identify and analyse well-defined Computer Engineering
problems using codified standard methods.
Design/development of solutions (PO3): Design solutions for Computer
Engineering well-defined technical problems and assist with the design of systems
components or processes to meet specified needs.
Engineering Tools, Experimentation and Testing (PO4): Apply modern Computer
Engineering tools and appropriate technique to conduct standard tests and
measurements.

Competency and Practical Skills:


This practical is expected to develop the following skills for the industry-identified
competency ‘Develop Interactive Web application using PHP and MySQL’:
Programming skills.
Debugging skills.

Relevant Course Outcomes (COs):


Develop PHP scripts using arrays and functions.

Practical Outcomes:
Develop PHP scripts using one-dimensional, multi-dimensional and associative
arrays.

48 | P a g e
Introduction to Web Development (4340704)

Relevant Affective domain Outcomes (ADOs):


Maintain tools and equipments.
Follow Coding standards and practices.
Follow ethical practices.

Prerequisite Theory:
PHP array is a collection of similar data times stored in a single variable. It is basically an
ordered map, which contains values on the basis of keys/indexes. PHP arrays allows
traversing and processing of data items using a single loop. There are three types of
arrays in PHP.
1. Indexed arrays
2. Associative arrays
3. Multi-dimensional arrays
Indexed/Numeric arrays
These type of arrays can store data of any type. They have integer indexes that start at
zero by default. The Indexed array can be created as follow:

$subject_codes = array(4330701, 4330702, 4330703, 4330704);

Or it can be assigned manually as below:

$subject_codes[0] = 4330701;
$subject_codes[1] = 4330702;
$subject_codes[2] = 4330703;
$subject_codes[3] = 4330704;

Below example shows accessing data stored in the array:

$subject_codes = array(4330701, 4330702, 4330703, 4330704);


echo "Subject codes: <br>";
echo $subject_codes[0] . "<br>";
echo $subject_codes[1] . "<br>";
echo $subject_codes[2] . "<br>";
echo $subject_codes[3] . "<br>";

Another way to access all elements in the array using for loops is as below:

$subject_codes = array(4330701, 4330702, 4330703, 4330704);


echo "Subject codes: <br>";
for($i = 0; $i < count($subject_codes); $i++) {
echo $subject_codes[$i] . "<br>";
}

49 | P a g e
Introduction to Web Development (4340704)

We can access array data using foreach loop as below:


$subject_codes = array(4330701, 4330702, 4330703, 4330704);
echo "Subject codes: <br>";
foreach ($subject_codes as $code) {
echo $code . "<br>";
}

Associative arrays
Associative arrays are similar to indexed arrays but instead of integer indexes values are
assigned to user-defined keys of string type. Below example shows how to assign
associative array:
$subjects = array("4330701" => "SLP",
"4330702" => "RDBMS",
"4330703" => "BOS",
"4330704" => "DSA");

Or it can be assigned manually as below:


$subjects["4330701"] = "SLP";
$subjects["4330702"] = "RDBMS";
$subjects["4330703"] = "BOS";
$subjects["4330704"] = "DSA";

Below example shows accessing data stored in the associative array:


$subjects = array("4330701" => "SLP",
"4330702" => "RDBMS",
"4330703" => "BOS",
"4330704" => "DSA");
echo "Subjects: <br>";
echo $subjects["4330701"] . "<br>";
echo $subjects["4330702"] . "<br>";
echo $subjects["4330703"] . "<br>";
echo $subjects["4330704"] . "<br>";

We can access associative array data using foreach loop as below:


$subjects = array("4330701" => "SLP",
"4330702" => "RDBMS",
"4330703" => "BOS",
"4330704" => "DSA");
echo "Subjects: <br>";
foreach ($subjects as $code => $sub) {
echo $code . ": " . $sub . "<br>";
}

50 | P a g e
Introduction to Web Development (4340704)

Multidimensional arrays
A multidimensional array is an array containing one or more arrays. PHP supports
multidimensional array that are two or more levels deep. However, arrays more than
three levels are hard to manage. Below is example of two dimensional array:
$subjects = array (
array("4330701","SLP",150),
array("4330702","RDBMS",150),
array("4330703","BOS",150),
array("4330704","DSA",150)
);

Below example shows a way to access all elements in the multidimensional array using
for loops is as below:
$subjects = array (
array("4330701","SLP",150),
array("4330702","RDBMS",150),
array("4330703","BOS",150),
array("4330704","DSA",150)
);

for ($row = 0; $row < count($subjects); $row++) {


echo "Subject " . $row . ": <br>";
for ($col = 0; $col < count($subjects[0]); $col++) {
echo $subjects[$row][$col] . "<br>";
}
}

Resources Required:
Sr.
Instrument /Components Configuration/Specification
No
Processor:
1. Computer System RAM:
Operating System:

XAMPP server XAMPP Version:


2.

Text Editor Editor:


3.

4. Web Browser Browser:

Source code and Output:


Write a script to calculate the length of a string and count the number of words in
the given string without using string functions.

51 | P a g e
Introduction to Web Development (4340704)

Source Code:

Output:

52 | P a g e
Introduction to Web Development (4340704)

Write a script to sort a given indexed array.


Source Code:

Output:

53 | P a g e
Introduction to Web Development (4340704)

Write a script to perform 3 x 3 matrix Multiplication.


Source Code:

Output:

54 | P a g e
Introduction to Web Development (4340704)

Write a script to encode a given message into equivalent Morse code.


Source Code:

55 | P a g e
Introduction to Web Development (4340704)

Output:

Practical related Quiz


Which of the following is/are the correct way(s) to declare an array in PHP?
A) $arr = {1, 2, 3};
B) $arr = [1, 2, 3];
C) $arr = array(1, 2, 3);
D) $arr = (1, 2, 3);
What is the output of the following code?
$arr = array("apple", "banana", "cherry");
echo $arr[1];
A) "apple"
B) "banana"
C) "cherry"
D) None of the above
What is the correct syntax to declare an array in PHP?
A) array()
B) []
C) Array()
D) All of the above
What is the output of the following code?
$array = array(10, 20, 30, 40);
echo count($array);

56 | P a g e
Introduction to Web Development (4340704)

A. 4
B. 3
C. 2
D. 1
Which of the following array functions in PHP is used to sort an array in descending
order according to its values?
A) sort()
B) rsort()
C) asort()
D) arsort()
What is the output of the following code?
$arr1 = array(1, 2, 3);
$arr2 = array(4, 5, 6);
$result = array_merge($arr1, $arr2);
print_r($result);
A) Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
B) Array ( [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
C) Array ( [0] => 1 [1] => 4 [2] => 5 [3] => 6 )
D) None of the above
What is an associative array in PHP?
A) An array that stores values in indexed format
B) An array that stores values in a key-value pair format
C) An array that stores values in a multidimensional format
D) An array that stores values in a stack formatWhich of the following array
functions in PHP is used to remove the last element from an array?
A) array_pop()
B) array_shift()
C) array_slice()
D) array_splice()
Which of the following array functions in PHP is used to check whether a particular
value exists in an array or not?
A) in_array()
B) array_search()
C) array_key_exists()

57 | P a g e
Introduction to Web Development (4340704)

D) array_unique()
Which of the following array functions in PHP is used to remove the first element
from an array?
A) array_pop()
B) array_shift()
C) array_slice()
D) array_splice()
How to check if a key exists in an associative array in PHP?
A) Using the in_array() function
B) Using the array_search() function
C) Using the isset() function
D) Using the empty() function
Which of the following functions can be used to merge two or more arrays into one
array in PHP?
A) array_concat()
B) array_merge()
C) array_combine()
D) array_intersect()
What is the output of the following code?
$arr1 = array(1, 2, 3);
$arr2 = array(4, 5, 6);
$arr3 = $arr1 + $arr2;
print_r($arr3);
A) Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
B) Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 5 [4] => 6 )
C) Array ( [0] => 4 [1] => 5 [2] => 6 [3] => 1 [4] => 2 [5] => 3 )
D) Error

References:
https://www.php.net/manual/en/language.types.array.php
https://www.w3schools.com/php/php_arrays.asp
https://www.geeksforgeeks.org/php-arrays
https://www.tutorialspoint.com/php/php_arrays.htm
https://www.freecodecamp.org/news/how-to-use-arrays-in-php/

58 | P a g e
Introduction to Web Development (4340704)

Assessment Rubrics:
% of
Criteria Rubrics Marks
point
Excellent (10-8 marks): Completed programs/scripts
correctly as per the requirements.
C1: Adequate (7-6 marks): Completed programs/scripts
Program correctly with approx. 70% requirements.
50 %
Completeness/ Poor (5-4 marks): Completed programs/scripts correctly
Correctness with 70% - 50% requirements.
Unsatisfactory (0-3 marks): Completed programs/ scripts
correctly with less than 50% requirements.
Excellent (10-8 marks): The code is clean, well-organized and
very easy to understand.
Adequate (7-6 marks): The code is fairly easy to read and
C2: understand.
25 %
Readability Poor (5-4 marks): The code is readable only by someone who
knows what it is supposed to be doing.
Unsatisfactory (0-3 marks): The code is poorly organized and
very difficult to understand.
Excellent (10-8 marks):
• Coding standards are followed in complete code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• The Complete code is well-documented with comments
explaining the code.
Adequate (7-6 marks):
• Coding standards are followed in most of the code while
naming variables/functions/ classes, explaining the
C3:
purpose of variables/ functions/classes.
Coding
25 % • Most of the code is documented with comments
Standards/ explaining the code.
Documentation
Poor (5-4 marks):
• Coding standards are followed in very little code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• Very little code is documented with comments
explaining the code.
Unsatisfactory (0-3 marks):
• Coding standards are not followed properly.
• Proper comments are not written explaining the code.
Total Marks for Practical = 0.5 * (Marks of C1) + 0.25 * (Marks of C2) + 0.25 * (Marks of C3)

Signature with Date:

59 | P a g e
Introduction to Web Development (4340704)

Practical No. 6: Functions


Consider a currency system in which there are notes of 7 denominations, namely
Rs. 1, Rs. 2, Rs. 5, Rs. 10, Rs. 20, Rs. 50 and Rs. 100. Write a function that computes
the smallest number of notes that will combine for a given amount of money.
Write scripts using string functions:
• to check if the given string is lowercase or not.
• to reverse the given string.
• to remove white spaces from the given string.
• to replace the given word from the given string.
Write scripts using math functions:
• to generate a random number between the given range.
• to display the binary, octal and hexadecimal of a given decimal number.
• to display the sin, cos and tan of the given angle.
Write a script to display the current date and time in different formats.

Objectives:
A function is a block of reusable code that is used to perform a specific action. Functions
provide below advantages:
• Reduce duplication of the code.
• Modularisation of the code.
• Improve clarity of the code.
• Information hiding.
This practical will help student to practice writing PHP scripts using user defined
functions and in-built functions.

Relevant Program Outcomes (POs):


Basic and Discipline specific knowledge (PO1): Apply knowledge of basic
mathematics, science and engineering fundamentals and engineering
specialization to solve the Computer Engineering problems.
Problem analysis (PO2): Identify and analyse well-defined Computer Engineering
problems using codified standard methods.
Design/development of solutions (PO3): Design solutions for Computer
Engineering well-defined technical problems and assist with the design of systems
components or processes to meet specified needs.
Engineering Tools, Experimentation and Testing (PO4): Apply modern Computer
Engineering tools and appropriate technique to conduct standard tests and
measurements.

60 | P a g e
Introduction to Web Development (4340704)

Competency and Practical Skills:


This practical is expected to develop the following skills for the industry-identified
competency ‘Develop Interactive Web application using PHP and MySQL’:
Programming skills.
Debugging skills.

Relevant Course Outcomes (COs):


Develop PHP scripts using arrays and functions.

Practical Outcomes:
Develop PHP scripts using in-built and user defined functions.

Relevant Affective domain Outcomes (ADOs):


Maintain tools and equipments.
Follow Coding standards and practices.
Follow ethical practices.

Prerequisite Theory:
A function is a block of code written in a program to perform some specific task.
Functions take inputs as parameters, executes a block of statements or perform
operations on these parameters and returns the result. There are two types of functions
in PHP:

• Built-in functions: PHP provides large collection of built-in library functions (more
than 1000 functions). Whenever we need, we can just call these built-in functions
as per our requirements.
• User defined functions: PHP allows us to create our own customised functions
called user defined functions. We can create our own packages of code and use
them whenever required.
User defined functions:
User defined functions are defined as below:

function functionname() {
Block of code;
}

Note: A function name must start with a letter or an underscore. Function names are
NOT case-sensitive.
Below code is example of PHP function which prints a message on the browser.

61 | P a g e
Introduction to Web Development (4340704)

<?php
function writeMessage() {
echo "Welcome to the PHP course..!!";
}

writeMessage (); // function call


?>

Function with arguments:


Data can be passed to functions through arguments. Arguments are specified inside the
parentheses after the function name. There can be any number of arguments separated
by comma.

<?php
function printSubjects($code, $subject) {
echo "Subject name for code $code is $subject <br>";
}

printSubjects("4330701","Scripting Language -Python");


printSubjects("4330702","Relational Database Management
System");
printSubjects("4330703","Basics of Operating System");
printSubjects("4330704","Data Structures and Algorithms");
?>

Arguments are by default passed by value, which means that a copy of the value is
passed to the function, so the original variable that was passed into the function is not
changed when we modify argument in the function. We can pass argument by
reference, where changes made to the argument also change the original variable that
was passed in. The & operator is used to pass variable by reference in argument. Below
example show how to pass argument by reference:

<?php
function incrementVar(&$var) {
$var += 1;
return $var;
}
$a = 5;
$res = incrementVar($a);
echo "Value after increment is $res <br>";
?>

Below example shows how to use default argument:

62 | P a g e
Introduction to Web Development (4340704)

<?php
function areaofCircle($radius = 10) {
$area = 2 * 3.14 * $radius;
echo "Area of Circle is : $area <br>";
}

areaofCircle();
areaofCircle(20);
?>

Function with returning value:


Function can return a value using return statements:

<?php
function sumArray($arr) {
$sum = 0;
for ($i = 0; $i < count($arr); $i++) {
$sum += $arr[$i];
}
return $sum;
}
$a = array(4, 9, 11, 25, 17);
$s = sumArray($a);

echo "Sum of array is: $s <br>";


?>

Resources Required:
Sr.
Instrument /Components Configuration/Specification
No
Processor:
1. Computer System RAM:
Operating System:

XAMPP Version:
2. XAMPP server

Editor:
3. Text Editor

4. Web Browser Browser:

63 | P a g e
Introduction to Web Development (4340704)

Source code and Output:


Consider a currency system in which there are notes of 7 denominations, namely
Rs. 1, Rs. 2, Rs. 5, Rs. 10, Rs. 20, Rs. 50 and Rs. 100. Write a function that computes
the smallest number of notes that will combine for a given amount of money.
Source Code:

Output:

64 | P a g e
Introduction to Web Development (4340704)

Write scripts using string functions:


• to check if the given string is lowercase or not.
• to reverse the given string.
• to remove white spaces from the given string.
• to replace the given word from the given string.
Source Code:

65 | P a g e
Introduction to Web Development (4340704)

Output:

Write scripts using math functions:


• to generate a random number between the given range.
• to display the binary, octal and hexadecimal of a given decimal number.
• to display the sin, cos and tan of the given angle.
Source Code:

66 | P a g e
Introduction to Web Development (4340704)

Output:

Write a script to display the current date and time in different formats.
Source Code:

67 | P a g e
Introduction to Web Development (4340704)

Output:

Practical related Quiz:


What is the correct syntax to define a function in PHP?
A) function myFunction() {}
B) myFunction() {}
C) def myFunction() {}
D) function = myFunction() {}
What is the scope of a variable defined inside a function in PHP?
A) Global
B) Local
C) Static
D) None of the above
Which of the following is the correct way to define a default value for a function
argument in PHP?
A) function test($arg = "default") {}
B) function test($arg : "default") {}
C) function test($arg => "default") {}
D) function test($arg | "default") {}
What is the output of the following code?

68 | P a g e
Introduction to Web Development (4340704)

function test() {
$args = func_get_args();
foreach($args as $arg) {
echo $arg . " ";
}
}
test("hello", "world");
A) "hello world"
B) "hello, world"
C) "helloworld"
D) None of the above
Which function is used to check whether a function exists or not in PHP?
A) function_exists()
B) method_exists()
C) class_exists()
D) property_exists()
What is the output of the following code?
function myFunction(&$a) {
$a++;
}
$x = 5;
myFunction($x);
echo $x;
A. 5
B. 6
C. Error
D. None of the above

References:
https://www.php.net/manual/en/language.functions.php
https://www.w3schools.com/php/php_functions.asp
https://www.geeksforgeeks.org/php-functions
https://www.tutorialspoint.com/php/php_functions.htm
https://zetcode.com/php/function

69 | P a g e
Introduction to Web Development (4340704)

Assessment Rubrics:
% of
Criteria Rubrics Marks
point
Excellent (10-8 marks): Completed programs/scripts
correctly as per the requirements.
C1: Adequate (7-6 marks): Completed programs/scripts
Program correctly with approx. 70% requirements.
50 %
Completeness/ Poor (5-4 marks): Completed programs/scripts correctly
Correctness with 70% - 50% requirements.
Unsatisfactory (0-3 marks): Completed programs/ scripts
correctly with less than 50% requirements.
Excellent (10-8 marks): The code is clean, well-organized and
very easy to understand.
Adequate (7-6 marks): The code is fairly easy to read and
C2: understand.
25 %
Readability Poor (5-4 marks): The code is readable only by someone who
knows what it is supposed to be doing.
Unsatisfactory (0-3 marks): The code is poorly organized and
very difficult to understand.
Excellent (10-8 marks):
• Coding standards are followed in complete code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• The Complete code is well-documented with comments
explaining the code.
Adequate (7-6 marks):
• Coding standards are followed in most of the code while
naming variables/functions/ classes, explaining the
C3:
purpose of variables/ functions/classes.
Coding
25 % • Most of the code is documented with comments
Standards/ explaining the code.
Documentation
Poor (5-4 marks):
• Coding standards are followed in very little code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• Very little code is documented with comments
explaining the code.
Unsatisfactory (0-3 marks):
• Coding standards are not followed properly.
• Proper comments are not written explaining the code.
Total Marks for Practical = 0.5 * (Marks of C1) + 0.25 * (Marks of C2) + 0.25 * (Marks of C3)

Signature with Date:

70 | P a g e
Introduction to Web Development (4340704)

Practical No. 7: OOP Concepts


Write a script to define a class with constructor and destructor.
Create an object of a class and access its public properties and methods.
Write a script that uses the set attribute and get attribute methods to access a
class’s private attributes of a class.
Write a script to demonstrate single inheritance.
Write a script to demonstrate multiple inheritance.
Write a script to demonstrate multilevel inheritance.
Write a script to demonstrate method overriding.
Write a script to demonstrate method overloading based on the number of
arguments.
Write a script to demonstrate a simple interface.
Write a script to demonstrate a simple abstract class.
Write a script to demonstrate cloning of objects.

Objectives:
From PHP5, you can also write PHP code in an object-oriented style. Object-Oriented
Programming (OOP) is a programming paradigm that emphasizes the use of objects and
classes to structure code and data in a way that promotes code reuse, modularity, and
maintainability. In PHP, OOP has several practical significances, including:
• Code organization
• Encapsulation
• Inheritance
• Polymorphism
• Modularity
Overall, OOP in PHP can make it easier to write more maintainable, extensible, and
reliable code, which can ultimately lead to faster development times and fewer bugs.

Relevant Program Outcomes (POs):


Basic and Discipline specific knowledge (PO1): Apply knowledge of basic
mathematics, science and engineering fundamentals and engineering
specialization to solve the Computer Engineering problems.
Problem analysis (PO2): Identify and analyse well-defined Computer Engineering
problems using codified standard methods.
Design/development of solutions (PO3): Design solutions for Computer
Engineering well-defined technical problems and assist with the design of systems
components or processes to meet specified needs.

71 | P a g e
Introduction to Web Development (4340704)

Engineering Tools, Experimentation and Testing (PO4): Apply modern Computer


Engineering tools and appropriate technique to conduct standard tests and
measurements.
Project Management (PO6): Use engineering management principles individually,
as a team member or a leader to manage projects and effectively communicate
about well-defined engineering activities.
Life-long learning (PO7): Ability to analyse individual needs and engage in updating
in the context of technological changes in field of engineering.

Competency and Practical Skills:


This practical is expected to develop the following skills for the industry-identified
competency ‘Develop Interactive Web application using PHP and MySQL’:
Programming skills.
Debugging skills.

Relevant Course Outcomes (COs):


Develop PHP scripts by applying object-oriented concepts.

Practical Outcomes:
Develop PHP scripts with the help of various object-oriented concepts like class,
object, constructor, inheritance, interface, overloading and overriding.

Relevant Affective domain Outcomes (ADOs):


Maintain tools and equipments.
Follow Coding standards and practices.
Follow ethical practices.

Prerequisite Theory:
Before diving into implementing OOP concepts in PHP, it's important to have a solid
understanding of the following concepts:
• Classes and Objects: A class is a blueprint for creating objects, while an object is
an instance of a class. Classes define the properties and methods that objects will
have.
• Inheritance: Inheritance is a mechanism that allows a new class to be based on
an existing class, inheriting its properties and methods. This allows for code reuse
and can make it easier to organize your code.
• Encapsulation: Encapsulation is the practice of hiding the implementation details
of a class from the outside world, so that the class can only be accessed through
its public interface. This helps to prevent unintended changes to the state of an
object.

72 | P a g e
Introduction to Web Development (4340704)

• Polymorphism: Polymorphism is the ability for objects of different classes to be


used interchangeably. This is often achieved through the use of interfaces or
abstract classes.
• Abstraction: Abstraction is the process of identifying the essential features of a
concept, and ignoring the details that are not relevant. This is often achieved
through the use of abstract classes or interfaces.
• Access Modifiers: Access modifiers are keywords that determine the visibility of
properties and methods in a class. The three access modifiers in PHP are public,
protected, and private.
• Static Methods and Properties: Static methods and properties belong to the class
itself, rather than to a specific instance of the class. They can be accessed without
creating an object.
By understanding these concepts, you'll have a solid foundation for implementing OOP
in PHP. You can start by defining classes and creating objects, and then work your way
up to using inheritance, encapsulation, polymorphism, and other advanced OOP
concepts.

Resources Required:
Sr.
Instrument /Components Configuration/Specification
No
Processor:
1. Computer System RAM:
Operating System:

XAMPP server XAMPP Version:


2.

Text Editor Editor:


3.

4. Web Browser Browser:

Source code:
Write a script to define a class with constructor and destructor.
Source Code:

73 | P a g e
Introduction to Web Development (4340704)

Output:

74 | P a g e
Introduction to Web Development (4340704)

Create an object of a class and access its public properties and methods.
Source Code:

Output:

75 | P a g e
Introduction to Web Development (4340704)

Write a script that uses the set attribute and get attribute methods to access a
class’s private attributes of a class.
Source Code:

Output:

76 | P a g e
Introduction to Web Development (4340704)

Write a script to demonstrate single inheritance.


Source Code:

Output:

77 | P a g e
Introduction to Web Development (4340704)

Write a script to demonstrate multiple inheritance.


Source Code:

Output:

78 | P a g e
Introduction to Web Development (4340704)

Write a script to demonstrate multilevel inheritance.


Source Code:

Output:

79 | P a g e
Introduction to Web Development (4340704)

Write a script to demonstrate method overriding.


Source Code:

Output:

80 | P a g e
Introduction to Web Development (4340704)

Write a script to demonstrate method overloading based on the number of


arguments.
Source Code:

Output:

81 | P a g e
Introduction to Web Development (4340704)

Write a script to demonstrate a simple interface.


Source Code:

Output:

82 | P a g e
Introduction to Web Development (4340704)

Write a script to demonstrate a simple abstract class.


Source Code:

Output:

83 | P a g e
Introduction to Web Development (4340704)

Write a script to demonstrate cloning of objects.


Source Code:

Output:

84 | P a g e
Introduction to Web Development (4340704)

Practical related Quiz:


What is a class in PHP?
A) A function that returns a value
B) A group of functions that perform a specific task
C) A blueprint for creating objects
D) A variable that stores a value
What is an object in PHP?
A) A variable that stores a value
B) A function that returns a value
C) An instance of a class
D) A group of functions that performs a specific task
What is encapsulation in PHP?
A) The process of hiding the implementation details of a class
B) The process of creating new instances of a class
C) The process of defining properties within a class
D) The process of defining methods within a class
What is a constructor in PHP?
A) A method that is called automatically when an object is created
B) A method that is used to create new instances of a class
C) A method that is used to define properties within a class
D) A method that is used to define methods within a class
What is a destructor in PHP?
A) A method that is used to create new objects
B) A method that is used to destroy objects
C) A method that is used to copy objects
D) A method that is used to serialize objects
What is an interface in PHP?
A) A class that cannot be instantiated
B) A blueprint for creating objects
C) A set of methods that a class must implement
D) A method that is used to create new instances of a class
What is inheritance in PHP?
A) The process of creating a new class from an existing class

85 | P a g e
Introduction to Web Development (4340704)

B) The process of copying code from one class to another


C) The process of creating new instances of a class
D) The process of defining properties within a class
Which of the following is true about private properties in PHP?
A) They can be accessed from outside the class
B) They can only be accessed from within the class
C) They can be accessed from within the class and its subclasses
D) They can be accessed from anywhere in the program
What is method overloading in PHP?
A) The ability to define multiple methods with the same name in a class
B) The ability to override a method in a subclass
C) The ability to access private methods from outside the class
D) The ability to access static methods from outside the class
What is method overriding in PHP?
A) The ability to define multiple methods with the same name in a class
B) The ability to override a method in a subclass
C) The ability to access private methods from outside the class
D) The ability to access static methods from outside the class
What is the use of the self keyword in PHP?
A) It refers to the current instance of the class
B) It refers to the parent class
C) It refers to the subclass
D) It refers to the instance of the class that is being called

References:
https://www.w3schools.com/php/php_oop_intro.asp
https://code.tutsplus.com/tutorials/object-oriented-php-for-beginners--net-
12762
https://www.sitepoint.com/object-oriented-php-basics/
https://www.geeksforgeeks.org/object-oriented-programming-concepts-in-php/
https://www.php.net/manual/en/language.oop5.php
https://www.tutorialspoint.com/php/php_object_oriented.htm

86 | P a g e
Introduction to Web Development (4340704)

Assessment Rubrics:
% of
Criteria Rubrics Marks
point
Excellent (10-8 marks): Completed programs/scripts
correctly as per the requirements.
C1: Adequate (7-6 marks): Completed programs/scripts
Program correctly with approx. 70% requirements.
50 %
Completeness/ Poor (5-4 marks): Completed programs/scripts correctly
Correctness with 70% - 50% requirements.
Unsatisfactory (0-3 marks): Completed programs/ scripts
correctly with less than 50% requirements.
Excellent (10-8 marks): The code is clean, well-organized and
very easy to understand.
Adequate (7-6 marks): The code is fairly easy to read and
C2: understand.
25 %
Readability Poor (5-4 marks): The code is readable only by someone who
knows what it is supposed to be doing.
Unsatisfactory (0-3 marks): The code is poorly organized and
very difficult to understand.
Excellent (10-8 marks):
• Coding standards are followed in complete code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• The Complete code is well-documented with comments
explaining the code.
Adequate (7-6 marks):
• Coding standards are followed in most of the code while
naming variables/functions/ classes, explaining the
C3:
purpose of variables/ functions/classes.
Coding
25 % • Most of the code is documented with comments
Standards/ explaining the code.
Documentation
Poor (5-4 marks):
• Coding standards are followed in very little code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• Very little code is documented with comments
explaining the code.
Unsatisfactory (0-3 marks):
• Coding standards are not followed properly.
• Proper comments are not written explaining the code.
Total Marks for Practical = 0.5 * (Marks of C1) + 0.25 * (Marks of C2) + 0.25 * (Marks of C3)

Signature with Date:

87 | P a g e
Introduction to Web Development (4340704)

Practical No. 8: Forms


Create a web page using a form to collect employee information.
Extend practical - 8(i) to validate user information using regular expressions.
Create two distinct web pages to demonstrate information passing between them
using URL - Get method.
Create two different web pages to demonstrate information passing between web
pages using Hidden variables - Post method.

Objectives:
In PHP, forms are a powerful tool for collecting data from users and processing that data
on the server side. Here are some practical significances of using forms in PHP:
User Input: Forms allow users to enter information or data that can be processed
by PHP scripts on the server. This can include simple text input, file uploads, or even
complex data such as dates or email addresses.
Data Validation: Forms can be used to ensure that the data entered by users is valid
and meets certain criteria. For example, a form can check that an email address is
formatted correctly or that a password meets certain complexity requirements.
Security: Forms can be used to improve the security of PHP applications. For
example, forms can be used to implement measures such as CAPTCHA to prevent
automated attacks or CSRF tokens to prevent cross-site request forgery attacks.
User Experience: Forms can help to improve the user experience of PHP
applications by allowing users to interact with the application in a more intuitive
way. For example, forms can be used to allow users to search for specific content
or to create new accounts.
Data Processing: Forms allow PHP scripts to process user data on the server side.
This can include saving data to a database, sending email notifications, or
performing complex calculations.
Overall, forms are a fundamental part of PHP development and are an essential tool for
building interactive, user-friendly, and secure web applications.

Relevant Program Outcomes (POs):


Basic and Discipline specific knowledge (PO1): Apply knowledge of basic
mathematics, science and engineering fundamentals and engineering
specialization to solve the Computer Engineering problems.
Problem analysis (PO2): Identify and analyse well-defined Computer Engineering
problems using codified standard methods.
Design/development of solutions (PO3): Design solutions for Computer
Engineering well-defined technical problems and assist with the design of systems
components or processes to meet specified needs.

88 | P a g e
Introduction to Web Development (4340704)

Engineering Tools, Experimentation and Testing (PO4): Apply modern Computer


Engineering tools and appropriate technique to conduct standard tests and
measurements.
Project Management (PO6): Use engineering management principles individually,
as a team member or a leader to manage projects and effectively communicate
about well-defined engineering activities.
Life-long learning (PO7): Ability to analyse individual needs and engage in updating
in the context of technological changes in field of engineering.

Competency and Practical Skills:


This practical is expected to develop the following skills for the industry-identified
competency ‘Develop Interactive Web application using PHP and MySQL’:
Programming skills.
Debugging skills.

Relevant Course Outcomes (COs):


Develop web pages using form controls with validation to collect user inputs in PHP.

Practical Outcomes:
Create PHP scripts with the use of various form elements, perform validation and
implement form processing.

Relevant Affective domain Outcomes (ADOs):


Maintain tools and equipments.
Follow Coding standards and practices.
Follow ethical practices.

Prerequisite Theory:
Forms handling in PHP involves collecting data submitted by users through HTML
forms, processing that data using PHP scripts, and then taking actions based on that
data. Here are the steps involved in forms handling in PHP:
Creating an HTML form: First, create an HTML form that users can fill out. This form
should include input fields like text boxes, radio buttons, and checkboxes, and it
should have a "submit" button that sends the data to a PHP script.
Setting the "action" attribute: In the form tag, you should set the "action" attribute
to the filename of the PHP script that will process the data. When the user submits
the form, the data will be sent to this script for processing.
Retrieving form data: In the PHP script that will process the form data, you should
use the $_POST superglobal to retrieve the data submitted by the user. The $_POST
array contains key-value pairs, where the key is the name of the form field and the
value is the data entered by the user.

89 | P a g e
Introduction to Web Development (4340704)

Validating form data: Before processing the form data, you should validate it to
ensure that it is in the correct format and that it contains the required data. You
can use PHP's built-in functions for data validation, or you can create custom
validation functions.
Sanitizing form data: After validating the form data, you should sanitize it to
prevent malicious input, such as SQL injection attacks. You can use PHP's built-in
functions for data sanitization, such as htmlspecialchars() or filter_var().
Processing form data: Once the form data has been validated and sanitized, you
can process it according to your application's requirements. For example, you might
insert the data into a database, send an email, or redirect the user to a different
page.
Displaying feedback: After the form data has been processed, you should provide
feedback to the user. This might include a message confirming that their data was
successfully submitted or an error message if the data could not be processed.
In summary, forms handling in PHP involves creating an HTML form, processing the
data submitted through the form using a PHP script, validating and sanitizing the data,
and then taking actions based on that data. By following these steps, you can create
robust and secure web applications that can handle a wide range of user inputs.
Example HTML Form:

<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<h2>Registration Form</h2>
<form action="register.php" method="post">
<label for="username">Username:</label>
<input type="text" name="username" id="username"><br>

<label for="email">Email:</label>
<input type="email" name="email" id="email"><br>

<label for="password">Password: </label>


<input type="password" name="password" id="password"><br>

<input type="submit" value="Submit">


</form>
</body>
</html>

90 | P a g e
Introduction to Web Development (4340704)

The form has three input fields for the user to enter their desired username, email, and
password. The form's action attribute is set to register.php, which is the PHP script that
will handle the form data. The method attribute is set to post, indicating that the form
data will be sent as a POST request.
PHP Script (register.php):

<?php
// Retrieve form data
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];

// Validate form data


if (empty($username) || empty($email) || empty($password))
{
echo "Please fill in all fields.";
exit;
}

// Sanitize form data


$username = htmlspecialchars($username);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
$password = htmlspecialchars($password);

// Process form data (in this example, just display it)


echo "Thank you for registering!<br>";
echo "Your username is: $username<br>";
echo "Your email is: $email<br>";
echo "Your password is: $password<br>";
?>

The PHP script retrieves the form data using the $_POST superglobal and then validates
and sanitizes the data to prevent malicious input. In this example, the script checks that
all fields are filled in and uses the htmlspecialchars() and filter_var() functions to sanitize
the data.
Finally, the script processes the form data by displaying it back to the user. In a real-
world scenario, you might store the form data in a database or send it in an email.
That's it! This is a simple example of a registration page in PHP.

91 | P a g e
Introduction to Web Development (4340704)

Resources Required:
Sr.
Instrument /Components Configuration/Specification
No
Processor:
1. Computer System RAM:
Operating System:

2. XAMPP server XAMPP Version:

3. Text Editor Editor:

4. Web Browser Browser:

Source code and Output:


Create a web page using a form to collect employee information.
Extend practical - 8(i) to validate user information using regular expressions.
Source Code:

92 | P a g e
Introduction to Web Development (4340704)

Output:

Create two distinct web pages to demonstrate information passing between them
using URL - Get method.
Source Code:

93 | P a g e
Introduction to Web Development (4340704)

Output:

Create two different web pages to demonstrate information passing between web
pages using Hidden variables - Post method.
Source Code:

94 | P a g e
Introduction to Web Development (4340704)

Output:

Practical related Quiz:


What is the purpose of forms handling in PHP?
A) To display dynamic content on a web page
B) To process data submitted by users through HTML forms
C) To create interactive user interfaces
D) To manipulate data in a database
What is the purpose of form validation in PHP?
A) To prevent malicious input
B) To ensure that data is in the correct format
C) To check for required data
D) All of the above
Which PHP function is used to sanitize user input by converting special characters
to HTML entities?
A) htmlspecialchars()
B) filter_var()
C) trim()
D) addslashes()
What is the purpose of the "action" attribute in an HTML form?
A) To specify the method used to submit the form data
B) To specify the encoding type of the form data
C) To specify the URL of the page that will process the form data

95 | P a g e
Introduction to Web Development (4340704)

D) To specify the name of the form element


Which PHP function is used to check whether a variable contains a valid email
address?
A) filter_var()
B) is_email()
C) validate_email()
D) email_check()
What is the purpose of form feedback in PHP?
A) To provide the user with confirmation that their data was submitted successfully
B) To display error messages if the data could not be processed
C) To redirect the user to a different page
D) All of the above
Which PHP function is used to redirect the user to a different page?
A) header()
B) redirect()
C) go_to()
D) location()
Which PHP function is used to retrieve the value of a form input field?
A) $_GET
B) $_POST
C) isset()
D) A or B, depending on the method used to submit the form
What is the correct syntax to create a password input field in PHP?
A) <input type="password" name="password_field">
B) <form password="text" name="password_field">
C) <input field="password" name="password_field">
D) None of the above

References:
https://www.w3schools.com/php/php_forms.asp
https://www.geeksforgeeks.org/php-form-handling/
https://www.tutorialspoint.com/php/php_forms.htm
https://www.php.net/manual/en/tutorial.forms.php
https://www.tutorialrepublic.com/php-tutorial/php-form-validation.php

96 | P a g e
Introduction to Web Development (4340704)

Assessment Rubrics:
% of
Criteria Rubrics Marks
point
Excellent (10-8 marks): Completed programs/scripts
correctly as per the requirements.
C1: Adequate (7-6 marks): Completed programs/scripts
Program correctly with approx. 70% requirements.
50 %
Completeness/ Poor (5-4 marks): Completed programs/scripts correctly
Correctness with 70% - 50% requirements.
Unsatisfactory (0-3 marks): Completed programs/ scripts
correctly with less than 50% requirements.
Excellent (10-8 marks): The code is clean, well-organized and
very easy to understand.
Adequate (7-6 marks): The code is fairly easy to read and
C2: understand.
25 %
Readability Poor (5-4 marks): The code is readable only by someone who
knows what it is supposed to be doing.
Unsatisfactory (0-3 marks): The code is poorly organized and
very difficult to understand.
Excellent (10-8 marks):
• Coding standards are followed in complete code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• The Complete code is well-documented with comments
explaining the code.
Adequate (7-6 marks):
• Coding standards are followed in most of the code while
naming variables/functions/ classes, explaining the
C3:
purpose of variables/ functions/classes.
Coding
25 % • Most of the code is documented with comments
Standards/ explaining the code.
Documentation
Poor (5-4 marks):
• Coding standards are followed in very little code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• Very little code is documented with comments
explaining the code.
Unsatisfactory (0-3 marks):
• Coding standards are not followed properly.
• Proper comments are not written explaining the code.
Total Marks for Practical = 0.5 * (Marks of C1) + 0.25 * (Marks of C2) + 0.25 * (Marks of C3)

Signature with Date:

97 | P a g e
Introduction to Web Development (4340704)

Practical No. 9: Session, Cookies


Create web pages to demonstrate passing information using Session.
Write a script to demonstrate storing and retrieving information from cookies.

Objectives:
Sessions and cookies are important concepts in web development, and they have
practical significance in PHP in several ways:
User authentication: Sessions and cookies can be used to authenticate users on a
website. When a user logs in, their session ID can be stored in a cookie, and the
server can verify the ID to ensure that the user is authorized to access certain pages
or features.
Personalization: Sessions and cookies can be used to personalize the user
experience on a website. For example, a session can be used to store the user's
preferred language or theme, and a cookie can be used to remember the user's
login credentials for future visits.
Shopping carts: Sessions and cookies can be used to create and manage shopping
carts on an e-commerce website. The contents of the user's cart can be stored in a
session, and a cookie can be used to remember the user's cart across multiple visits.
Tracking user behaviour: Cookies can be used to track user behaviour on a website,
such as which pages they visit and which links they click. This information can be
used to improve the website's usability and performance.
Security: Sessions and cookies can be used to enhance the security of a website.
For example, a session can be used to prevent CSRF (cross-site request forgery)
attacks, while cookies can be used to prevent XSS (cross-site scripting) attacks.

Relevant Program Outcomes (POs):


Basic and Discipline specific knowledge (PO1): Apply knowledge of basic
mathematics, science and engineering fundamentals and engineering
specialization to solve the Computer Engineering problems.
Problem analysis (PO2): Identify and analyse well-defined Computer Engineering
problems using codified standard methods.
Design/development of solutions (PO3): Design solutions for Computer
Engineering well-defined technical problems and assist with the design of systems
components or processes to meet specified needs.
Engineering Tools, Experimentation and Testing (PO4): Apply modern Computer
Engineering tools and appropriate technique to conduct standard tests and
measurements.
Project Management (PO6): Use engineering management principles individually,
as a team member or a leader to manage projects and effectively communicate
about well-defined engineering activities.

98 | P a g e
Introduction to Web Development (4340704)

Life-long learning (PO7): Ability to analyse individual needs and engage in updating
in the context of technological changes in field of engineering.

Competency and Practical Skills:


This practical is expected to develop the following skills for the industry-identified
competency ‘Develop Interactive Web application using PHP and MySQL’:
Programming skills.
Debugging skills.

Relevant Course Outcomes (COs):


Develop web pages using form controls with validation to collect user inputs in PHP.

Practical Outcomes:
Implement session and cookie to store and manage user data.

Relevant Affective domain Outcomes (ADOs):


Maintain tools and equipments.
Follow Coding standards and practices.
Follow ethical practices.

Prerequisite Theory:
In PHP, sessions and cookies are two mechanisms used to store and manage data
related to a user's interaction with a website or web application.
SESSION
Sessions are a way of storing information on the server about a user's activity on a
website. When a user visits a website, the server assigns them a unique session ID,
which is stored in a cookie on the user's computer. The server then uses this session ID
to keep track of the user's activity as they move around the website. The session data
can include things like user preferences, shopping cart items, or authentication status.
Sessions can be started using the session_start() function and the session data can be
accessed through the $_SESSION superglobal array.
COOKIE
Cookies are small text files that are stored on a user's computer by their web browser.
Cookies are often used to remember user preferences or login information, or to track
user behavior across different pages or sessions. In PHP, cookies can be set using the
setcookie() function. Cookies can have an expiration time, after which they are
automatically deleted, or they can be set to expire when the user closes their browser.
Cookie data can be accessed using the $_COOKIE superglobal array.
COMPARISION
Both sessions and cookies have their advantages and disadvantages. Sessions are
generally more secure because the data is stored on the server, but they can be

99 | P a g e
Introduction to Web Development (4340704)

slower and less flexible. Cookies are faster and more flexible, but they can be less
secure because the data is stored on the user's computer. When using cookies, it's
important to make sure that sensitive information, such as passwords or credit card
numbers, is not stored in the cookie.
In summary, sessions and cookies are two important mechanisms used to store and
manage user-related data in PHP. By understanding how to use these mechanisms
correctly, developers can create more secure and user-friendly web applications.
Examples
Using Session
Start the session using the session_start() function.
<?php
session_start();
>

Set a session variable.


<?php
$_SESSION[‘username’] = ‘Ashish’;
>

Access the session variable on another page.


<?php
session_start();
echo "Welcome " .$_SESSION[‘username’];
>

Using Cookie
1. Set a cookie using the setcookie() function.
<?php
$cookie_name "username";
$cookie_value = "Ashish";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>

2. Access the cookie value.


<?php
if(isset($_COOKIE [$cookie_name])) {
echo "Welcome". $_COOKIE [$cookie_name];
}
?>

100 | P a g e
Introduction to Web Development (4340704)

Note that when using sessions and cookies, it's important to be careful about what
data is stored and how it's accessed, to prevent security issues. For example, sensitive
information like passwords or credit card numbers should never be stored in a cookie
or session.

Resources Required:
Sr.
Instrument /Components Configuration/Specification
No
Processor:
1. Computer System RAM:
Operating System:

2. XAMPP server XAMPP Version:

3. Text Editor Editor:

4. Web Browser Browser:

Source code and Output:


Create web pages to demonstrate passing information using Session.
Source Code:

101 | P a g e
Introduction to Web Development (4340704)

Output:

Write a script to demonstrate storing and retrieving information from cookies.


Source Code:

102 | P a g e
Introduction to Web Development (4340704)

Output:

103 | P a g e
Introduction to Web Development (4340704)

Practical related Quiz:


What is a session in PHP?
A) A way of storing information on the user's computer
B) A way of storing information on the server about a user's activity on a website
C) A way of transferring data between different pages on a website
D) A way of authenticating users on a website
How is a session started in PHP?
A) By setting a cookie on the user's computer
B) By using the start_session() function
C) By setting a session variable using $_SESSION
D) By using the session_start() function
How is data stored in a PHP session?
A) As a cookie on the client side
B) As a file on the server side
C) As a URL parameter
D) As a hidden form field
What is a cookie in PHP?
A) A way of storing information on the user's computer
B) A way of storing information on the server about a user's activity on a website
C) A way of transferring data between different pages on a website
D) A way of authenticating users on a website
How is a cookie set in PHP?
A) By using the setcookie() function
B) By using the start_session() function
C) By setting a cookie variable using $_COOKIE
D) By using the session_start() function
How long can a cookie last in PHP?
A) 1 day
B) 1 week
C) 1 month
D) As long as the user wants it to last
Which of the following is more secure, sessions or cookies?

104 | P a g e
Introduction to Web Development (4340704)

A) Sessions
B) Cookies
C) They are equally secure
D) It depends on the use case
What kind of data should not be stored in a cookie?
A) User preferences
B) Login information
C) Sensitive information like passwords or credit card numbers
D) All of the above can be stored in a cookie
What superglobal array is used to access session data in PHP?
A) $_SESSION
B) $_COOKIE
C) $_REQUEST
D) $_SERVER
What superglobal array is used to access cookie data in PHP?
A) $_SESSION
B) $_COOKIE
C) $_REQUEST
D) $_SERVER
How can you delete a cookie in PHP?
A) By using the setcookie() function with an expiration time in the past
B) By using the unset() function with the cookie variable
C) By using the delete_cookie() function with the cookie name
D) Cookies cannot be deleted once they are set

References:
https://www.php.net/manual/en/features.sessions.php
https://www.php.net/manual/en/function.setcookie.php
https://www.tutorialspoint.com/php/php_sessions.htm
https://www.tutorialspoint.com/php/php_cookies.htm
https://www.w3schools.com/php/php_sessions.asp
https://www.w3schools.com/php/php_cookies.asp
https://www.geeksforgeeks.org/php-sessions/
https://www.geeksforgeeks.org/php-cookies/

105 | P a g e
Introduction to Web Development (4340704)

Assessment Rubrics:
% of
Criteria Rubrics Marks
point
Excellent (10-8 marks): Completed programs/scripts
correctly as per the requirements.
C1: Adequate (7-6 marks): Completed programs/scripts
Program correctly with approx. 70% requirements.
50 %
Completeness/ Poor (5-4 marks): Completed programs/scripts correctly
Correctness with 70% - 50% requirements.
Unsatisfactory (0-3 marks): Completed programs/ scripts
correctly with less than 50% requirements.
Excellent (10-8 marks): The code is clean, well-organized and
very easy to understand.
Adequate (7-6 marks): The code is fairly easy to read and
C2: understand.
25 %
Readability Poor (5-4 marks): The code is readable only by someone who
knows what it is supposed to be doing.
Unsatisfactory (0-3 marks): The code is poorly organized and
very difficult to understand.
Excellent (10-8 marks):
• Coding standards are followed in complete code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• The Complete code is well-documented with comments
explaining the code.
Adequate (7-6 marks):
• Coding standards are followed in most of the code while
naming variables/functions/ classes, explaining the
C3:
purpose of variables/ functions/classes.
Coding
25 % • Most of the code is documented with comments
Standards/ explaining the code.
Documentation
Poor (5-4 marks):
• Coding standards are followed in very little code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• Very little code is documented with comments
explaining the code.
Unsatisfactory (0-3 marks):
• Coding standards are not followed properly.
• Proper comments are not written explaining the code.
Total Marks for Practical = 0.5 * (Marks of C1) + 0.25 * (Marks of C2) + 0.25 * (Marks of C3)

Signature with Date:

106 | P a g e
Introduction to Web Development (4340704)

Practical No. 10: Database


Create a web page that reads employee information using a form and stores it in
the database.
Create a web page for employee log-in.
Write a script to upload an image to the server.
After an employee log in, create a home web page that displays basic employee
information.
Create a web page to delete employee profiles from the database.
Create a web page that allows employees to change their password.

Objectives:
Databases are an essential part of many web applications developed with PHP. Here are
some practical reasons why databases are important in PHP development:
Data storage: Databases provide a structured way to store and organize data for
PHP applications. This makes it easy to manage and retrieve data using SQL queries.
Scalability: Databases can handle large amounts of data and high traffic volumes,
making it a great choice for PHP applications that need to grow and scale over time.
Security: Databases provide strong security features to protect data and prevent
unauthorized access. This includes user authentication, data encryption, and role-
based access control.
Data analysis: Databases can be used to perform complex data analysis and
generate reports. This is useful for PHP applications that need to process large
amounts of data and extract meaningful insights.
Data synchronization: Databases can be used to synchronize data between
different systems and applications. This is useful for PHP applications that need to
integrate with other systems and exchange data in real-time.
Overall, databases are an essential tool for PHP developers, providing reliable data
storage, scalability, security, data analysis, and data synchronization. They play a crucial
role in many web applications, and their importance cannot be overstated.

Relevant Program Outcomes (POs):


Basic and Discipline specific knowledge (PO1): Apply knowledge of basic
mathematics, science and engineering fundamentals and engineering
specialization to solve the Computer Engineering problems.
Problem analysis (PO2): Identify and analyse well-defined Computer Engineering
problems using codified standard methods.
Design/development of solutions (PO3): Design solutions for Computer
Engineering well-defined technical problems and assist with the design of systems
components or processes to meet specified needs.

107 | P a g e
Introduction to Web Development (4340704)

Engineering Tools, Experimentation and Testing (PO4): Apply modern Computer


Engineering tools and appropriate technique to conduct standard tests and
measurements.
Project Management (PO6): Use engineering management principles individually,
as a team member or a leader to manage projects and effectively communicate
about well-defined engineering activities.
Life-long learning (PO7): Ability to analyse individual needs and engage in updating
in the context of technological changes in field of engineering.

Competency and Practical Skills:


This practical is expected to develop the following skills for the industry-identified
competency ‘Develop Interactive Web application using PHP and MySQL’:
Programming skills.
Debugging skills.

Relevant Course Outcomes (COs):


Develop and host interactive websites using PHP and MySQL database.

Practical Outcomes:
Implement various database operations using PHP script.

Relevant Affective domain Outcomes (ADOs):


Maintain tools and equipments.
Follow Coding standards and practices.
Follow ethical practices.

Prerequisite Theory:
MySQL is a popular relational database management system that is commonly used in
web development with PHP. Here are some MySQL functions that can be used in PHP
to interact with MySQL databases:
mysqli_connect() - This function is used to establish a connection to a MySQL
database server.
mysqli_query() - This function is used to execute a MySQL query on a connected
database.
mysqli_fetch_array() - This function is used to fetch the result of a MySQL query as
an array.
mysqli_insert_id() - This function is used to get the auto-generated ID of the last
inserted record in a table.
mysqli_real_escape_string() - This function is used to escape special characters in
a string to prevent SQL injection attacks.

108 | P a g e
Introduction to Web Development (4340704)

mysqli_num_rows() - This function is used to get the number of rows returned by


a MySQL query.
mysqli_error() - This function is used to get the error message associated with the
last MySQL operation.
mysqli_close() - This function is used to close the connection to a MySQL database
server.
These are just a few examples of the MySQL functions that can be used in PHP. There
are many other functions available for working with MySQL databases in PHP, and
their usage depends on the specific needs of your application.
Example
Assuming we have a MySQL database with a table named "users" that has columns
"id", "username", and "password", we can use PHP to perform various operations on
this table.
1. Connect to the MySQL database:

<?php
$host = "localhost"; $username = "db_user";
$password = "db_password";
$dbname = "my_database";

// Create connection
$conn = mysqli_connect($host, $username, $password, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: mysqli_connect_error());
}
echo "Connected successfully";
?>

2. Insert a new user into the "users" table:

109 | P a g e
Introduction to Web Development (4340704)

<?php
$username = "john_doe";
$password = "my_password";

// Escape special characters in the username and password to


// prevent SQL injection
$username = mysqli_real_escape_string($conn, $username);
$password mysqli_real_escape_string($conn, $password); =

// Create and execute the SQL query to insert a new user


$sql = "INSERT INTO users (username, password) VALUES
('$username', '$password')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>

3. Retrieve all users from the "users" table:

<?php
// Create and execute the SQL query to retrieve all users
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);

// Check if any rows were returned


if (mysqli_num_rows($result) > 0) {
// Output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: ". $row["id"] . " - Username: " .
$row["username"] . "<br>";
}
}
else {
echo "0 results";
}
?>

110 | P a g e
Introduction to Web Development (4340704)

4. Update the password for a specific user in the "users" table:

<?php
$username "ashish";
$new_password = "new_password";

// Escape special characters in the username and new password to


// prevent SQL injec
$username = mysqli_real_escape_string($conn, $username);
$new_password = mysqli_real_escape_string($conn, $new_password);

// Create and execute the SQL query to update the password for a
// specific user
$sql = "UPDATE users SET password='$new_password' WHERE
username='$username'
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
}
else {
echo "Error updating record: mysqli_error($conn);
}
?>

5. Delete a specific user from the "users" table:

<?php
$username "ashish";

// Escape special characters in the username to prevent SQL


// injection
$username = mysqli_real_escape_string($conn, $username);

// Create and execute the SQL query to delete a specific user


$sql = "DELETE FROM users WHERE username='$username'
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
}
else {
echo "Error deleting record: mysqli_error($conn);
}
?>

111 | P a g e
Introduction to Web Development (4340704)

Resources Required:
Sr.
Instrument /Components Configuration/Specification
No
Processor:
1. Computer System RAM:
Operating System:

2. XAMPP server XAMPP Version:

3. Text Editor Editor:

4. Web Browser Browser:

Source code and Output:


Create a web page that reads employee information using a form and stores it in
the database.
Source Code:

112 | P a g e
Introduction to Web Development (4340704)

Output:

Create a web page for employee log-in.


Source Code:

113 | P a g e
Introduction to Web Development (4340704)

Output:

Write a script to upload an image to the server.


Source Code:

114 | P a g e
Introduction to Web Development (4340704)

Output:

After an employee log in, create a home web page that displays basic employee
information.
Source Code:

115 | P a g e
Introduction to Web Development (4340704)

Output:

Create a web page to delete employee profiles from the database.


Source Code:

116 | P a g e
Introduction to Web Development (4340704)

Output:

Create a web page that allows employees to change their password.


Source Code:

117 | P a g e
Introduction to Web Development (4340704)

Output:

Practical related Quiz:


What does "mysqli" stand for?
A) MySQL Improved
B) My Structured Query Language Interface
C) My SQL Interaction
D) None of the above
What is the function used to establish a connection to a MySQL database with
mysqli?
A) mysqli_select_db()
B) mysqli_query()
C) mysqli_connect()
D) None of the above
Which of the following is a valid way to fetch a single row of data using mysqli?
A) mysqli_fetch_row()
B) mysqli_fetch_array()
C) mysqli_fetch_assoc()
D) All of the above
What is the function used to execute a prepared statement with mysqli?
118 | P a g e
Introduction to Web Development (4340704)

A) mysqli_stmt_execute()
B) mysqli_execute_stmt()
C) mysqli_stmt_query()
D) None of the above
Which of the following is used to retrieve the result set of a query executed with
mysqli?
A) mysqli_fetch_row()
B) mysqli_fetch_array()
C) mysqli_fetch_assoc()
D) All of the above
What is the function used to close a connection to a MySQL database with mysqli?
A) mysqli_close()
B) mysqli_disconnect()
C) mysqli_terminate()
D) None of the above
Which of the following is used to retrieve the number of rows affected by a query
executed with mysqli?
A) mysqli_affected_rows()
B) mysqli_num_rows()
C) Both A and B
D) None of the above
Which of the following methods is used to check for errors in a MySQLi database
query in PHP?
A) mysqli_errno()
B) mysqli_error()
C) mysqli_connect_errno()
D) All of the above

References:
https://www.php.net/manual/en/book.mysql.php
https://www.w3schools.com/php/php_mysql_intro.asp
https://www.tutorialspoint.com/php/php_mysql.htm
https://phpdelusions.net/mysqli
https://www.geeksforgeeks.org/mysqli-procedural-functions
https://www.guru99.com/mysql-php-and-other-database-access-methods.html

119 | P a g e
Introduction to Web Development (4340704)

Assessment Rubrics:
% of
Criteria Rubrics Marks
point
Excellent (10-8 marks): Completed programs/scripts
correctly as per the requirements.
C1: Adequate (7-6 marks): Completed programs/scripts
Program correctly with approx. 70% requirements.
50 %
Completeness/ Poor (5-4 marks): Completed programs/scripts correctly
Correctness with 70% - 50% requirements.
Unsatisfactory (0-3 marks): Completed programs/ scripts
correctly with less than 50% requirements.
Excellent (10-8 marks): The code is clean, well-organized and
very easy to understand.
Adequate (7-6 marks): The code is fairly easy to read and
C2: understand.
25 %
Readability Poor (5-4 marks): The code is readable only by someone who
knows what it is supposed to be doing.
Unsatisfactory (0-3 marks): The code is poorly organized and
very difficult to understand.
Excellent (10-8 marks):
• Coding standards are followed in complete code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• The Complete code is well-documented with comments
explaining the code.
Adequate (7-6 marks):
• Coding standards are followed in most of the code while
naming variables/functions/ classes, explaining the
C3:
purpose of variables/ functions/classes.
Coding
25 % • Most of the code is documented with comments
Standards/ explaining the code.
Documentation
Poor (5-4 marks):
• Coding standards are followed in very little code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• Very little code is documented with comments
explaining the code.
Unsatisfactory (0-3 marks):
• Coding standards are not followed properly.
• Proper comments are not written explaining the code.
Total Marks for Practical = 0.5 * (Marks of C1) + 0.25 * (Marks of C2) + 0.25 * (Marks of C3)

Signature with Date:

120 | P a g e
Introduction to Web Development (4340704)

Practical No. 11: Email, PDF, JSON


Write a script to generate a salary slip for an employee in PDF format.
Write a script to send an email.
Write a script to convert an associative array into JSON string format and vice versa.

Objectives:
Email, PDF, and JSON are three distinct types of data formats that can be used in PHP
for various practical purposes.
Email: PHP provides built-in email functions that allow developers to send and
receive emails using different protocols such as SMTP, IMAP, and POP3. Email is
widely used for communication purposes in various web applications, such as
sending verification emails, password reset links, newsletters, and order
confirmations.
PDF: PDF is a popular file format used for creating and sharing documents that can
be viewed on different devices and platforms. PHP provides various libraries and
tools for generating and manipulating PDF documents, such as FPDF, TCPDF, and
mPDF. PDFs are often used for generating invoices, receipts, reports, and other
types of documents in web applications.
JSON: JSON (JavaScript Object Notation) is a lightweight data interchange format
that is easy to read and write for humans and machines. JSON is often used for
exchanging data between client-side and server-side applications using AJAX
(Asynchronous JavaScript and XML) and RESTful (Representational State Transfer)
APIs. PHP provides built-in functions for encoding and decoding JSON data, such as
json_encode() and json_decode().

Relevant Program Outcomes (POs):


Basic and Discipline specific knowledge (PO1): Apply knowledge of basic
mathematics, science and engineering fundamentals and engineering
specialization to solve the Computer Engineering problems.
Problem analysis (PO2): Identify and analyse well-defined Computer Engineering
problems using codified standard methods.
Design/development of solutions (PO3): Design solutions for Computer
Engineering well-defined technical problems and assist with the design of systems
components or processes to meet specified needs.
Engineering Tools, Experimentation and Testing (PO4): Apply modern Computer
Engineering tools and appropriate technique to conduct standard tests and
measurements.
Project Management (PO6): Use engineering management principles individually,
as a team member or a leader to manage projects and effectively communicate
about well-defined engineering activities.

121 | P a g e
Introduction to Web Development (4340704)

Life-long learning (PO7): Ability to analyse individual needs and engage in updating
in the context of technological changes in field of engineering.

Competency and Practical Skills:


This practical is expected to develop the following skills for the industry-identified
competency ‘Develop Interactive Web application using PHP and MySQL’:
Programming skills.
Debugging skills.

Relevant Course Outcomes (COs):


Develop and host interactive websites using PHP and MySQL database.

Practical Outcomes:
Implement Email, PDF and JSON facility for data exchange and document
generation using PHP script.

Relevant Affective domain Outcomes (ADOs):


Maintain tools and equipments.
Follow Coding standards and practices.
Follow ethical practices.

Prerequisite Theory:
Email
Email is a common communication tool used in web development, and PHP provides
built-in functions and libraries to send and receive emails. Here are the basic steps to
send an email in PHP.
• Configure the SMTP server settings
• Set up the email headers
• Compose the email message
Example
$to = '[email protected]';
$subject = 'Test email';
$message = 'Hello, this is a test email!';

$headers = 'From: [email protected]' . "\r\n" .


'Reply-To: [email protected]' . "\r\n" .
'MIME-Version: 1.0' . "\r\n" .
'Content-type: text/html; charset=iso-8859-1' . "\r\n" .
'X-Mailer: PHP/'. phpversion();

mail($to, $subject, $message, $headers);

122 | P a g e
Introduction to Web Development (4340704)

PDF
PDF (Portable Document Format) is a commonly used document format that allows for
easy sharing and printing of documents. PHP provides several libraries and functions
that allow for the creation and manipulation of PDF documents. Here are the basic steps
to create a PDF document in PHP:
• Install a PDF library: There are several PDF libraries available for PHP, such as FPDF,
TCPDF, and DOMPDF. You need to install and configure a PDF library to generate the
PDF document.
• Create a PDF object: Once you have installed a PDF library, you can create a PDF
object to represent the document. This object contains methods and properties for
adding content to the PDF document, such as text, images, tables, and other
elements.
• Add content to the PDF document: You can use the methods provided by the PDF
library to add content to the PDF document. For example, you can use the SetFont()
method to set the font style, Cell() method to add text to the document, and Image()
method to add images to the document.
• Output the PDF document: Once you have added all the content to the PDF
document, you can output the document to the browser or save it to a file. The PDF
library provides methods to output the PDF document in various formats, such as
PDF, HTML, or image.
Here is an example code snippet to create a PDF document using the FPDF library in
PHP:

<?php
require('fpdf/fpdf.php');

$pdf new FPDF(); =


$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10, 'Hello World!');
$pdf->Output();
?>

JSON
JSON (JavaScript Object Notation) is a lightweight data interchange format that is
commonly used for exchanging data between web applications. PHP provides several
built-in functions and libraries to encode and decode JSON data. Here are the basic
steps to work with JSON data in PHP:
Encode PHP data into JSON format: To encode PHP data into JSON format, you can use
the json_encode() function. This function converts a PHP object or array into a JSON
string.

123 | P a g e
Introduction to Web Development (4340704)

$person = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);

$json = json_encode($person);
echo $json;

In this example, we have defined a PHP array person and encoded it into a JSON string
using the json_encode() function. The output of the code will be:

{"name":"John","age":30,"city":"New York"}

Resources Required:
Sr.
Instrument /Components Configuration/Specification
No
Processor:
1. Computer System RAM:
Operating System:

2. XAMPP server XAMPP Version:

3. Text Editor Editor:

4. Web Browser Browser:

Source code and Output:


Write a script to generate a salary slip for an employee in PDF format.
Source Code:

124 | P a g e
Introduction to Web Development (4340704)

Output:

125 | P a g e
Introduction to Web Development (4340704)

Write a script to send an email.


Source Code:

Output:

126 | P a g e
Introduction to Web Development (4340704)

Write a script to convert an associative array into JSON string format and vice versa.
Source Code:

Output:

127 | P a g e
Introduction to Web Development (4340704)

Practical related Quiz:


Which PHP function can be used to send an email with an attachment?
A) mail()
B) sendmail()
C) imap_send()
D) None of the above
Which PHP function is used to set the email headers?
A) SetHeader()
B) add_header()
C) Header()
D) None of the above
Which of the following is a valid way to attach a file to an email message in PHP?
A) Using the attach() function
B) Using the addAttachment() function
C) Using the include() function
D) None of the above
Which PHP library can be used to generate PDF documents?
A) JSON
B) cURL
C) FPDF
D) XML
Which of the following functions is used to create a new FPDF object in PHP?
A) new PDF()
B) new FPDF()
C) create PDF()
D) create FPDF()
Which PHP library can be used to generate PDF documents with complex layouts
and styles?
A) FPDF
B) TCPDF
C) DOMPDF
D) All of the above
Which of the following methods is used to add an image to a PDF document in
FPDF?

128 | P a g e
Introduction to Web Development (4340704)

A) AddImage()
B) Image()
C) InsertImage()
D) None of the above
Which PHP library has better support for HTML to PDF conversion?
A) FPDF
B) TCPDF
C) Dompdf
D) None of the above
Which PHP function is used to encode a PHP array or object into a JSON string?
A) json_encode()
B) json_decode()
C) json_parse()
D) None of the above
Which PHP function can be used to decode a JSON string into a PHP object or array?
A) json_encode()
B) json_decode()
C) serialize()
D) unserialize()
Which of the following PHP functions can be used to check if a JSON string is valid?
A) json_encode()
B) json_decode()
C) json_last_error()
D) None of the above

References:
https://www.php.net/manual/en/function.mail.php
https://www.tutorialspoint.com/php/php_sending_emails.htm
https://www.sitepoint.com/generate-pdfs-php/
https://www.geeksforgeeks.org/how-to-generate-pdf-file-using-php/
https://www.php.net/manual/en/function.json-encode.php
https://www.w3schools.com/js/js_json_php.asp

129 | P a g e
Introduction to Web Development (4340704)

Assessment Rubrics:
% of
Criteria Rubrics Marks
point
Excellent (10-8 marks): Completed programs/scripts
correctly as per the requirements.
C1: Adequate (7-6 marks): Completed programs/scripts
Program correctly with approx. 70% requirements.
50 %
Completeness/ Poor (5-4 marks): Completed programs/scripts correctly
Correctness with 70% - 50% requirements.
Unsatisfactory (0-3 marks): Completed programs/ scripts
correctly with less than 50% requirements.
Excellent (10-8 marks): The code is clean, well-organized and
very easy to understand.
Adequate (7-6 marks): The code is fairly easy to read and
C2: understand.
25 %
Readability Poor (5-4 marks): The code is readable only by someone who
knows what it is supposed to be doing.
Unsatisfactory (0-3 marks): The code is poorly organized and
very difficult to understand.
Excellent (10-8 marks):
• Coding standards are followed in complete code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• The Complete code is well-documented with comments
explaining the code.
Adequate (7-6 marks):
• Coding standards are followed in most of the code while
naming variables/functions/ classes, explaining the
C3:
purpose of variables/ functions/classes.
Coding
25 % • Most of the code is documented with comments
Standards/ explaining the code.
Documentation
Poor (5-4 marks):
• Coding standards are followed in very little code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• Very little code is documented with comments
explaining the code.
Unsatisfactory (0-3 marks):
• Coding standards are not followed properly.
• Proper comments are not written explaining the code.
Total Marks for Practical = 0.5 * (Marks of C1) + 0.25 * (Marks of C2) + 0.25 * (Marks of C3)

Signature with Date:

130 | P a g e
Introduction to Web Development (4340704)

Practical No. 12: Simple Web Application


Create a simple web application for Employee Management with 3-4 web pages
and host it using cPanel and Filezilla.

Objectives:
Development of simple web application as mini-project will give an experience of
problem-solving along with group members, by using knowledge and under the
guidance of a faculty. Mini-project will help students to develop different skills such as:
team work, researching on a topic, problem solving, time management, planning, code
development, testing and documentation.

Relevant Program Outcomes (POs):


Basic and Discipline specific knowledge (PO1): Apply knowledge of basic
mathematics, science and engineering fundamentals and engineering
specialization to solve the Computer Engineering problems.
Problem analysis (PO2): Identify and analyse well-defined Computer Engineering
problems using codified standard methods.
Design/development of solutions (PO3): Design solutions for Computer
Engineering well-defined technical problems and assist with the design of systems
components or processes to meet specified needs.
Engineering Tools, Experimentation and Testing (PO4): Apply modern Computer
Engineering tools and appropriate technique to conduct standard tests and
measurements.
Project Management (PO6): Use engineering management principles individually,
as a team member or a leader to manage projects and effectively communicate
about well-defined engineering activities.
Life-long learning (PO7): Ability to analyse individual needs and engage in updating
in the context of technological changes in field of engineering.

Competency and Practical Skills:


This practical is expected to develop the following skills for the industry-identified
competency ‘Develop Interactive Web application using PHP and MySQL’:
Programming skills.
Debugging skills.
Project management skills.

Relevant Course Outcomes (COs):


Develop PHP scripts using variables, operators and control structures.
Develop PHP scripts using arrays and functions.
Develop PHP scripts by applying object oriented concepts.

131 | P a g e
Introduction to Web Development (4340704)

Develop web pages using form controls with validation to collect user inputs in PHP.
Develop and host interactive websites using PHP and MySQL database.

Practical Outcomes:
Develop simple application using PHP and MySQL.

Relevant Affective domain Outcomes (ADOs):


Maintain tools and equipments.
Follow Coding standards and practices.
Follow ethical practices.

Resources Required:
Sr.
Instrument /Components Configuration/Specification
No
Processor:
1. Computer System RAM:
Operating System:

2. XAMPP server XAMPP Version:

3. Text Editor Editor:

4. Web Browser Browser:

Source code and Output:


Source Code:

132 | P a g e
Introduction to Web Development (4340704)

133 | P a g e
Introduction to Web Development (4340704)

134 | P a g e
Introduction to Web Development (4340704)

Output:

135 | P a g e
Introduction to Web Development (4340704)

Assessment Rubrics:
% of
Criteria Rubrics Marks
point
Excellent (10-8 marks): Completed project/scripts correctly
as per the requirements.
C1: Adequate (7-6 marks): Completed project /scripts correctly
Project with approx. 70% requirements.
50 %
Completeness/ Poor (5-4 marks): Completed project /scripts correctly with
Correctness 70% - 50% requirements.
Unsatisfactory (0-3 marks): Completed project/ scripts
correctly with less than 50% requirements.
Excellent (10-8 marks): The code is clean, well-organized and
very easy to understand.
Adequate (7-6 marks): The code is fairly easy to read and
C2: understand.
25 %
Readability Poor (5-4 marks): The code is readable only by someone who
knows what it is supposed to be doing.
Unsatisfactory (0-3 marks): The code is poorly organized and
very difficult to understand.
Excellent (10-8 marks):
• Coding standards are followed in complete code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• The Complete code is well-documented with comments
explaining the code.
Adequate (7-6 marks):
• Coding standards are followed in most of the code while
naming variables/functions/ classes, explaining the
C3:
purpose of variables/ functions/classes.
Coding
25 % • Most of the code is documented with comments
Standards/ explaining the code.
Documentation
Poor (5-4 marks):
• Coding standards are followed in very little code while
naming variables/functions/ classes, explaining the
purpose of variables/ functions/classes.
• Very little code is documented with comments
explaining the code.
Unsatisfactory (0-3 marks):
• Coding standards are not followed properly.
• Proper comments are not written explaining the code.
Total Marks for Practical = 0.5 * (Marks of C1) + 0.25 * (Marks of C2) + 0.25 * (Marks of C3)

Signature with Date:

136 | P a g e

You might also like